identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/78182648/blibli-go/blob/master/app/admin/main/search/service/log_test.go
Github Open Source
Open Source
MIT
2,022
blibli-go
78182648
Go
Code
189
693
package service import ( "context" "testing" "go-common/app/admin/main/search/model" . "github.com/smartystreets/goconvey/convey" ) func Test_LogAudit(t *testing.T) { var ( err error c = context.Background() p = &model.LogParams{ Bsp: &model.BasicSearchParams{ AppID: "log_audit", }, } params map[string][]string ) Convey("LogAudit", t, WithService(func(s *Service) { business, ok := svr.Check("log_audit", 0) if !ok { return } _, err = s.LogAudit(c, params, p, business) So(err, ShouldBeNil) })) } //func Test_LogAuditGroupBy(t *testing.T) { // var ( // err error // c = context.Background() // p = &model.LogParams{ // Bsp: &model.BasicSearchParams{ // AppID: "log_audit_group", // }, // } // params map[string][]string // ) // params = map[string][]string{ // "group": {"oid"}, // } // Convey("LogAuditGroupBy", t, WithService(func(s *Service) { // indexMapping, indexFmt, ok := svr.Check("log_audit", p.Business) // if !ok { // return // } // _, err = s.LogAuditGroupBy(c, params, p, indexMapping, indexFmt) // Printf("---------%v", err) // So(err, ShouldBeNil) // })) //} func Test_LogUserAction(t *testing.T) { var ( err error c = context.Background() p = &model.LogParams{ Bsp: &model.BasicSearchParams{ AppID: "log_user_action", }, } params map[string][]string ) Convey("LogUserAction", t, WithService(func(s *Service) { business, ok := svr.Check("log_user_action", 0) if !ok { return } _, err = s.LogUserAction(c, params, p, business) So(err, ShouldBeNil) })) }
7,805
https://github.com/brantwills/CleanArchitecture/blob/master/CleanArchitecture.Application/Customers/Queries/GetCustomerDetail/GetCustomerDetailQueryHandler.cs
Github Open Source
Open Source
MIT
2,018
CleanArchitecture
brantwills
C#
Code
45
182
using CleanArchitecture.Domain.Entities; using CleanArchitecture.Domain.Interfaces; using MediatR; using System.Threading; using System.Threading.Tasks; namespace CleanArchitecture.Application.Customers.Queries.GetCustomerDetail { public class GetCustomerDetailQueryHandler : IRequestHandler<GetCustomerDetailQuery, Customer> { private ICustomerRepository _readStore; public GetCustomerDetailQueryHandler(ICustomerRepository readStore) { _readStore = readStore; } public async Task<Customer> Handle(GetCustomerDetailQuery request, CancellationToken cancellationToken) { return await _readStore.GetCustomerById(request.Id); } } }
50,247
https://github.com/vidal-community/jax-rs-linker/blob/master/jax-rs-linker-processor/src/test/java/fr/vidal/oss/jax_rs_linker/parser/ParameterVisitorTest.java
Github Open Source
Open Source
MIT
2,022
jax-rs-linker
vidal-community
Java
Code
126
587
package fr.vidal.oss.jax_rs_linker.parser; import com.google.testing.compile.CompilationRule; import fr.vidal.oss.jax_rs_linker.model.PathParameter; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.ws.rs.PathParam; import java.util.Collection; import java.util.NoSuchElementException; import static fr.vidal.oss.jax_rs_linker.functions.ElementToPathParameter.ELEMENT_INTO_PATH_PARAMETER; import static fr.vidal.oss.jax_rs_linker.functions.SetterToPathParameter.SETTER_TO_PATH_PARAMETER; import static org.assertj.core.api.Assertions.assertThat; public class ParameterVisitorTest { @Rule public CompilationRule compilation = new CompilationRule(); private Elements elements; @Before public void prepare() { elements = compilation.getElements(); } @Test public void extracts_path_parameters_from_bean_parameters() { TypeElement resource = elements.getTypeElement("parameter_visitor.StupidResource"); Element method = extract(resource, "doSomething"); ParameterVisitor<PathParameter> visitor = new ParameterVisitor<>( compilation.getTypes(), new AnnotatedElementMapping<>( PathParam.class, ELEMENT_INTO_PATH_PARAMETER::apply, SETTER_TO_PATH_PARAMETER::apply ) ); Collection<PathParameter> parameters = visitor.visit(method); assertThat(parameters).extracting("name") .containsOnly("{foo}", "{bar}", "{baz}"); } private Element extract(TypeElement resource, String methodName) { for (Element element : elements.getAllMembers(resource)) { if (element.getSimpleName().contentEquals(methodName)) { return element; } } throw new NoSuchElementException( String.format("No method <%s> found for <%s>", methodName, resource.getQualifiedName()) ); } }
26,941
https://github.com/daniel-perry/rt/blob/master/reference_implementation/cs6620-prog6/Time.h
Github Open Source
Open Source
MIT
null
rt
daniel-perry
C
Code
23
67
#ifndef Time_h #define Time_h class Time { public: static double currentSeconds(); private: Time(); Time(const Time&); Time& operator=(const Time&); static void initialize(); }; #endif
46,498
https://github.com/alim-firejack/Firejack-Platform/blob/master/platform/src/main/webapp/js/net/firejack/platform/core/component/tinymce/plugins/imagemanager/langs/en_dlg.js
Github Open Source
Open Source
Apache-2.0
2,014
Firejack-Platform
alim-firejack
JavaScript
Code
5
52
tinyMCE.addI18n('en.photo_dlg',{title:'Add Photo Attachment'});tinyMCE.addI18n('en.video_dlg',{title:'Add Video Attachment'});
6,029
https://github.com/maco2035/console/blob/master/assets/js/graphql/apiKeys.js
Github Open Source
Open Source
Apache-2.0
2,022
console
maco2035
JavaScript
Code
25
68
import { gql } from '@apollo/client'; export const ALL_API_KEYS = gql` query ApiKeysQuery { apiKeys { id name role inserted_at user active } } `
19,440
https://github.com/gar1t/ChicagoML/blob/master/Makefile
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference, Apache-2.0
2,020
ChicagoML
gar1t
Makefile
Code
15
42
build: bundle exec jekyll build serve: bundle exec jekyll serve clean: rm -rf _site .sass-cache
23,003
https://github.com/z88dk/z88dk/blob/master/libsrc/target/cpc/cpcrslib/cpc_rsx.asm
Github Open Source
Open Source
ClArtistic
2,023
z88dk
z88dk
Assembly
Code
253
743
; ; Amstrad CPC library ; Call a RSX/Bar command ; ; int cpc_rsx(char *cmd, ...) ; ; It accepts the command name (it will be adapted "on the fly"), ; and a list of pointers to variables. ; ; $Id: cpc_rsx.asm,v 1.5 2017-01-02 19:59:39 aralbrec Exp $ ; SECTION code_clib PUBLIC cpc_rsx PUBLIC _cpc_rsx INCLUDE "target/cpc/def/cpcfirm.def" .cpc_rsx ._cpc_rsx ;call firmware ;defw kl_rom_walk push ix ;save callers ld ix,4 add ix,sp push ix dec a push af ; number of parameters add a ld e,a ld d,0 add ix,de ld l,(ix+0) ld h,(ix+1) ; cmd ld de,cmd_buff push de ; cmd_buff .loop ld a,(hl) cp 'a' jr c,nolowr cp 'z'+1 jr nc,nolowr and $df ; to upper .nolowr ld (de),a inc hl inc de or a jr nz,loop dec de dec de ld a,(de) or $80 ; string termination ld (de),a pop hl ; cmd_buff call firmware defw kl_find_command jr nc,notfound ld (rsx_command),hl ; store address of function ld a,c ld (rsx_command+2),a ; store "rom select" of function pop af ; number of parameters pop ix ; parameter address list rst $18 ; KL FAR CALL defw rsx_command ld hl,0 jr c,rsx_ok bit 6,a jr nz,harderr and $1f ; mask out the "error already reported" bit .harderr ld l,a .rsx_ok pop ix ;restore caller ret .notfound pop bc ; params stuff.. pop bc ; ..balance stack ld hl,-1 ; Error: command not found pop ix ;restore caller ret SECTION bss_clib .rsx_command defw 0 defb 0 .cmd_buff defs 12 ; max command name lenght
1,004
https://github.com/Sashakoleso/zero-sahsa/blob/master/src/sass/styles.scss
Github Open Source
Open Source
MIT
null
zero-sahsa
Sashakoleso
SCSS
Code
23
120
/* Import partials below */ @import './normalize.scss'; @import './helpers/fonts.scss'; @import './helpers/variables.scss'; @import './components/header.scss'; @import './components/section_1.scss'; @import './components/section_2.scss'; @import './components/section_3.scss'; @import './components/section_4.scss'; @import './components/footer.scss';
2,953
https://github.com/kimihan/soma/blob/master/application/controllers/app_gerencial/geral.php
Github Open Source
Open Source
MIT
null
soma
kimihan
PHP
Code
76
270
<?php require_once(APPPATH.'libraries/MY_Controller.php'); class Geral extends MY_Controller { /** * Método construtor da classe * * @access public */ function __construct() { parent::__construct(); } function consulta_cep($cep) { //criando o recurso cURL $cr = curl_init(); //definindo a url de busca curl_setopt($cr, CURLOPT_URL, "https://viacep.com.br/ws/".$cep."/json/"); curl_setopt($cr, CURLOPT_RETURNTRANSFER, true); //definindo uma variável para receber o conteúdo da página... $retorno = curl_exec($cr); //fechando-o para liberação do sistema. curl_close($cr); //fechamos o recurso e liberamos o sistema... //mostrando o conteúdo... echo $retorno; } }
6,479
https://github.com/chinayou25/Ray/blob/master/Ray.Core/Message/MessageTypeMapper.cs
Github Open Source
Open Source
Apache-2.0
2,018
Ray
chinayou25
C#
Code
84
287
using System; using System.Collections.Generic; using System.Linq; namespace Ray.Core.Message { public static class MessageTypeMapper { static MessageTypeMapper() { var assemblyList = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic); var eventType = typeof(IMessage); foreach (var assembly in assemblyList) { var allType = assembly.GetExportedTypes().Where(t => eventType.IsAssignableFrom(t)); foreach (var type in allType) { EventTypeDict.Add(type.FullName, type); } } } static Dictionary<string, Type> EventTypeDict = new Dictionary<string, Type>(); /// <summary> /// 根据typecode获取Type对象 /// </summary> /// <param name="typeCode">Type对象的唯一标识</param> /// <returns></returns> public static Type GetType(string typeCode) { EventTypeDict.TryGetValue(typeCode, out var type); return type; } } }
34,374
https://github.com/muxanick/scala-native-java-stubs/blob/master/javax/swing/text/JTextComponent.scala
Github Open Source
Open Source
MIT
null
scala-native-java-stubs
muxanick
Scala
Code
3,913
7,486
package javax.swing.text import java.awt.{Color, Component, Component.AccessibleAWTComponent, ComponentOrientation, Container, Container.AccessibleAWTContainer, Dimension, Insets, Point, Rectangle} import java.awt.event.{InputMethodEvent, InputMethodListener, MouseEvent} import java.awt.im.InputMethodRequests import java.awt.print.Printable import java.io.{Reader, Writer} import java.lang.{Object, String} import java.text.MessageFormat import javax.accessibility.{Accessible, AccessibleAction, AccessibleContext, AccessibleEditableText, AccessibleExtendedText, AccessibleRole, AccessibleStateSet, AccessibleText, AccessibleTextSequence} import javax.print.PrintService import javax.print.attribute.PrintRequestAttributeSet import javax.swing.{Action, DropMode, JComponent, JComponent.AccessibleJComponent, KeyStroke, Scrollable, TransferHandler.DropLocation} import javax.swing.event.{CaretEvent, CaretListener, DocumentEvent, DocumentListener} import javax.swing.plaf.TextUI import scala.scalanative.annotation.stub /** JTextComponent is the base class for swing text * components. It tries to be compatible with the * java.awt.TextComponent class * where it can reasonably do so. Also provided are other services * for additional flexibility (beyond the pluggable UI and bean * support). * You can find information on how to use the functionality * this class provides in * General Rules for Using Text Components, * a section in The Java Tutorial. * * * Caret Changes * * The caret is a pluggable object in swing text components. * Notification of changes to the caret position and the selection * are sent to implementations of the CaretListener * interface that have been registered with the text component. * The UI will install a default caret unless a customized caret * has been set. * By default the caret tracks all the document changes * performed on the Event Dispatching Thread and updates it's position * accordingly if an insertion occurs before or at the caret position * or a removal occurs before the caret position. DefaultCaret * tries to make itself visible which may lead to scrolling * of a text component within JScrollPane. The default caret * behavior can be changed by the DefaultCaret.setUpdatePolicy(int) method. * * Note: Non-editable text components also have a caret though * it may not be painted. * * Commands * * Text components provide a number of commands that can be used * to manipulate the component. This is essentially the way that * the component expresses its capabilities. These are expressed * in terms of the swing Action interface, * using the TextAction implementation. * The set of commands supported by the text component can be * found with the getActions() method. These actions * can be bound to key events, fired from buttons, etc. * * Text Input * * The text components support flexible and internationalized text input, using * keymaps and the input method framework, while maintaining compatibility with * the AWT listener model. * * A Keymap lets an application bind key * strokes to actions. * In order to allow keymaps to be shared across multiple text components, they * can use actions that extend TextAction. * TextAction can determine which JTextComponent * most recently has or had focus and therefore is the subject of * the action (In the case that the ActionEvent * sent to the action doesn't contain the target text component as its source). * * The input method framework * lets text components interact with input methods, separate software * components that preprocess events to let users enter thousands of * different characters using keyboards with far fewer keys. * JTextComponent is an active client of * the framework, so it implements the preferred user interface for interacting * with input methods. As a consequence, some key events do not reach the text * component because they are handled by an input method, and some text input * reaches the text component as committed text within an InputMethodEvent instead of as a key event. * The complete text input is the combination of the characters in * keyTyped key events and committed text in input method events. * * The AWT listener model lets applications attach event listeners to * components in order to bind events to actions. Swing encourages the * use of keymaps instead of listeners, but maintains compatibility * with listeners by giving the listeners a chance to steal an event * by consuming it. * * Keyboard event and input method events are handled in the following stages, * with each stage capable of consuming the event: * * * * Stage * KeyEvent * InputMethodEvent * 1. * input methods * (generated here) * 2. * focus manager * * * * 3. * registered key listeners * registered input method listeners * * 4. * * input method handling in JTextComponent * * 5. keymap handling using the current keymap * 6. keyboard handling in JComponent (e.g. accelerators, component navigation, etc.) * * * * * To maintain compatibility with applications that listen to key * events but are not aware of input method events, the input * method handling in stage 4 provides a compatibility mode for * components that do not process input method events. For these * components, the committed text is converted to keyTyped key events * and processed in the key event pipeline starting at stage 3 * instead of in the input method event pipeline. * * By default the component will create a keymap (named DEFAULT_KEYMAP) * that is shared by all JTextComponent instances as the default keymap. * Typically a look-and-feel implementation will install a different keymap * that resolves to the default keymap for those bindings not found in the * different keymap. The minimal bindings include: * * inserting content into the editor for the * printable keys. * removing content with the backspace and del * keys. * caret movement forward and backward * * * Model/View Split * * The text components have a model-view split. A text component pulls * together the objects used to represent the model, view, and controller. * The text document model may be shared by other views which act as observers * of the model (e.g. a document may be shared by multiple components). * * * * * The model is defined by the Document interface. * This is intended to provide a flexible text storage mechanism * that tracks change during edits and can be extended to more sophisticated * models. The model interfaces are meant to capture the capabilities of * expression given by SGML, a system used to express a wide variety of * content. * Each modification to the document causes notification of the * details of the change to be sent to all observers in the form of a * DocumentEvent which allows the views to stay up to date with the model. * This event is sent to observers that have implemented the * DocumentListener * interface and registered interest with the model being observed. * * Location Information * * The capability of determining the location of text in * the view is provided. There are two methods, modelToView(int) * and viewToModel(java.awt.Point) for determining this information. * * Undo/Redo support * * Support for an edit history mechanism is provided to allow * undo/redo operations. The text component does not itself * provide the history buffer by default, but does provide * the UndoableEdit records that can be used in conjunction * with a history buffer to provide the undo/redo support. * The support is provided by the Document model, which allows * one to attach UndoableEditListener implementations. * * Thread Safety * * The swing text components provide some support of thread * safe operations. Because of the high level of configurability * of the text components, it is possible to circumvent the * protection provided. The protection primarily comes from * the model, so the documentation of AbstractDocument * describes the assumptions of the protection provided. * The methods that are safe to call asynchronously are marked * with comments. * * Newlines * * For a discussion on how newlines are handled, see * DefaultEditorKit. * * * Printing support * * Several print methods are provided for basic * document printing. If more advanced printing is needed, use the * getPrintable(java.text.MessageFormat, java.text.MessageFormat) method. * * * * Warning: * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans™ * has been added to the java.beans package. * Please see XMLEncoder. */ abstract class JTextComponent extends JComponent with Scrollable with Accessible { /** Creates a new JTextComponent. */ @stub def this() = ??? /** This class implements accessibility support for the * JTextComponent class. It provides an implementation of * the Java Accessibility API appropriate to menu user-interface elements. * * Warning: * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans™ * has been added to the java.beans package. * Please see XMLEncoder. */ class AccessibleJTextComponent extends JComponent.AccessibleJComponent with AccessibleText with CaretListener with DocumentListener with AccessibleAction with AccessibleEditableText with AccessibleExtendedText { /** Constructs an AccessibleJTextComponent. */ @stub def this() = ??? /** Handles caret updates (fire appropriate property change event, * which are AccessibleContext.ACCESSIBLE_CARET_PROPERTY and * AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY). */ @stub def caretUpdate(e: CaretEvent): Unit = ??? /** Handles document remove (fire appropriate property change event, * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). */ @stub def changedUpdate(e: DocumentEvent): Unit = ??? /** Cuts the text between two indices into the system clipboard. */ @stub def cut(startIndex: Int, endIndex: Int): Unit = ??? /** Deletes the text between two indices */ @stub def delete(startIndex: Int, endIndex: Int): Unit = ??? /** Performs the specified Action on the object */ @stub def doAccessibleAction(i: Int): Boolean = ??? /** Gets the AccessibleAction associated with this object that supports * one or more actions. */ @stub def getAccessibleAction(): AccessibleAction = ??? /** Returns the number of accessible actions available in this object * If there are more than one, the first one is considered the * "default" action of the object. */ @stub def getAccessibleActionCount(): Int = ??? /** Returns a description of the specified action of the object. */ @stub def getAccessibleActionDescription(i: Int): String = ??? /** Returns the AccessibleEditableText interface for * this text component. */ @stub def getAccessibleEditableText(): AccessibleEditableText = ??? /** Gets the role of this object. */ @stub def getAccessibleRole(): AccessibleRole = ??? /** Gets the state set of the JTextComponent. */ @stub def getAccessibleStateSet(): AccessibleStateSet = ??? /** Get the AccessibleText associated with this object. */ @stub def getAccessibleText(): AccessibleText = ??? /** Returns the String after a given index. */ @stub def getAfterIndex(part: Int, index: Int): String = ??? /** Returns the String at a given index. */ @stub def getAtIndex(part: Int, index: Int): String = ??? /** Returns the String before a given index. */ @stub def getBeforeIndex(part: Int, index: Int): String = ??? /** Returns the zero-based offset of the caret. */ @stub def getCaretPosition(): Int = ??? /** Returns the AttributeSet for a given character (at a given index). */ @stub def getCharacterAttribute(i: Int): AttributeSet = ??? /** Determines the bounding box of the character at the given * index into the string. */ @stub def getCharacterBounds(i: Int): Rectangle = ??? /** Returns the number of characters (valid indices) */ @stub def getCharCount(): Int = ??? /** Given a point in local coordinates, return the zero-based index * of the character under that Point. */ @stub def getIndexAtPoint(p: Point): Int = ??? /** Returns the portion of the text that is selected. */ @stub def getSelectedText(): String = ??? /** Returns the end offset within the selected text. */ @stub def getSelectionEnd(): Int = ??? /** Returns the start offset within the selected text. */ @stub def getSelectionStart(): Int = ??? /** Returns the Rectangle enclosing the text between * two indicies. */ @stub def getTextBounds(startIndex: Int, endIndex: Int): Rectangle = ??? /** Returns the text string between two indices. */ @stub def getTextRange(startIndex: Int, endIndex: Int): String = ??? /** Returns the AccessibleTextSequence after a given * index. */ @stub def getTextSequenceAfter(part: Int, index: Int): AccessibleTextSequence = ??? /** Returns the AccessibleTextSequence at a given * index. */ @stub def getTextSequenceAt(part: Int, index: Int): AccessibleTextSequence = ??? /** Returns the AccessibleTextSequence before a given * index. */ @stub def getTextSequenceBefore(part: Int, index: Int): AccessibleTextSequence = ??? /** Inserts the specified string at the given index */ @stub def insertTextAtIndex(index: Int, s: String): Unit = ??? /** Handles document insert (fire appropriate property change event * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). */ @stub def insertUpdate(e: DocumentEvent): Unit = ??? /** Pastes the text from the system clipboard into the text * starting at the specified index. */ @stub def paste(startIndex: Int): Unit = ??? /** Handles document remove (fire appropriate property change event, * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). */ @stub def removeUpdate(e: DocumentEvent): Unit = ??? /** Replaces the text between two indices with the specified * string. */ @stub def replaceText(startIndex: Int, endIndex: Int, s: String): Unit = ??? /** Selects the text between two indices. */ @stub def selectText(startIndex: Int, endIndex: Int): Unit = ??? /** Sets attributes for the text between two indices. */ @stub def setAttributes(startIndex: Int, endIndex: Int, as: AttributeSet): Unit = ??? /** Sets the text contents to the specified string. */ @stub def setTextContents(s: String): Unit = ??? } /** Adds a caret listener for notification of any changes * to the caret. */ def addCaretListener(listener: CaretListener): Unit /** Adds the specified input method listener to receive * input method events from this component. */ def addInputMethodListener(l: InputMethodListener): Unit /** Transfers the currently selected range in the associated * text model to the system clipboard, leaving the contents * in the text model. */ def copy(): Unit /** Transfers the currently selected range in the associated * text model to the system clipboard, removing the contents * from the model. */ def cut(): Unit /** Notifies all listeners that have registered interest for * notification on this event type. */ protected def fireCaretUpdate(e: CaretEvent): Unit /** Gets the AccessibleContext associated with this * JTextComponent. */ def getAccessibleContext(): AccessibleContext /** Fetches the command list for the editor. */ def getActions(): Array[Action] /** Fetches the caret that allows text-oriented navigation over * the view. */ def getCaret(): Caret /** Fetches the current color used to render the * caret. */ def getCaretColor(): Color /** Returns an array of all the caret listeners * registered on this text component. */ def getCaretListeners(): Array[CaretListener] /** Returns the position of the text insertion caret for the * text component. */ def getCaretPosition(): Int /** Fetches the current color used to render the * disabled text. */ def getDisabledTextColor(): Color /** Fetches the model associated with the editor. */ def getDocument(): Document /** Returns whether or not automatic drag handling is enabled. */ def getDragEnabled(): Boolean /** Returns the location that this component should visually indicate * as the drop location during a DnD operation over the component, * or null if no location is to currently be shown. */ def getDropLocation(): JTextComponent.DropLocation /** Returns the drop mode for this component. */ def getDropMode(): DropMode /** Returns the key accelerator that will cause the receiving * text component to get the focus. */ def getFocusAccelerator(): Char /** Fetches the object responsible for making highlights. */ def getHighlighter(): Highlighter /** Gets the input method request handler which supports * requests from input methods for this component. */ def getInputMethodRequests(): InputMethodRequests /** Fetches the keymap currently active in this text * component. */ def getKeymap(): Keymap /** Returns the margin between the text component's border and * its text. */ def getMargin(): Insets /** Returns the NavigationFilter. */ def getNavigationFilter(): NavigationFilter /** Returns the preferred size of the viewport for a view component. */ def getPreferredScrollableViewportSize(): Dimension /** Returns a Printable to use for printing the content of this * JTextComponent. */ def getPrintable(headerFormat: MessageFormat, footerFormat: MessageFormat): Printable /** Components that display logical rows or columns should compute * the scroll increment that will completely expose one block * of rows or columns, depending on the value of orientation. */ def getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int): Int /** Returns true if a viewport should always force the height of this * Scrollable to match the height of the viewport. */ def getScrollableTracksViewportHeight(): Boolean /** Returns true if a viewport should always force the width of this * Scrollable to match the width of the viewport. */ def getScrollableTracksViewportWidth(): Boolean /** Components that display logical rows or columns should compute * the scroll increment that will completely expose one new row * or column, depending on the value of orientation. */ def getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int): Int /** Returns the selected text contained in this * TextComponent. */ def getSelectedText(): String /** Fetches the current color used to render the * selected text. */ def getSelectedTextColor(): Color /** Fetches the current color used to render the * selection. */ def getSelectionColor(): Color /** Returns the selected text's end position. */ def getSelectionEnd(): Int /** Returns the selected text's start position. */ def getSelectionStart(): Int /** Returns the text contained in this TextComponent. */ def getText(): String /** Fetches a portion of the text represented by the * component. */ def getText(offs: Int, len: Int): String /** Returns the string to be used as the tooltip for event. */ def getToolTipText(event: MouseEvent): String /** Fetches the user-interface factory for this text-oriented editor. */ def getUI(): TextUI /** Returns the boolean indicating whether this * TextComponent is editable or not. */ def isEditable(): Boolean /** Converts the given location in the model to a place in * the view coordinate system. */ def modelToView(pos: Int): Rectangle /** Moves the caret to a new position, leaving behind a mark * defined by the last time setCaretPosition was * called. */ def moveCaretPosition(pos: Int): Unit /** Returns a string representation of this JTextComponent. */ protected def paramString(): String /** Transfers the contents of the system clipboard into the * associated text model. */ def paste(): Unit /** A convenience print method that displays a print dialog, and then * prints this JTextComponent in interactive mode with no * header or footer text. */ def print(): Boolean /** A convenience print method that displays a print dialog, and then * prints this JTextComponent in interactive mode with * the specified header and footer text. */ def print(headerFormat: MessageFormat, footerFormat: MessageFormat): Boolean /** Prints the content of this JTextComponent. */ def print(headerFormat: MessageFormat, footerFormat: MessageFormat, showPrintDialog: Boolean, service: PrintService, attributes: PrintRequestAttributeSet, interactive: Boolean): Boolean /** Processes input method events occurring on this component by * dispatching them to any registered * InputMethodListener objects. */ protected def processInputMethodEvent(e: InputMethodEvent): Unit /** Initializes from a stream. */ def read(in: Reader, desc: Any): Unit /** Removes a caret listener. */ def removeCaretListener(listener: CaretListener): Unit /** Notifies this component that it no longer has a parent component. */ def removeNotify(): Unit /** Replaces the currently selected content with new content * represented by the given string. */ def replaceSelection(content: String): Unit /** Restores composed text previously saved by saveComposedText. */ protected def restoreComposedText(): Unit /** Saves composed text around the specified position. */ protected def saveComposedText(pos: Int): Boolean /** Selects the text between the specified start and end positions. */ def select(selectionStart: Int, selectionEnd: Int): Unit /** Selects all the text in the TextComponent. */ def selectAll(): Unit /** Sets the caret to be used. */ def setCaret(c: Caret): Unit /** Sets the current color used to render the caret. */ def setCaretColor(c: Color): Unit /** Sets the position of the text insertion caret for the * TextComponent. */ def setCaretPosition(position: Int): Unit /** Sets the language-sensitive orientation that is to be used to order * the elements or text within this component. */ def setComponentOrientation(o: ComponentOrientation): Unit /** Sets the current color used to render the * disabled text. */ def setDisabledTextColor(c: Color): Unit /** Associates the editor with a text document. */ def setDocument(doc: Document): Unit /** Turns on or off automatic drag handling. */ def setDragEnabled(b: Boolean): Unit /** Sets the drop mode for this component. */ def setDropMode(dropMode: DropMode): Unit /** Sets the specified boolean to indicate whether or not this * TextComponent should be editable. */ def setEditable(b: Boolean): Unit /** Sets the key accelerator that will cause the receiving text * component to get the focus. */ def setFocusAccelerator(aKey: Char): Unit /** Sets the highlighter to be used. */ def setHighlighter(h: Highlighter): Unit /** Sets the keymap to use for binding events to * actions. */ def setKeymap(map: Keymap): Unit /** Sets margin space between the text component's border * and its text. */ def setMargin(m: Insets): Unit /** Sets the NavigationFilter. */ def setNavigationFilter(filter: NavigationFilter): Unit /** Sets the current color used to render the selected text. */ def setSelectedTextColor(c: Color): Unit /** Sets the current color used to render the selection. */ def setSelectionColor(c: Color): Unit /** Sets the selection end to the specified position. */ def setSelectionEnd(selectionEnd: Int): Unit /** Sets the selection start to the specified position. */ def setSelectionStart(selectionStart: Int): Unit /** Sets the text of this TextComponent * to the specified text. */ def setText(t: String): Unit /** Sets the user-interface factory for this text-oriented editor. */ def setUI(ui: TextUI): Unit /** Reloads the pluggable UI. */ def updateUI(): Unit /** Converts the given place in the view coordinate system * to the nearest representative location in the model. */ def viewToModel(pt: Point): Int /** Stores the contents of the model into the given * stream. */ def write(out: Writer): Unit } object JTextComponent { /** Represents a drop location for JTextComponents. */ final object DropLocation extends TransferHandler.DropLocation { /** Returns the bias for the drop index. */ @stub def getBias(): Position.Bias = ??? /** Returns the index where dropped data should be inserted into the * associated component. */ @stub def getIndex(): Int = ??? /** Returns a string representation of this drop location. */ @stub def toString(): String = ??? } /** Binding record for creating key bindings. * * Warning: * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans™ * has been added to the java.beans package. * Please see XMLEncoder. */ object KeyBinding extends Object { /** Creates a new key binding. */ @stub def apply(key: KeyStroke, actionName: String) = ??? /** The name of the action for the key. */ @stub val actionName: String = ??? /** The key. */ @stub val key: KeyStroke = ??? } /** The default keymap that will be shared by all * JTextComponent instances unless they * have had a different keymap set. */ @stub val DEFAULT_KEYMAP: String = ??? /** The bound property name for the focus accelerator. */ @stub val FOCUS_ACCELERATOR_KEY: String = ??? /** Adds a new keymap into the keymap hierarchy. */ @stub def addKeymap(nm: String, parent: Keymap): Keymap = ??? /** Fetches a named keymap previously added to the document. */ @stub def getKeymap(nm: String): Keymap = ??? /** * Loads a keymap with a bunch of * bindings. */ @stub def loadKeymap(map: Keymap, bindings: Array[JTextComponent.KeyBinding], actions: Array[Action]): Unit = ??? /** Removes a named keymap previously added to the document. */ @stub def removeKeymap(nm: String): Keymap = ??? }
47,174
https://github.com/liupeng110/letv/blob/master/src/main/java/com/letv/core/bean/HomeBlock.java
Github Open Source
Open Source
Apache-2.0
2,017
letv
liupeng110
Java
Code
300
981
package com.letv.core.bean; import android.util.Log; import com.letv.core.bean.channel.ChannelNavigation; import com.letv.core.bean.channel.RedField; import com.letv.core.utils.BaseTypeUtils; import com.letv.datastatistics.util.DataConstant.StaticticsVersion2Constatnt.StaticticsName; import java.util.ArrayList; public class HomeBlock implements LetvBaseBean, Comparable<HomeBlock> { private static final int HORIZONTAL_COUNT = 2; private static final long serialVersionUID = 1; public ArrayList<AlbumInfo> albumList; public String area; public ArrayList<HomeChildItemData> arrayHomeChildItem; public String blockname; public String bucket; public String cid; public String cms_num; public String contentStyle; public int contentType; public String date; public String fragId; public int index; public String isLock; public String isPage; public ArrayList<HomeMetaData> list; public int mGroupCardId = -1; public boolean mHasStatistics = false; public int num; public ArrayList<RedField> redField; public String redirectCid; public RedirectData redirectData; public String redirectPageId; public String redirectType; public String redirectUrl; public String redirectVideoType; public String reid; public ArrayList<HomeBlock> sub_block; public ArrayList<ChannelNavigation> tabsNavigation; public String type; public int videoNum; public void toHomeChildItemData() { if (this.list != null && this.list.size() > 0) { int count; this.arrayHomeChildItem = new ArrayList(); if (this.list.size() % 2 == 0) { count = this.list.size(); } else { count = this.list.size() + 1; } int i = 0; while (i < count) { HomeChildItemData homeChildItemData = new HomeChildItemData(this); if (this.list.size() > i) { homeChildItemData.childItemData[0] = (HomeMetaData) this.list.get(i); homeChildItemData.childItemData[0].index = i; Log.v("toHomeChildItemData", ">>childItemData1 : " + homeChildItemData.childItemData[0]); } if (this.list.size() > i + 1) { homeChildItemData.childItemData[1] = (HomeMetaData) this.list.get(i + 1); homeChildItemData.childItemData[1].index = i + 1; Log.v("toHomeChildItemData", ">>childItemData222 : " + homeChildItemData.childItemData[1]); } i += 2; if (homeChildItemData.childItemData[1] != null || homeChildItemData.childItemData[0] != null) { this.arrayHomeChildItem.add(homeChildItemData); } } } } public int compareTo(HomeBlock another) { if (BaseTypeUtils.stoi(this.isLock) == BaseTypeUtils.stoi(another.isLock)) { return this.index - another.index; } return BaseTypeUtils.stoi(another.isLock) - BaseTypeUtils.stoi(this.isLock); } public String toString() { return "blockname=" + this.blockname + StaticticsName.STATICTICS_NAM_CID + this.cid + "area" + this.area + "bucket=" + this.bucket + "cms_num=" + this.cms_num + "redirectData=" + this.redirectData + "contentStyle=" + this.contentStyle + "list=" + this.list; } }
8,767
https://github.com/zwcloud/ZWCloud.DwriteCairo/blob/master/DwriteCairo/DirectWriteCairoTextRenderer/DirectWriteCairoTextRenderer.cs
Github Open Source
Open Source
Apache-2.0
null
ZWCloud.DwriteCairo
zwcloud
C#
Code
129
564
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace ZWCloud.DWriteCairo { [ComImport] [Guid("ef8a8135-5cc6-45fe-8825-c5a0724eb819")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IDWriteTextRenderer { } internal class DirectWriteCairoTextRenderer :IDisposable { public static DirectWriteCairoTextRenderer Create() { return new DirectWriteCairoTextRenderer(CreateTextRender()); } #region COM internals #region COM interface creation public static IDirectWriteCairoTextRenderer CreateTextRender() { object render = Internal.NativeMethods.DwriteCairoCreateTextRender(new Guid(IID_IDirectWriteCairoTextRenderer)); Debug.Assert(render != null, "IDirectWriteCairoTextRenderer creating failed."); return (IDirectWriteCairoTextRenderer)render; } #endregion #region COM Method public IDirectWriteCairoTextRenderer comObject; public const string IID_IDirectWriteCairoTextRenderer = "f5b028d5-86fd-4332-ad5e-e86cf11cecd4"; [ComImport] [Guid(IID_IDirectWriteCairoTextRenderer)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IDirectWriteCairoTextRenderer : IDWriteTextRenderer { } private DirectWriteCairoTextRenderer(IDirectWriteCairoTextRenderer obj) { this.comObject = obj; } ~DirectWriteCairoTextRenderer() { this.Release(); } private void Release() { if (this.comObject != null) { Marshal.ReleaseComObject(this.comObject); this.comObject = null; } } #region COM Method wrappers //None #endregion #endregion #endregion #region Implementation of IDisposable public void Dispose() { this.Release(); GC.SuppressFinalize(this); } #endregion } }
28,135
https://github.com/farzadz/addressbook/blob/master/src/main/java/com/farzadz/addressbook/config/SwaggerUIConfig.java
Github Open Source
Open Source
MIT
null
addressbook
farzadz
Java
Code
26
128
package com.farzadz.addressbook.config; import static com.farzadz.addressbook.config.RestEndpointConfig.SWAGGER_BASE_PATH; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class SwaggerUIConfig { @RequestMapping(value = {SWAGGER_BASE_PATH, "/"}) public String api() { return "redirect:/swagger-ui/"; } }
19,348
https://github.com/fe6/icon/blob/master/packages/vue/src/icons/byted-headwear.tsx
Github Open Source
Open Source
MIT
2,022
icon
fe6
TSX
Code
89
415
/** @format */ import { ISvgIconProps, IconWrapper } from '../runtime'; export const BytedHeadwear = IconWrapper( 'byted-headwear', false, (props: ISvgIconProps) => ( <svg width={props.size} height={props.size} viewBox="0 0 48 48" fill="none"> <path d="M12.4167 43C10.095 40.0682 8 35.7788 8 31C8 22.1634 15.1634 15 24 15C32.8366 15 40 22.1634 40 31C40 35.7788 37.905 40.0682 35.5833 43" stroke={props.colors[0]} stroke-width={props.strokeWidth} stroke-linecap={props.strokeLinecap} stroke-linejoin={props.strokeLinejoin} /> <path d="M34 13.5L43 5L40 17L35 18L34 13.5Z" fill={props.colors[1]} stroke={props.colors[0]} stroke-width={props.strokeWidth} stroke-linecap={props.strokeLinecap} stroke-linejoin={props.strokeLinejoin} /> <path d="M14 13.5L5 5L8 17L13 18L14 13.5Z" fill={props.colors[1]} stroke={props.colors[0]} stroke-width={props.strokeWidth} stroke-linecap={props.strokeLinecap} stroke-linejoin={props.strokeLinejoin} /> </svg> ), ); export default BytedHeadwear;
6,610
https://github.com/JLY2015/obkv-table-client-java/blob/master/src/test/java/com/alipay/oceanbase/rpc/protocol/payload/impl/column/ObGeneratedColumnTest.java
Github Open Source
Open Source
MulanPSL-1.0
2,022
obkv-table-client-java
JLY2015
Java
Code
183
601
/*- * #%L * OBKV Table Client Framework * %% * Copyright (C) 2021 OceanBase * %% * OBKV Table Client Framework is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * #L% */ package com.alipay.oceanbase.rpc.protocol.payload.impl.column; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static com.alipay.oceanbase.rpc.protocol.payload.impl.ObCollationType.CS_TYPE_UTF8MB4_GENERAL_CI; import static com.alipay.oceanbase.rpc.protocol.payload.impl.ObObjType.ObVarcharType; import static org.junit.Assert.fail; public class ObGeneratedColumnTest { @Test public void testEntity() { ObGeneratedColumnSubStrFunc subStr = new ObGeneratedColumnSubStrFunc(); subStr.setParameters(new ArrayList<Object>() { { add("K"); add(1); add(4); } }); ObGeneratedColumn column = new ObGeneratedColumn("k_prefix", 0, ObVarcharType, CS_TYPE_UTF8MB4_GENERAL_CI, subStr); Assert.assertEquals("k_prefix", column.getColumnName()); List<String> refColumnNames = new ArrayList<String>(); refColumnNames.add("K"); Assert.assertEquals(refColumnNames, column.getRefColumnNames()); Assert.assertEquals(0, column.getIndex()); Assert.assertEquals(ObVarcharType, column.getObObjType()); Assert.assertEquals(CS_TYPE_UTF8MB4_GENERAL_CI, column.getObCollationType()); try { column.evalValue(); fail(); } catch (IllegalArgumentException e) { } } }
32,279
https://github.com/lokesh-coder/lesyjs/blob/master/packages/misc/pilot-ui/src/app/modules/query/pipes/name-pipe.ts
Github Open Source
Open Source
MIT
2,021
lesyjs
lokesh-coder
TypeScript
Code
38
117
import { Pipe, PipeTransform } from "@angular/core"; @Pipe({ name: "title" }) export class TitlePipe implements PipeTransform { transform(text: string): string { const result = text .replace(/([A-Z])/g, " $1") .replace(/-/g, " ") .toLowerCase(); return result.charAt(0).toUpperCase() + result.slice(1); } }
10,581
https://github.com/azerodeveloper/AzeroMobile/blob/master/app/build.gradle
Github Open Source
Open Source
Apache-2.0
2,021
AzeroMobile
azerodeveloper
Gradle
Code
296
2,160
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' apply from: 'version.gradle' android { compileSdkVersion 28 defaultConfig { applicationId appinfo.appId minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName appinfo.appVersionName manifestPlaceholders = [ "versionName": "${versionName}", appId: applicationId ] testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" ndk { abiFilters "armeabi-v7a" } } signingConfigs { debug{ keyAlias 'talaile' keyPassword 'android' storeFile file("../keystore/talaile.keystore") storePassword 'android' } release{ } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } debug{ signingConfig signingConfigs.debug } } androidExtensions { experimental = true } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = JavaVersion.VERSION_1_8.toString() } repositories { flatDir { dirs 'libs' } } dynamicFeatures = [] } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.core:core-ktx:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.arasthel:spannedgridlayoutmanager:3.0.2' implementation 'com.google.android.material:material:1.0.0-rc01' implementation 'androidx.recyclerview:recyclerview:1.0.0' implementation "androidx.viewpager2:viewpager2:1.0.0" implementation 'com.github.bumptech.glide:glide:4.10.0' implementation 'jp.wasabeef:glide-transformations:4.1.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' kapt 'com.github.bumptech.glide:compiler:4.10.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' implementation(name: 'denoise-release', ext: 'aar') implementation(name: 'azero-release', ext: 'aar') implementation(name: 'appintro-release', ext: 'aar') implementation(name: 'android-vad-v1.0.0-release', ext: 'aar') implementation 'com.alibaba:fastjson:1.2.14' implementation 'log4j:log4j:1.2.17' implementation 'com.loopj.android:android-async-http:1.4.9' implementation 'cz.msebera.android:httpclient:4.3.6' def exoplayerVersion = '2.10.5' implementation "com.google.android.exoplayer:exoplayer-core:${exoplayerVersion}" implementation "com.google.android.exoplayer:exoplayer-dash:${exoplayerVersion}" implementation "com.google.android.exoplayer:exoplayer-smoothstreaming:${exoplayerVersion}" implementation "com.google.android.exoplayer:exoplayer-hls:${exoplayerVersion}" implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2' implementation 'com.googlecode.soundlibs:jlayer:1.0.1.4' implementation 'com.google.code.gson:gson:2.8.2' implementation 'com.squareup.okhttp3:okhttp:3.11.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0' implementation 'com.squareup.okio:okio:2.2.2' implementation 'com.github.promeg:tinypinyin:2.0.3' def lifecycle_version = "1.1.1" implementation "android.arch.lifecycle:extensions:$lifecycle_version" implementation "com.android.support:palette-v7:28.0.0" //permission implementation 'pub.devrel:easypermissions:3.0.0' implementation 'cn.dxjia:imagetextbutton:1.0.0' //跑步功能 implementation 'com.amap.api:location:latest.integration' implementation 'com.amap.api:map2d:latest.integration' // implementation project(':obex') implementation project(':lib-todaystepcounter') implementation project(':lib-todayrunrecord') implementation project(':lib-surrogate') implementation project(':lib-phoneareacodelibray') // implementation(name: 'obex_unitylib_1.0.8', ext: 'aar') // add for room implementation "android.arch.persistence.room:runtime:1.1.1" // room 配合 RxJava implementation "android.arch.persistence.room:rxjava2:1.1.1" kapt "android.arch.persistence.room:compiler:1.1.1" implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.navigation:navigation-fragment-ktx:2.2.0' implementation 'androidx.navigation:navigation-ui-ktx:2.2.0' implementation 'com.rengwuxian.materialedittext:library:2.1.4' // implementation 'com.github.AppIntro:AppIntro:5.1.0' //微信sdk api 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+' implementation "com.squareup.retrofit2:converter-gson:2.7.1" // 友盟统计SDK // implementation "com.umeng.umsdk:analytics:8.1.3" //基础组件库依赖(必须) Push 6.1.0版本必须升级新版本Common SDK implementation 'com.umeng.umsdk:common:9.1.0' implementation 'com.umeng.umsdk:utdid:1.5.2' implementation 'com.umeng.umsdk:asms:1.1.3' implementation 'com.umeng.umsdk:crash:0.0.4' //友盟push相关依赖(必须) implementation 'com.umeng.umsdk:push:6.1.0' implementation 'com.umeng.umsdk:alicloud-httpdns:1.2.5' implementation 'com.umeng.umsdk:alicloud-utils:1.1.5' implementation 'com.umeng.umsdk:alicloud_beacon:1.0.1' implementation 'com.umeng.umsdk:agoo-accs:3.3.8.8-open-fix2' implementation 'com.umeng.umsdk:agoo_networksdk:3.5.5' implementation 'com.umeng.umsdk:agoo_tlog:3.0.0.17' implementation 'com.umeng.umsdk:agoo_tnet4android:3.1.14.9' }
6,410
https://github.com/plummera/CodeIgnite-Form/blob/master/application/views/templates/header.php
Github Open Source
Open Source
MIT
null
CodeIgnite-Form
plummera
PHP
Code
90
594
<html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="CodeIgniter GtechNY PHP"> <meta name="author" content="Anthony T. Plummer"> <link rel="icon" href="../../favicon.ico"> <title>CodeIgniter For Fun & Profit</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <link rel="stylesheet" href="<?php echo base_url(); ?>build/styles_core.min.css" /> <link rel="stylesheet" href="<?php echo base_url(); ?>build/styles.min.css" /> </head> <body> <div id="header"><h1>GtechNY</h1></div> <nav class="navbar navbar-dark bg-inverse"> <a class="navbar-brand" href="#">GtechNY</a> <ul class="nav navbar-nav"> <li class="nav-item"><a class="nav-link" href="<?php echo site_url('/'); ?>">Home</a></li> <li class="nav-item"><a class="nav-link" href="<?php echo site_url('users/view'); ?>">View</a></li> <li class="nav-item"><a class="nav-link" href="<?php echo site_url('users/index'); ?>">Upload</a></li> </ul> </nav>
43,843
https://github.com/AhsanulQalbi/product-url-generator/blob/master/server/validation/admin-cms/role.validation.js
Github Open Source
Open Source
Apache-2.0
2,021
product-url-generator
AhsanulQalbi
JavaScript
Code
155
524
import db from '../../../config/sequelize'; const { Role } = db; const { check } = require('express-validator'); const Sequelize = require('sequelize'); const validate = (method) => { switch (method) { case 'create': { return [ check('name').not().isEmpty() .withMessage((value, { req }) => req.t('validation.not_empty', { variable: req.t('variable.name'), })) .bail() .custom((value, { req }) => Role .findOne({ where: { name: { [Sequelize.Op.iLike]: req.body.name, }, }, }).then((role) => { if (role) { throw new Error(req.t('validation.exist', { variable: req.t('variable.role'), key: req.t('variable.name'), value, })); } return value; })), ]; } case 'update': { return [ check('name').optional().not().isEmpty() .withMessage((value, { req }) => req.t('validation.not_empty', { variable: req.t('variable.name'), })) .bail() .custom((value, { req }) => Role .findOne({ where: { id: { [Sequelize.Op.ne]: parseInt(req.params.id, 10), }, name: { [Sequelize.Op.iLike]: req.body.name, }, }, }).then((role) => { if (role) { throw new Error(req.t('validation.exist', { variable: req.t('variable.role'), key: req.t('variable.name'), value, })); } return value; })), ]; } default: { return []; } } }; module.exports = { validate, };
22,798
https://github.com/elasticio/dun-and-bradstreet-component/blob/master/src/main/generated-java/com/dnb/services/firmorgaphics/Assessment.java
Github Open Source
Open Source
Apache-2.0
null
dun-and-bradstreet-component
elasticio
Java
Code
513
1,695
package com.dnb.services.firmorgaphics; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Assessment complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Assessment"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="HistoryRatingText" type="{http://services.dnb.com/FirmographicsProductServiceV2.0}DNBDecodedStringType" minOccurs="0"/> * &lt;element name="CommercialCreditScore" type="{http://services.dnb.com/FirmographicsProductServiceV2.0}CommercialCreditScoreType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="MarketingSegmentationClusterValue" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}int"> * &lt;totalDigits value="2"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="USPatriotActComplianceRiskScore" type="{http://services.dnb.com/FirmographicsProductServiceV2.0}USPatriotActComplianceRiskScore" minOccurs="0"/> * &lt;element name="ProofOfRightCount" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Assessment", namespace = "http://services.dnb.com/FirmographicsProductServiceV2.0", propOrder = { "historyRatingText", "commercialCreditScore", "marketingSegmentationClusterValue", "usPatriotActComplianceRiskScore", "proofOfRightCount" }) public class Assessment { @XmlElement(name = "HistoryRatingText") protected DNBDecodedStringType historyRatingText; @XmlElement(name = "CommercialCreditScore") protected List<CommercialCreditScoreType> commercialCreditScore; @XmlElement(name = "MarketingSegmentationClusterValue") protected Integer marketingSegmentationClusterValue; @XmlElement(name = "USPatriotActComplianceRiskScore") protected USPatriotActComplianceRiskScore usPatriotActComplianceRiskScore; @XmlElement(name = "ProofOfRightCount") protected Integer proofOfRightCount; /** * Gets the value of the historyRatingText property. * * @return * possible object is * {@link DNBDecodedStringType } * */ public DNBDecodedStringType getHistoryRatingText() { return historyRatingText; } /** * Sets the value of the historyRatingText property. * * @param value * allowed object is * {@link DNBDecodedStringType } * */ public void setHistoryRatingText(DNBDecodedStringType value) { this.historyRatingText = value; } /** * Gets the value of the commercialCreditScore property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the commercialCreditScore property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCommercialCreditScore().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CommercialCreditScoreType } * * */ public List<CommercialCreditScoreType> getCommercialCreditScore() { if (commercialCreditScore == null) { commercialCreditScore = new ArrayList<CommercialCreditScoreType>(); } return this.commercialCreditScore; } /** * Gets the value of the marketingSegmentationClusterValue property. * * @return * possible object is * {@link Integer } * */ public Integer getMarketingSegmentationClusterValue() { return marketingSegmentationClusterValue; } /** * Sets the value of the marketingSegmentationClusterValue property. * * @param value * allowed object is * {@link Integer } * */ public void setMarketingSegmentationClusterValue(Integer value) { this.marketingSegmentationClusterValue = value; } /** * Gets the value of the usPatriotActComplianceRiskScore property. * * @return * possible object is * {@link USPatriotActComplianceRiskScore } * */ public USPatriotActComplianceRiskScore getUSPatriotActComplianceRiskScore() { return usPatriotActComplianceRiskScore; } /** * Sets the value of the usPatriotActComplianceRiskScore property. * * @param value * allowed object is * {@link USPatriotActComplianceRiskScore } * */ public void setUSPatriotActComplianceRiskScore(USPatriotActComplianceRiskScore value) { this.usPatriotActComplianceRiskScore = value; } /** * Gets the value of the proofOfRightCount property. * * @return * possible object is * {@link Integer } * */ public Integer getProofOfRightCount() { return proofOfRightCount; } /** * Sets the value of the proofOfRightCount property. * * @param value * allowed object is * {@link Integer } * */ public void setProofOfRightCount(Integer value) { this.proofOfRightCount = value; } }
37,300
https://github.com/rainforestapp/rturk/blob/master/spec/operations/assign_qualification_spec.rb
Github Open Source
Open Source
MIT
2,015
rturk
rainforestapp
Ruby
Code
81
364
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper')) describe RTurk::AssignQualification do before(:all) do aws = YAML.load(File.open(File.join(SPEC_ROOT, 'mturk.yml'))) RTurk.setup(aws['AWSAccessKeyId'], aws['AWSAccessKey'], :sandbox => true) faker('assign_qualification', :operation => 'AssignQualification') end it "should ensure required params" do lambda{RTurk::AssignQualification()}.should raise_error RTurk::MissingParameters end it "should successfully request the operation" do RTurk::Requester.should_receive(:request).once.with( hash_including('Operation' => 'AssignQualification', 'IntegerValue' => 80)) RTurk::AssignQualification(:qualification_type_id => "123456789", :worker_id => "ABCDEF1234", :integer_value => 80) rescue RTurk::InvalidRequest end it "should parse and return the result" do RTurk::AssignQualification(:qualification_type_id => "123456789", :worker_id => "ABCDEF1234", :integer_value => 80).elements.should eql( {"AssignQualificationResult"=>{"Request"=>{"IsValid"=>"True"}}} ) end end
50,879
https://github.com/jstanly047/sltbkiosks/blob/master/sltbkiosksadminapp/src/main/java/com/kiosks/sltbkiosksadmin/sltbkiosksadminapp/SLTBAdminDetailsService.java
Github Open Source
Open Source
Apache-2.0
null
sltbkiosks
jstanly047
Java
Code
98
585
package com.kiosks.sltbkiosksadmin.sltbkiosksadminapp; import com.sltb.kioskslib.library.model.Admin; import com.kiosks.sltbkiosksadmin.sltbkiosksadminapp.repo.AccountRepo; import com.kiosks.sltbkiosksadmin.sltbkiosksadminapp.repo.AdminRepo; import com.kiosks.sltbkiosksadmin.sltbkiosksadminapp.repo.PassengerRepo; import com.sltb.kioskslib.library.model.Account; import com.sltb.kioskslib.library.model.Passenger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Optional; @Service public class SLTBAdminDetailsService implements UserDetailsService { @Autowired AdminRepo adminRepo; @Autowired PassengerRepo passengerRepo; @Autowired PasswordEncoder passwordEncoder; @Autowired AccountRepo accountRepo; @Override public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException{ Optional<Admin> passenger = adminRepo.findById(userId); String pwd = passenger.isEmpty() ? "" : passenger.get().getPasswordHash(); return new org.springframework.security.core.userdetails.User(userId,pwd, new ArrayList<>()); } public boolean addPassengerDetails(Passenger passenger) { if (passengerRepo.findById(passenger.getAccountid()).isPresent()) { return false; } passenger.setPassword(passwordEncoder.encode(passenger.getPassword())); passengerRepo.save(passenger); Account account = new Account(); account.setAccountId(passenger.getAccountid()); accountRepo.save(account); return true; } }
9,445
https://github.com/GamendeMier/BrawlCrate/blob/master/docs/search/enumvalues_10.js
Github Open Source
Open Source
MIT
null
BrawlCrate
GamendeMier
JavaScript
Code
7
300
var searchData= [ ['quad_32411',['Quad',['../class_brawl_lib_1_1_platform_1_1_win32_1_1_direct_sound.html#a935c291df2accbd8f61a30349a1eaa6dae9017664588010860a92ceb5f8fcb824',1,'BrawlLib::Platform::Win32::DirectSound']]], ['quads_32412',['Quads',['../namespace_brawl_lib_1_1_wii_1_1_models.html#ab175ebe1c9a8c2871641e5f706bacbeda456de28f607f812b42743dfdd8d89314',1,'BrawlLib::Wii::Models']]], ['quanttabledef_32413',['QuantTableDef',['../namespace_brawl_lib_1_1_s_s_b_b_1_1_resource_nodes.html#add592c198a54493ad0659bc44f0de0cba887261bf1c3af7ce0aadc38490074ef3',1,'BrawlLib::SSBB::ResourceNodes']]] ];
31,910
https://github.com/sGooze/br-engine-gl/blob/master/src/brd_texture_list.cpp
Github Open Source
Open Source
MIT
2,016
br-engine-gl
sGooze
C++
Code
80
237
#include "inc/brd_texture.h" BRD_TextureList::find_leaf(const char* path){ if (!strcmp(path, tex_path)) return this; // Check if searched path is leftmost or rightmost in relation to tex_path if (left != NULL) return left->find_leaf(path); if (right != NULL) return right->find_leaf(path); else return NULL; } BRD_TextureList::BRD_TextureList(const char* path){ // Called explicitly only for root texture tex_path = path; lst->tex = new BRD_Texture2D(path); deleted = false; left = right = NULL; } BRD_TextureList* BRD_TextureList::load(const char* path){ BRD_TextureList* leaf = find_leaf(path); if (leaf != NULL) return leaf; }
29,691
https://github.com/sunqm/pyscf/blob/master/pyscf/pbc/grad/test/test_kuhf.py
Github Open Source
Open Source
Apache-2.0
2,023
pyscf
sunqm
Python
Code
228
785
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from pyscf import lib from pyscf.pbc import scf, gto, grad def setUpModule(): global cell, kpts, disp cell = gto.Cell() cell.atom= [['C', [0.0, 0.0, 0.0]], ['C', [1.685068664391,1.685068664391,1.685068664391]]] cell.a = ''' 0.000000000, 3.370137329, 3.370137329 3.370137329, 0.000000000, 3.370137329 3.370137329, 3.370137329, 0.000000000''' cell.basis = [[0, [1.3, 1]], [1, [0.8, 1]]] cell.verbose = 5 cell.pseudo = 'gth-pade' cell.unit = 'bohr' cell.mesh = [13] * 3 cell.output = '/dev/null' cell.build() kpts = cell.make_kpts([1,1,2]) disp = 1e-5 def tearDownModule(): global cell cell.stdout.close() del cell class KnownValues(unittest.TestCase): def test_kuhf_grad(self): g_scan = scf.KUHF(cell, kpts, exxdiv=None).set(conv_tol=1e-10, conv_tol_grad=1e-6).nuc_grad_method().as_scanner() g = g_scan(cell)[1] self.assertAlmostEqual(lib.fp(g), -0.9017171774435333, 6) mfs = g_scan.base.as_scanner() e1 = mfs([['C', [0.0, 0.0, 0.0]], ['C', [1.685068664391,1.685068664391,1.685068664391+disp/2.0]]]) e2 = mfs([['C', [0.0, 0.0, 0.0]], ['C', [1.685068664391,1.685068664391,1.685068664391-disp/2.0]]]) self.assertAlmostEqual(g[1,2], (e1-e2)/disp, 6) if __name__ == "__main__": print("Full Tests for KUHF Gradients") unittest.main()
26,661
https://github.com/ertan2002/CMS/blob/master/Kooboo.CMS/Kooboo.CMS.Sites/Globalization/SiteLabel.cs
Github Open Source
Open Source
BSD-3-Clause
2,019
CMS
ertan2002
C#
Code
464
1,456
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using System; using System.Linq; using System.Collections.Generic; using Kooboo.CMS.Sites.Models; using Kooboo.CMS.Sites.View; using Kooboo.Globalization; using Kooboo.CMS.Sites.Caching; using System.Web; namespace Kooboo.CMS.Sites.Globalization { public static class SiteLabel { #region Cache static string cacheKey = "SiteLabelRepository"; public static IElementRepository GetElementRepository(Site site) { var repository = site.ObjectCache().Get(cacheKey); if (repository == null) { repository = new Kooboo.Globalization.Repository.CacheElementRepository(() => Kooboo.CMS.Common.Runtime.EngineContext.Current.Resolve<IElementRepositoryFactory>().CreateRepository(site)); site.ObjectCache().Add(cacheKey, repository, new System.Runtime.Caching.CacheItemPolicy() { SlidingExpiration = TimeSpan.Parse("00:30:00") }); } return (IElementRepository)repository; } public static void ClearCache(Site site) { site.ObjectCache().Remove(cacheKey); } #endregion #region Label with inline-editing. /// <summary> /// Label with inline-editing. /// </summary> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static IHtmlString Label(this string defaultValue) { return Label(defaultValue, defaultValue); } /// <summary> /// Label with inline-editing. /// </summary> /// <param name="defaultValue">The default value.</param> /// <param name="key">The key.</param> /// <param name="category">The category.</param> /// <returns></returns> public static IHtmlString Label(this string defaultValue, string key, string category = "") { //var pageViewContext = Page_Context.Current; //pageViewContext.CheckContext(); return Label(defaultValue, key, category, Site.Current); } /// <summary> /// Label with inline-editing. /// </summary> /// <param name="defaultValue">The default value.</param> /// <param name="key">The key.</param> /// <param name="category">The category.</param> /// <param name="site">The site.</param> /// <returns></returns> public static IHtmlString Label(this string defaultValue, string key, string category, Site site) { string value = LabelValue(defaultValue, key, category, site); if (Kooboo.Settings.IsWebApplication && Page_Context.Current.Initialized && Page_Context.Current.EnabledInlineEditing(EditingType.Label)) { value = string.Format("<var start=\"true\" editType=\"label\" dataType=\"{0}\" key=\"{1}\" category=\"{2}\" style=\"display:none;\"></var>{3}<var end=\"true\" style=\"display:none;\"></var>" , Kooboo.CMS.Sites.View.FieldDataType.Text.ToString() , HttpUtility.HtmlEncode(key) , HttpUtility.HtmlEncode(category) , value); } return new HtmlString(value); } #endregion #region RawLabel Label without inline editing. /// <summary> /// Raws the label. Label without inline editing. /// </summary> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static IHtmlString RawLabel(this string defaultValue) { return RawLabel(defaultValue, defaultValue); } /// <summary> /// Raws the label. Label without inline editing. /// </summary> /// <param name="defaultValue">The default value.</param> /// <param name="key">The key.</param> /// <param name="category">The category.</param> /// <returns></returns> public static IHtmlString RawLabel(this string defaultValue, string key, string category = "") { return RawLabel(defaultValue, key, category, Site.Current); } /// <summary> /// Raws the label. Label without inline editing. /// </summary> /// <param name="defaultValue">The default value.</param> /// <param name="key">The key.</param> /// <param name="category">The category.</param> /// <param name="site">The site.</param> /// <returns></returns> public static IHtmlString RawLabel(this string defaultValue, string key, string category, Site site) { return new HtmlString(LabelValue(defaultValue, key, category, site)); } #endregion private static string LabelValue(string defaultValue, string key, string category, Site site) { if (string.IsNullOrEmpty(key) && string.IsNullOrEmpty(category)) { return defaultValue; } var repository = GetElementRepository(site); var element = repository.Get(key, category, "en-US"); string value = ""; if (element == null) { element = new Element() { Name = key, Category = category ?? "", Culture = "en-US", Value = defaultValue }; repository.Add(element); value = element.Value; } else { value = element.Value; } return value; } } }
30,818
https://github.com/mattiasliljenzin/load-testing-simulator/blob/master/test/simulation.tests/Interceptors/ChangeHostInterceptorTest.cs
Github Open Source
Open Source
MIT
2,017
load-testing-simulator
mattiasliljenzin
C#
Code
66
264
using System; using System.Collections.Generic; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using NSubstitute; using RequestSimulation.Executing.Interceptors; using Shouldly; using Xunit; namespace simulation.tests.Interceptors { public class ChangeHostInterceptorTest { private readonly IConfiguration _configuration = TestUtilities.BuildConfiguration(); [Theory] [InlineData("http://www.google.com/api/search?q=test", "http://www.yahoo.com/api/search?q=test")] public void Should_intercept_as_expected(string input, string expected) { // Arrange var interceptor = new ChangeHostInterceptor(_configuration); var message = new HttpRequestMessage(HttpMethod.Get, new Uri(input)); // Act interceptor.InterceptAsync(message); // Assert message.RequestUri.ToString().ShouldBe(expected); } } }
5,152
https://github.com/mido008/Sparmaxi/blob/master/modules/mod_sj_vm_categories/tmpl/default_theme4.php
Github Open Source
Open Source
BSD-3-Clause
null
Sparmaxi
mido008
PHP
Code
351
1,394
<?php /** * @package SJ Categories for VirtueMart * @version 2.2.0 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL * @copyright (c) 2014 YouTech Company. All Rights Reserved. * @author YouTech Company http://www.smartaddons.com * */ defined('_JEXEC') or die; $big_image_config = array( 'type' => $params->get('imgcfgcat_type'), 'width' => $params->get('imgcfgcat_width'), 'height' => $params->get('imgcfgcat_height'), 'quality' => 90, 'function' => ($params->get('imgcfgcat_function') == 'none') ? null : 'resize', 'function_mode' => ($params->get('imgcfgcat_function') == 'none') ? null : substr($params->get('imgcfgcat_function'), 7), 'transparency' => $params->get('imgcfgcat_transparency', 1) ? true : false, 'background' => $params->get('imgcfgcat_background')); ?> <div class="cat-wrap theme4"> <?php $i = 0; foreach ($list as $key => $items) { $i++; $cat_child = $items->child_cat; ?> <div class="sj-categories-inner"> <div class="sj-categories-heading"> <div class="icon_left"></div> <?php if ($params->get('cat_title_display') == 1) { ?> <div class="cat-title"> <?php $caturl = JRoute::_('index.php?option=com_virtuemart&view=category&virtuemart_category_id=' . $items->virtuemart_category_id); ?> <a href="<?php echo $caturl; ?>" title="<?php echo $items->category_name; ?>" <?php echo VmCategoriesHelper::parseTarget($options->target); ?> > <?php echo VmCategoriesHelper::truncate($items->category_name, (int)$params->get('cat_title_maxcharacs', 25)); ?> </a> </div> <?php } ?> <div class="icon_right"></div> </div> <div class="sj-categories-content cf"> <?php if (!empty($cat_child)) { $k = 0; foreach ($cat_child as $key1 => $item) { $k++; $count = count($cat_child); ?> <div class="sj-categories-content-inner"> <div class="child-cat <?php echo ($k == $count) ? 'cat-lastitem' : ''; ?>"> <div class="child-cat-info"> <?php $img = VmCategoriesHelper::getVmCImage($item, $params, "imgcfgcat"); if ($img && (strlen($img['src']) != '')) { ?> <div class="image-cat" title="<?php echo $item->category_name; ?>" style="max-width:<?php echo $params->get('imgcfg_width'); ?>px;"> <?php $caturl = JRoute::_('index.php?option=com_virtuemart&view=category&virtuemart_category_id=' . $item->virtuemart_category_id); ?> <a href="<?php echo $caturl; ?>" title="<?php echo $item->category_name; ?>" <?php echo VmCategoriesHelper::parseTarget($options->target); ?> > <img src="<?php echo VmCategoriesHelper::imageSrc($img, $big_image_config); ?>" title="<?php echo $item->category_name; ?>" alt="<?php echo $item->category_name; ?>"/> </a> </div> <?php } ?> <?php if ((int)$params->get('cat_sub_title_display', 1)) { ?> <div class="child-cat-desc"> <div class="child-cat-title"> <?php $caturl = JRoute::_('index.php?option=com_virtuemart&view=category&virtuemart_category_id=' . $item->virtuemart_category_id); ?> <a href="<?php echo $caturl ?>" title="<?php echo $item->category_name; ?>" <?php echo VmCategoriesHelper::parseTarget($options->target); ?> > <?php echo VmCategoriesHelper::truncate($item->category_name, (int)$params->get('cat_sub_title_maxcharacs', 25)); ?> </a> </div> <?php if ($params->get('cat_all_product', 1)) { ?> <div class="num_items" style="float:left;color: #737373;"> <?php echo '(' . ($item->number_product) . ')'; ?> </div> <?php } ?> </div> <?php } ?> </div> </div> </div> <?php } } else { ?> <div class="sj-categories-content-inner"> <div class="child-cat subcat-empty"> <div class="child-cat-info"> <?php echo JText::_('No sub-categories to show!'); ?> </div> </div> </div> <?php } ?> </div> </div> <?php } ?> </div>
39,013
https://github.com/CarlosSchneiderZup/orange-talents-09-template-ecommerce/blob/master/Mercado-Livre/src/main/java/br/com/zupproject/Mercado/Livre/actuator/HealthCheck.java
Github Open Source
Open Source
Apache-2.0
null
orange-talents-09-template-ecommerce
CarlosSchneiderZup
Java
Code
48
210
package br.com.zupproject.Mercado.Livre.actuator; import java.util.HashMap; import java.util.Map; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; import static org.springframework.boot.actuate.health.Status.*; @Component public class HealthCheck implements HealthIndicator { @Override public Health health() { Map<String, Object> detalhes = new HashMap<>(); detalhes.put("versao", "1.0.0"); detalhes.put("descricao", "Health Check para o projeto do mercado livre"); return Health.status(UP).withDetails(detalhes).build(); } }
6,900
https://github.com/collenirwin/Codewars-Solutions/blob/master/Solutions/TypeScript/Regexp Basics - is it a digit(8 kyu).ts
Github Open Source
Open Source
MIT
null
Codewars-Solutions
collenirwin
TypeScript
Code
8
25
String.prototype.digit = function(): boolean { return /^\d$/.test(this); };
30,683
https://github.com/NLeSC/Platinum/blob/master/ptk-vbrowser-vrs/src/main/java/nl/esciencecenter/vbrowser/vrs/event/VRSEvent.java
Github Open Source
Open Source
Apache-2.0
null
Platinum
NLeSC
Java
Code
534
1,435
/* * Copyright 2012-2014 Netherlands eScience Center. * * 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 the following location: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For the full license, see: LICENSE.txt (located in the root folder of this distribution). * --- */ // source: package nl.esciencecenter.vbrowser.vrs.event; import java.io.Serializable; import nl.esciencecenter.ptk.events.IEvent; import nl.esciencecenter.vbrowser.vrs.vrl.VRL; public class VRSEvent implements IEvent<VRSEventType>, Serializable { private static final long serialVersionUID = -6655387700048315217L; // ======================================================================== // // ======================================================================== public static VRSEvent createChildsAddedEvent(VRL optionalParent, VRL childs[]) { VRSEvent event = new VRSEvent(optionalParent,VRSEventType.RESOURCES_CREATED); event.resources = childs; return event; } public static VRSEvent createChildAddedEvent(VRL parent, VRL child) { return createChildsAddedEvent(parent, new VRL[]{child}); } public static VRSEvent createChildsDeletedEvent(VRL optionalParent, VRL childs[]) { VRSEvent event = new VRSEvent(optionalParent,VRSEventType.RESOURCES_DELETED); event.resources = childs; return event; } public static VRSEvent createChildDeletedEvent(VRL optionalParent, VRL child) { VRSEvent event = new VRSEvent(optionalParent,VRSEventType.RESOURCES_DELETED,new VRL[]{child}); return event; } public static VRSEvent createNodesDeletedEvent(VRL nodeVrls[]) { VRSEvent event = new VRSEvent(null,VRSEventType.RESOURCES_DELETED); // multi event without parent. event.resources = nodeVrls; return event; } public static VRSEvent createRefreshEvent(VRL optionalParent, VRL res) { VRSEvent event = new VRSEvent(optionalParent,VRSEventType.RESOURCES_UPDATED); event.resources = new VRL[1]; event.resources[0] = res; return event; } public static VRSEvent createNodeRenamedEvent(VRL optParentVRL, VRL oldVrl, VRL newVrl) { VRSEvent event = new VRSEvent(optParentVRL,VRSEventType.RESOURCES_RENAMED); event.resources = new VRL[] { oldVrl }; event.otherResources = new VRL[] { newVrl }; return event; } // ======================================================================== // // ======================================================================== protected VRSEventType type; /** * Optional parent resource. */ protected VRL parentSource; /** * Sources this event applies to */ protected VRL[] resources; /** * Optional new resources, when specified otherResources[i] is the new VRL for resources[i]. */ protected VRL[] otherResources; /** * Optional attribute names involved. */ protected String attributeNames[]; public VRSEvent(VRL sourceVRL, VRSEventType type) { this.parentSource=sourceVRL; this.type=type; } protected VRSEvent(VRL optionalParent, VRSEventType type, VRL[] vrls) { this.type = type; this.parentSource=optionalParent; this.resources=vrls; } public VRSEventType getType() { return this.type; } /** Resources this event applies to. */ public VRL[] getResources() { return this.resources; } /** Resources this event applies to. */ public VRL[] getOtherResources() { return this.otherResources; } /** * If the parent resource has been specified, it is the parent of all the resource from * getResources() */ public VRL getParent() { return parentSource; } /** Attributes this event applies to if this is an Attribute Event */ public String[] getAttributeNames() { return this.attributeNames; } @Override public String toString() { return "DataSourceEvent:" + this.type + ":(parentSource=" + parentSource + ", resources={" + flattenStr(resources) + "})"; } private String flattenStr(VRL[] locs) { if (locs == null) return ""; String str = ""; for (int i = 0; i < locs.length; i++) { str += locs[i]; if (i + 1 < locs.length) str += ","; } return str; } @Override public VRSEventType getEventType() { return this.type; } @Override public Object getEventSource() { return parentSource; } }
32,020
https://github.com/rubycouzcedric/afpa/blob/master/view/ajax/model/regions.php
Github Open Source
Open Source
MIT
null
afpa
rubycouzcedric
PHP
Code
82
232
<?php /** * Description of regions * * @author ced27 */ class regions extends connectionRegion { public $reg_id = ''; public $reg_v_nom = ''; public $reg_nb_dep = ''; /** * Construction de la connexion à la BDD */ public function __construct() { parent::__construct(); $this->dbConnect(); } /** * Affichage de toutes les régions */ public function getRegion() { $query = 'SELECT * FROM `regions`'; $result = $this->pdo->query($query); $listRegion = $result->fetchAll(PDO::FETCH_OBJ); $result->closeCursor(); return $listRegion; } public function __destruct() { $this->pdo = NULL; } }
13,748
https://github.com/p2svn9x/gem_tool/blob/master/ToolAdmin/application/controllers/admin/Confignew.php
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,019
gem_tool
p2svn9x
PHP
Code
302
1,240
<?php Class Confignew extends MY_Controller { function __construct() { parent::__construct(); // $this->load->model('gameconfig_model'); $this->load->model('logadmin_model'); } function index() { $this->data['temp'] = 'admin/config/index'; $this->load->view('admin/main', $this->data); } function add() { $this->data['temp'] = 'admin/config/add'; $this->load->view('admin/main', $this->data); } function edit() { $namecf = $this->uri->rsegment('3'); $this->data['namecf'] = $namecf; $plat = $this->uri->rsegment('4'); $this->data['plat'] = $plat; $id = $this->uri->rsegment('5'); $this->data['id'] = $id; $this->data['temp'] = 'admin/config/testconfig'; $this->load->view('admin/main', $this->data); } function listconfig() { //$list = $this->gameconfig_model->get_list_game_config(); // $this->data['list'] = $list; $this->data['temp'] = 'admin/config/listconfignew'; $this->load->view('admin/main', $this->data); } function listconfigajax() { $datainfo = file_get_contents($this->config->item('api_backend') . '?c=601&pf=' . "" . '&nm=' . ""); if (isset($datainfo)) { echo $datainfo; } else { echo "Bạn không được hack"; } } function editajax() { $configpf = $this->input->post('configpf'); $nmconfig = $this->input->post('nmconfig'); $datainfo = file_get_contents($this->config->item('api_backend') . '?c=601&pf=' . $configpf . '&nm=' . $nmconfig); if (isset($datainfo)) { echo $datainfo; } else { echo "Bạn không được hack"; } } function successeditajax() { $admin_login = $this->session->userdata('user_id_login'); $admin_info = $this->admin_model->get_info($admin_login); $idconfig = $this->input->post('idconfig'); $valueconfig = urlencode($this->input->post('valueconfig')); $versionconfig = $this->input->post('versionconfig'); $configpf = $this->input->post('configpf'); $datainfo = file_get_contents($this->config->item('api_backend') . '?c=603&gid=' . $idconfig . '&gv=' . $valueconfig . '&v=' . $versionconfig . '&pf=' . $configpf); if (isset($datainfo)) { $data = array( 'account_name' => $configpf, 'username' => $admin_info->UserName, 'action' => "Sửa config", ); $this->logadmin_model->create($data); echo $datainfo; } else { echo "Bạn không được hack"; } } function configajax() { $datainfo = file_get_contents($this->config->item('api_url') . '?c=7'); if (isset($datainfo)) { echo $datainfo; } else { echo "Bạn không được hack"; } } function config1ajax() { $datainfo = file_get_contents($this->config->item('api_url2') . '?c=7'); if (isset($datainfo)) { echo $datainfo; } else { echo "Bạn không được hack"; } } function config2ajax() { $datainfo = file_get_contents($this->config->item('api_url3') . '?c=7'); if (isset($datainfo)) { echo $datainfo; } else { echo "Bạn không được hack"; } } function config3ajax() { $datainfo = file_get_contents($this->config->item('api_url4') . '?c=7'); if (isset($datainfo)) { echo $datainfo; } else { echo "Bạn không được hack"; } } }
26,314
https://github.com/russelljjarvis/pub-illing2019-nnetworks/blob/master/scripts/LIF_integrator_benchmarks/comparison_balancednet.jl
Github Open Source
Open Source
MIT
2,021
pub-illing2019-nnetworks
russelljjarvis
Julia
Code
367
1,770
dt = .01 t_end = 1e3 # ms in_current = 2. ns_of_neurons = 10 .^ [1,2,3,4] V_REST = -65. # * b2.mV V_RESET = -65. # * b2.mV FIRING_THRESHOLD = -50. # * b2.mV MEMBRANE_RESISTANCE = 10. # * b2.Mohm MEMBRANE_TIME_SCALE = 10. # * b2.ms ABSOLUTE_REFRACTORY_PERIOD = 0. # * b2.ms ############################################################################### ## EventBasedIntegrator ############################################################################### using Pkg; Pkg.activate("./../../core/"); Pkg.instantiate() push!(LOAD_PATH, string(pwd(),"./../../core/src/lifintegrator/core/")) using EventBasedIntegrator, LinearAlgebra, ProgressMeter using TimerOutputs using CPUTime, BenchmarkTools, HDF5 include("./eventbasedlifintegrator_defs/eventbasedlifintegrator_defs.jl") function balanced_julia(n_of_neurons; doEuler = false) network_julia, spike_monitor_julia, profiling_time_julia = simulate_balanced_network(10 * in_current; # should actually be voltage (R = 1 Ω) n_of_neurons = n_of_neurons, simulation_time = t_end, doEuler = doEuler, dt = dt, v_rest=V_REST, v_reset=V_RESET, firing_threshold=FIRING_THRESHOLD, membrane_resistance=MEMBRANE_RESISTANCE, membrane_time_scale=MEMBRANE_TIME_SCALE, abs_refractory_period=ABSOLUTE_REFRACTORY_PERIOD) spike_times_julia = [spike[2] for spike in spike_monitor_julia.spikes] return profiling_time_julia, spike_times_julia end # event based fid = h5open("./data/balancednet_julia.h5", "w") write(fid, "ns_of_neurons", ns_of_neurons) profiling_times_julia = zeros(length(ns_of_neurons)) for i in 1:length(ns_of_neurons) t, spts = balanced_julia(ns_of_neurons[i]; doEuler = false) write(fid, string("spike_train_",ns_of_neurons[i]), spts) profiling_times_julia[i] = t end write(fid, "profiling_times", profiling_times_julia) close(fid) # euler fid = h5open("./data/balancednet_julia_euler.h5", "w") write(fid, "ns_of_neurons", ns_of_neurons) profiling_times_julia_euler = zeros(length(ns_of_neurons)) for i in 1:length(ns_of_neurons) t, spts = balanced_julia(ns_of_neurons[i]; doEuler = true) write(fid, string("spike_train_",ns_of_neurons[i]), spts) profiling_times_julia_euler[i] = t end write(fid, "profiling_times", profiling_times_julia_euler) close(fid) # get the (2) weights for init of python network? ############################################################################### ## brian2 using C++ (cpp_standalone) and exact integration ############################################################################### using PyCall py""" import sys import brian2 as b2 sys.path.append('/Users/Bernd/Documents/PhD/Drafts/draft_mnistbenchmarks/BioPlausibleShallowDeepLearning/scripts/LIF_integrator_benchmarks/brian2_defs/') from brian2_defs import simulate_balanced_network """ function balanced_brian2(n_of_neurons; first_init = false) py""" import sys import brian2 as b2 if $first_init: b2.set_device('cpp_standalone', build_on_run=False) else: #brian2.__init__.clear_cache() b2.device.reinit() b2.device.activate() b2.set_device('cpp_standalone', build_on_run=False) spike_monitor_brian2, profiling_summary = simulate_balanced_network($in_current * b2.namp, n_of_neurons = $n_of_neurons, simulation_time = $t_end * b2.ms, dt = $dt, v_rest=$V_REST * b2.mV, v_reset=$V_RESET * b2.mV, firing_threshold=$FIRING_THRESHOLD * b2.mV, membrane_resistance=$MEMBRANE_RESISTANCE * b2.Mohm, membrane_time_scale=$MEMBRANE_TIME_SCALE * b2.ms, abs_refractory_period=$ABSOLUTE_REFRACTORY_PERIOD * b2.ms) """ spike_monitor_brian2, profiling_summary = py"spike_monitor_brian2", py"profiling_summary" profiling_times = [] for x in profiling_summary push!(profiling_times, x[2][1]) end profiling_time_brian2 = sum(profiling_times) spike_monitor_brian2 = py"spike_monitor_brian2" spike_times_brian2 = 1e3 .* spike_monitor_brian2.spike_trains()[0] return profiling_time_brian2, spike_times_brian2 end fid = h5open("./data/balancednet_brian2.h5", "w") write(fid, "ns_of_neurons", ns_of_neurons) profiling_times_brian2 = zeros(length(ns_of_neurons)) for i in 1:length(ns_of_neurons) t, spts = balanced_brian2(ns_of_neurons[i]; first_init = (i == 1)) write(fid, string("spike_train_",ns_of_neurons[i]), spts) profiling_times_brian2[i] = t end write(fid, "profiling_times", profiling_times_brian2) close(fid) ############################################################################### #print(string("Time elapsed brian2 (profiling)[ms]: ", 1e3 .* profiling_time_brian2,"\n")) #print(string("Time elapsed julia (median_of_profiling) [ms]: ", 1e3 .* profiling_time_julia,"\n"))
21,240
https://github.com/Gravios/MTA/blob/master/MTAFeature.m
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,023
MTA
Gravios
MATLAB
Code
140
360
classdef MTAFeature %MTAFeature(lable,expression,ifsave) - container for behavioral state information % %key - string: keyboard character associated with state % %label - string: name describing state (e.g. 'rear' or 'walk') % %expression - string: matlab expression defining the feature; % %ifsave - logical: save feature vector if true % %feature - numericArray: feature timeseries properties (SetAccess = public) %key - string: keyboard character associated with state key %label - string: name describing state (e.g. 'rear' or 'walk') label plot_type %expression - string: matlab expression defining the feature; expression %ifsave - logical: save feature vector if true ifsave %feature - numericArray: feature timeseries feature end methods function Feature = MTAFeature(label,expression,ifsave,plot_type) Feature.label = label; Feature.expression = expression; Feature.ifsave = ifsave; Feature.feature = []; Feature.plot_type = plot_type; end function Feature = compute(Feature,Session) Feature.feature = eval(Feature.expression); if isa(Feature.feature,'MTAData'), Feature.feature = Feature.feature.data; end end end end
3,122
https://github.com/Sebastp/inspook/blob/master/client/src/graphql/get-collections.js
Github Open Source
Open Source
MIT
null
inspook
Sebastp
JavaScript
Code
30
87
import gql from 'graphql-tag' export const getCollections = gql` query getCollections($pageSize: Int, $page: Int) { getCollections(pageSize: $pageSize, page: $page) { uid title desc cover color tags booksCount } } `
14,660
https://github.com/omar-adel/Android-Kotlin-MVI-CleanArchitecture/blob/master/app/src/main/java/com/mi/mvi/koin/AuthModule.kt
Github Open Source
Open Source
MIT
2,020
Android-Kotlin-MVI-CleanArchitecture
omar-adel
Kotlin
Code
106
576
package com.mi.mvi.koin import com.mi.mvi.cache.source.AccountCacheDataSourceImpl import com.mi.mvi.cache.source.AuthCacheDataSourceImpl import com.mi.mvi.data.datasource.cache.AccountCacheDataSource import com.mi.mvi.data.datasource.cache.AuthCacheDataSource import com.mi.mvi.data.datasource.remote.AuthRemoteDataSource import com.mi.mvi.data.repository.AuthRepositoryImpl import com.mi.mvi.domain.repository.AuthRepository import com.mi.mvi.domain.usecase.auth.CheckTokenUseCase import com.mi.mvi.domain.usecase.auth.LoginUseCase import com.mi.mvi.domain.usecase.auth.RegisterUseCase import com.mi.mvi.presentation.auth.AuthActivity import com.mi.mvi.presentation.auth.AuthViewModel import com.mi.mvi.remote.service.AuthAPIService import com.mi.mvi.remote.source.AuthRemoteDataSourceImpl import kotlinx.coroutines.ExperimentalCoroutinesApi import org.koin.android.viewmodel.dsl.viewModel import org.koin.core.qualifier.named import org.koin.dsl.module import retrofit2.Retrofit @ExperimentalCoroutinesApi val authModule = module { scope(named<AuthActivity>()) { factory { provideAuthAPI(get()) } factory<AuthRemoteDataSource> { AuthRemoteDataSourceImpl( get() ) } factory<AuthCacheDataSource> { AuthCacheDataSourceImpl( get() ) } factory<AccountCacheDataSource> { AccountCacheDataSourceImpl( get() ) } factory<AuthRepository> { AuthRepositoryImpl( get(), get(), get(), get(), get() ) } factory { LoginUseCase(get()) } factory { RegisterUseCase(get()) } factory { CheckTokenUseCase(get()) } viewModel { AuthViewModel(get(), get(), get()) } } } fun provideAuthAPI(retrofit: Retrofit): AuthAPIService = retrofit.create(AuthAPIService::class.java)
1,525
https://github.com/atree-GitHub/competitive-library/blob/master/lib/utility/neighbor.hpp
Github Open Source
Open Source
CC0-1.0
2,022
competitive-library
atree-GitHub
C++
Code
97
238
#pragma once #include <cassert> #include <utility> #include <vector> template<class F> std::vector<std::pair<std::size_t, std::size_t>> neighbor(size_t x, size_t y, int dir, const F& ok) { using namespace std; assert(dir == 4 or dir == 8); const int dx[8] = { 0, 0, -1, 1, -1, -1, 1, 1 }; const int dy[8] = { -1, 1, 0, 0, -1, 1, -1, 1 }; vector<pair<size_t, size_t>> ret{}; for (int i = 0; i < dir; i++) { const auto& [nx, ny] = pair{ x + dx, y + dy }; if (ok(nx, ny)) ret.emplace_back(pair{ nx, ny }); } return ret; }
12,734
https://github.com/feralresearch/dscore/blob/master/DSSyphon/DSSyphonSource.m
Github Open Source
Open Source
MIT
2,016
dscore
feralresearch
Objective-C
Code
101
423
// // DSSyphonSource.m // Confess // // Created by Andrew on 11/21/15. // Copyright © 2015 Digital Scenographic. All rights reserved. // #import <Foundation/Foundation.h> #import "DSSyphonSource.h" #import <Syphon/Syphon.h> @implementation DSSyphonSource - (id)init{ if (self = [super init]){ name=@""; _hasWarning=NO; } return self; } // Name -(NSString*)name{return name;} -(void)setName:(NSString*)newName{ [self willChangeValueForKey:@"name"]; [self willChangeValueForKey:@"displayName"]; name=newName; // Update the displayname if(_hasWarning){ _displayName=[NSString stringWithFormat:@"<!> %@",name]; }else{ _displayName=name; } [self didChangeValueForKey:@"displayName"]; [self didChangeValueForKey:@"name"]; } -(void) encodeWithCoder: (NSCoder *)coder{ [coder encodeObject:name forKey:@"name"]; } - (id)initWithCoder:(NSCoder *)coder{ if (self = [super init]) { name = [coder decodeObjectForKey:@"name"]; } return self; } -(NSImage*)sourceIcon{ return [[_syphonClient serverDescription] objectForKey:SyphonServerDescriptionIconKey]; } @end
22,812
https://github.com/ganqiyin/xms/blob/master/Libraries/Dependency/Xms.Dependency/IDependencyBatchBuilder.cs
Github Open Source
Open Source
MIT
2,021
xms
ganqiyin
C#
Code
35
107
using System; namespace Xms.Dependency { public interface IDependencyBatchBuilder { DependencyBatchBuilder Append(int dependentComponentType, Guid dependentObjectId, int requiredComponentType, params Guid[] requiredObjectId); DependencyBatchBuilder Append(string dependentComponentName, Guid dependentObjectId, string requiredComponentName, params Guid[] requiredObjectId); void Clear(); bool Save(); } }
613
https://github.com/BBVA/hancock-dlt-adapter/blob/master/src/domain/ethereum/smartContract/__tests__/common.spec.ts
Github Open Source
Open Source
Apache-2.0
2,019
hancock-dlt-adapter
BBVA
TypeScript
Code
744
3,000
import 'jest'; import * as request from 'request-promise-native'; import * as db from '../../../../db/ethereum'; import { hancockDbError, hancockDefaultError } from '../../../../models/error'; import { ContractAbi, IEthereumContractDbModel, IEthereumSmartContractInvokeModel, IEthereumSmartContractRawTxResponse, } from '../../../../models/ethereum'; import { error } from '../../../../utils/error'; import { hancockContractNotFoundError } from '../../models/error'; import * as ethereumScCommonDomain from '../common'; import { hancockContractAbiError, hancockContractBinaryError, hancockContractCallError, hancockContractSendError, } from '../models/error'; jest.mock('request-promise-native'); jest.mock('../../../../db/ethereum'); jest.mock('../../../../utils/logger'); jest.mock('../../../../utils/error'); describe('ethereumScCommonDomain', () => { describe('::retrieveContractAbiByAddressOrAlias', () => { const dbMock: jest.Mock = (db.getSmartContractByAddressOrAlias as jest.Mock); beforeEach(() => { dbMock.mockReset(); }); it('should return the smartcontract model from db', async () => { const addressOrAlias: string = 'whatever'; const contractModelResponse: IEthereumContractDbModel | null = {} as IEthereumContractDbModel; dbMock.mockResolvedValueOnce(contractModelResponse); const result: any = await ethereumScCommonDomain.retrieveContractAbiByAddressOrAlias(addressOrAlias); expect(dbMock).toHaveBeenLastCalledWith(addressOrAlias); expect(result).toEqual(contractModelResponse); }); it('should throw an exception if the smartcontract is not found', async () => { const addressOrAlias: string = 'whatever'; dbMock.mockResolvedValueOnce(null); try { await ethereumScCommonDomain.retrieveContractAbiByAddressOrAlias(addressOrAlias); fail('it should fail'); } catch (e) { expect(dbMock).toHaveBeenLastCalledWith(addressOrAlias); expect(error).toHaveBeenCalledWith(hancockContractNotFoundError); expect(e).toEqual(hancockContractNotFoundError); } }); it('should throw an exception if there are problems retrieving the smartcontract', async () => { const addressOrAlias: string = 'whatever'; dbMock.mockRejectedValueOnce(hancockDbError); try { await ethereumScCommonDomain.retrieveContractAbiByAddressOrAlias(addressOrAlias); fail('it should fail'); } catch (e) { expect(dbMock).toHaveBeenLastCalledWith(addressOrAlias); expect(error).toHaveBeenCalledWith(hancockDbError, hancockDbError); expect(e).toEqual(hancockDbError); } }); }); describe('::retrieveContractAbi', () => { const requestMock: jest.Mock = (request as any); beforeEach(() => { requestMock.mockReset(); }); it('should return the smartcontract abi from the urlBase', async () => { const urlBase: string = 'http://whatever'; const contractAbiResponse: string = '[{"abi":"whatever"}]'; const expectedResponse: ContractAbi = [{ abi: 'whatever' }]; requestMock.mockResolvedValueOnce(contractAbiResponse); const result: ContractAbi = await ethereumScCommonDomain.retrieveContractAbi(urlBase); expect(requestMock).toHaveBeenLastCalledWith(`${urlBase}.abi`); expect(result).toEqual(expectedResponse); }); it('should throw an exception if there are problems retrieving the smartcontract abi', async () => { const urlBase: string = 'http://whatever'; requestMock.mockRejectedValueOnce(hancockContractAbiError); try { await ethereumScCommonDomain.retrieveContractAbi(urlBase); fail('it should fail'); } catch (e) { expect(requestMock).toHaveBeenLastCalledWith(`${urlBase}.abi`); expect(error).toHaveBeenCalledWith(hancockContractAbiError, hancockContractAbiError); expect(e).toEqual(hancockContractAbiError); } }); }); describe('::retrieveContractBinary', () => { const requestMock: jest.Mock = (request as any); beforeEach(() => { requestMock.mockReset(); }); it('should return the smartcontract binary from the urlBase', async () => { const urlBase: string = 'http://whatever'; const contractAbiResponse: string = '0xMockedResponseBinary'; requestMock.mockResolvedValueOnce(contractAbiResponse); const result: string = await ethereumScCommonDomain.retrieveContractBinary(urlBase); expect(requestMock).toHaveBeenLastCalledWith(`${urlBase}.bin`); expect(result).toEqual(contractAbiResponse); }); it('should throw an exception if there are problems retrieving the smartcontract binary', async () => { const urlBase: string = 'http://whatever'; requestMock.mockRejectedValueOnce(hancockContractBinaryError); try { await ethereumScCommonDomain.retrieveContractBinary(urlBase); fail('it should fail'); } catch (e) { expect(requestMock).toHaveBeenLastCalledWith(`${urlBase}.bin`); expect(error).toHaveBeenCalledWith(hancockContractBinaryError, hancockContractBinaryError); expect(e).toEqual(hancockContractBinaryError); } }); }); describe('::adaptContractInvoke', () => { const methodMock: string = 'mockMethod'; const contractInstanceMethodWeb3WrapperMock = { call: jest.fn(), send: jest.fn(), }; const contractInstanceMock = { methods: { [methodMock]: jest.fn().mockReturnValue(contractInstanceMethodWeb3WrapperMock), }, }; global.ETH = { web3: { eth: { Contract: jest.fn().mockImplementation(() => contractInstanceMock), }, }, }; const contractConstructorMock: jest.Mock = ETH.web3.eth.Contract; const contractInstanceMethodMock: jest.Mock = contractInstanceMock.methods[methodMock]; const contractInvokeReqMock: IEthereumSmartContractInvokeModel = { abi: 'mockAbi', // action: 'call', from: 'mockFrom', method: methodMock, params: ['mockParams'], to: 'mockTo', } as any; beforeEach(() => { delete contractInvokeReqMock.action; contractConstructorMock.mockClear(); contractInstanceMethodMock.mockClear(); contractInstanceMethodWeb3WrapperMock.call.mockReset(); contractInstanceMethodWeb3WrapperMock.send.mockReset(); }); it('should invoke the smartcontract method doing a "call" action', async () => { contractInvokeReqMock.action = 'call'; const invokeResponse: any = 'mockedResponse'; contractInstanceMethodWeb3WrapperMock.call.mockImplementationOnce((params, callback) => { callback(null, invokeResponse); }); const result: IEthereumSmartContractRawTxResponse = await ethereumScCommonDomain.adaptContractInvoke(contractInvokeReqMock); // new instance of web3 SM expect(contractConstructorMock).toHaveBeenLastCalledWith(contractInvokeReqMock.abi, contractInvokeReqMock.to); // method web3 wrapper generated expect(contractInstanceMethodMock).toHaveBeenCalledWith(...(contractInvokeReqMock.params as string[])); // web3 wrapper called expect(contractInstanceMethodWeb3WrapperMock.call.mock.calls[0][0]).toEqual({ from: contractInvokeReqMock.from }); // returned value is right expect(result).toEqual(invokeResponse); }); it('should throw an exception if there are problems invoking the smartcontract method doing a "call" action', async () => { contractInvokeReqMock.action = 'call'; contractInstanceMethodWeb3WrapperMock.call.mockImplementationOnce((params, callback) => { callback(hancockDefaultError, undefined); }); try { await ethereumScCommonDomain.adaptContractInvoke(contractInvokeReqMock); fail('it should fail'); } catch (e) { // new instance of web3 SM expect(contractConstructorMock).toHaveBeenLastCalledWith(contractInvokeReqMock.abi, contractInvokeReqMock.to); // method web3 wrapper generated expect(contractInstanceMethodMock).toHaveBeenCalledWith(...(contractInvokeReqMock.params as string[])); // web3 wrapper called expect(contractInstanceMethodWeb3WrapperMock.call.mock.calls[0][0]).toEqual({ from: contractInvokeReqMock.from }); // rejected error is ok expect(e).toEqual(hancockContractCallError); expect(error).toHaveBeenCalledWith(hancockContractCallError, hancockDefaultError); } }); it('should invoke the smartcontract method doing a "send" action', async () => { contractInvokeReqMock.action = 'send'; const invokeResponse: any = 'mockedResponse'; contractInstanceMethodWeb3WrapperMock.send.mockImplementationOnce((params, callback) => { callback(null, invokeResponse); }); const result: IEthereumSmartContractRawTxResponse = await ethereumScCommonDomain.adaptContractInvoke(contractInvokeReqMock); // new instance of web3 SM expect(contractConstructorMock).toHaveBeenLastCalledWith(contractInvokeReqMock.abi, contractInvokeReqMock.to); // method web3 wrapper generated expect(contractInstanceMethodMock).toHaveBeenCalledWith(...(contractInvokeReqMock.params as string[])); // web3 wrapper called expect(contractInstanceMethodWeb3WrapperMock.send.mock.calls[0][0]).toEqual({ from: contractInvokeReqMock.from }); // returned value is right expect(result).toEqual(invokeResponse); }); it('should throw an exception if there are problems invoking the smartcontract method doing a "send" action', async () => { contractInvokeReqMock.action = 'send'; const throwedError: Error = new Error('Boom!'); contractInstanceMethodWeb3WrapperMock.send.mockImplementationOnce((params, callback) => { callback(throwedError, undefined); }); try { await ethereumScCommonDomain.adaptContractInvoke(contractInvokeReqMock); fail('it should fail'); } catch (e) { // new instance of web3 SM expect(contractConstructorMock).toHaveBeenLastCalledWith(contractInvokeReqMock.abi, contractInvokeReqMock.to); // method web3 wrapper generated expect(contractInstanceMethodMock).toHaveBeenCalledWith(...(contractInvokeReqMock.params as string[])); // web3 wrapper called expect(contractInstanceMethodWeb3WrapperMock.send.mock.calls[0][0]).toEqual({ from: contractInvokeReqMock.from }); // rejected error is ok expect(e).toEqual(hancockContractSendError); } }); }); });
12,084
https://github.com/gustavkarlsson/krate/blob/master/samples/android/src/main/java/se/gustavkarlsson/krate/samples/android/gui/fragments/editnote/EditNoteViewModel.kt
Github Open Source
Open Source
MIT
2,021
krate
gustavkarlsson
Kotlin
Code
37
226
package se.gustavkarlsson.krate.samples.android.gui.fragments.editnote import se.gustavkarlsson.krate.samples.android.krate.NoteStore import se.gustavkarlsson.krate.samples.android.krate.SetEditingNoteContent import se.gustavkarlsson.krate.samples.android.krate.SetEditingNoteTitle class EditNoteViewModel(private val store: NoteStore) { val initialTitle: String = store.currentState.editingNote!!.title val initialContent: String = store.currentState.editingNote!!.content fun onTitleChanged(text: CharSequence) { store.issue(SetEditingNoteTitle(text.toString())) } fun onContentChanged(text: CharSequence) { store.issue(SetEditingNoteContent(text.toString())) } }
1,735
https://github.com/GordonLesti/SlidingWindowFilter-evaluator/blob/master/src/main/java/swf/operator/Add.java
Github Open Source
Open Source
MIT
2,021
SlidingWindowFilter-evaluator
GordonLesti
Java
Code
13
33
package swf.operator; public interface Add<T> { public T add(T obj1, T obj2); }
48,460
https://github.com/OnePlc/oneplace-xi-core/blob/master/module/Lottery/src/V1/Rpc/Tickets/TicketsControllerFactory.php
Github Open Source
Open Source
BSD-3-Clause
null
oneplace-xi-core
OnePlc
PHP
Code
15
64
<?php namespace Lottery\V1\Rpc\Tickets; class TicketsControllerFactory { public function __invoke($controllers) { return new TicketsController($controllers->get('faucetdev')); } }
32,344
https://github.com/RobinLaw-manman/annoying-algorithm/blob/master/src/main/java/study/piepie/algorithm/sort/QuickSort.java
Github Open Source
Open Source
Apache-2.0
null
annoying-algorithm
RobinLaw-manman
Java
Code
301
1,041
package study.piepie.algorithm.sort; /** * @author Robin * @date 2021-05-09 14:52 **/ public class QuickSort { // 指针j从右到左扫描比pivot小的 // 指针i从左到右扫描比pivot大的 // 交换两个人位置 // 这样保证了[j,right]的一定大于pivot // [left,i]的一定小于pivot // 所以结束循环一定是要么j左移超过了i, 要么是i右移超过了j // 无论是哪种情况j一定停留在一个小于pivot的数字上 // 或者i==j 这个数字等于pivot // 用pivot和这个位置交换就可以确保pivot左边的都比它小,右边的都比pivot大 // 8 4 7 9 10 6 11 public static void sort(int[] nums) { sort(nums, 0, nums.length - 1); } public static void sort(int[] nums, int left , int right) { if (left >= right) { return; } int p = partition(nums, left, right); sort(nums, left, p - 1); sort(nums, p + 1, right); } public static int partition(int[] nums, int left, int right) { if (left == right) { return left; } int i = left; int j = right + 1; int pivot = nums[left]; while (true) { while (nums[++i] < pivot) { if (i == right) { break; } } while (nums[--j] > pivot) { if (j == left) { break; } } if (i >= j) { break; } swap(nums, i, j); } swap(nums, left, j); return j; } private static void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; // 数组不能这么玩 // nums[i] = nums[i] ^ nums[j]; // nums[j] = nums[i] ^ nums[j]; // nums[i] = nums[i] ^ nums[j]; } public static void main(String[] args) { // i++ 和 ++i还有一个区别在于给其他变量赋值的时候,i++把未自增之前的值赋给其他变量,而++i是自增之后的 // 结论while(i++) 比 while(++i)多执行一次操作,i多加了1 int i = 0; while (i++ < 3) { // 0 < 3 ---> i=i+1=1 ----> 执行循环体 System.out.println("hello i:"+ i); // 1 2 3 } System.out.println(i); // 4 int j = 0; while (++j < 3) { // i=i+1=1 ---> 1 < 3 ----> 执行循环体 System.out.println("hello j:"+ j); // 1 2 } System.out.println(j); // 3 int[] nums = new int[]{1, 2}; System.out.println(nums[0] + " " + nums[1]); swap(nums, 0, 1); System.out.println(nums[0] + " " + nums[1]); } }
34,692
https://github.com/naroate/MyFragmentRepo/blob/master/ZMiLaucher_withAnimationEffects/src/com/ljp/laucher/additem/AddItemAdapter.java
Github Open Source
Open Source
Apache-2.0
2,017
MyFragmentRepo
naroate
Java
Code
219
869
package com.ljp.laucher.additem; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ljp.laucher.R; import com.ljp.laucher.databean.ContentItem; import com.ljp.laucher.util.ImgAsync_List; public class AddItemAdapter extends BaseAdapter { List<ContentItem> listData; ImgAsync_List asyncImageLoader_Weibo; Context context;ListView listview; // private String id; public AddItemAdapter(Context context,ListView listview, List<ContentItem> tdlist) { super(); this.listData = tdlist; this.context = context; this.listview =listview; asyncImageLoader_Weibo = new ImgAsync_List(); } @Override public int getCount() { // TODO Auto-generated method stub return listData.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return listData.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { convertView = LayoutInflater.from(context).inflate( R.layout.listitem_additem, null); } ContentItem item = listData.get(position); final ListHolder holder = new ListHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.more_icon); holder.des = (TextView) convertView.findViewById(R.id.more_des); holder.des.setText((String) item.getFrom()); int url = item.getFrom_icon(); if(url!=-1) holder.icon.setBackgroundResource(url); else holder.icon.setBackgroundResource(R.drawable.icon); /* Drawable cachedImage = asyncImageLoader_Weibo.loadDrawable(context, url, new ImageCallback_LW() { public void imageLoaded(Drawable imageDrawable, String imageUrls) { ImageView imageViewByTag = (ImageView) listview.findViewWithTag(imageUrls); if (imageViewByTag == null || imageDrawable == null) holder.icon.setBackgroundDrawable(imageDrawable); else imageViewByTag.setBackgroundDrawable(imageDrawable); } }); if (cachedImage == null) { holder.icon.setBackgroundResource(R.drawable.icon); } else { holder.icon.setBackgroundDrawable(cachedImage); }*/ return convertView; } public class ListHolder { public TextView des; public ImageView icon; } }
3,880
https://github.com/gabrielmtzcarrillo/MySteelportEmulator/blob/master/SaintsRowAPI/Models/Channel.cs
Github Open Source
Open Source
MIT
2,022
MySteelportEmulator
gabrielmtzcarrillo
C#
Code
91
217
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SaintsRowAPI.Models { public class Channel { public int ID { get; set; } public Game Game { get; set; } public ChannelOwner Owner { get; set; } public string Name { get; set; } public static Channel ChannelGetById(int channelId) { return new Channel() { ID = channelId, Owner = (ChannelOwner)channelId, }; } public static Channel ChannelGetByOwner(Game game, ChannelOwner owner) { return new Channel() { ID = (int)owner, Game = game, Owner = owner, Name = owner.ToString() }; } } }
48,153
https://github.com/oddek/8-bit-Computer/blob/master/src/computer/Computer8Bit.srcs/sources_1/new/HexToSseg.vhd
Github Open Source
Open Source
MIT
2,022
8-bit-Computer
oddek
VHDL
Code
210
530
library IEEE; use IEEE.STD_LOGIC_1164.ALL; entity HexToSseg is Port ( hex : in STD_LOGIC_VECTOR (3 downto 0); seg : out STD_LOGIC_VECTOR (7 downto 0)); end HexToSseg; architecture Behavioral of HexToSseg is begin seg(7) <= '1'; process(hex) begin case hex is when "0000" => -- 0 seg(6 downto 0) <= "1000000"; when "0001" => -- 1 seg(6 downto 0) <= "1111001"; when "0010" => -- 2 seg(6 downto 0) <= "0100100"; when "0011" => -- 3 seg(6 downto 0) <= "0110000"; when "0100" => --4 seg(6 downto 0) <= "0011001"; when "0101" => --5 seg(6 downto 0) <= "0010010"; when "0110" => -- 6 seg(6 downto 0) <= "0000010"; when "0111" => -- 7 seg(6 downto 0) <= "1111000"; when "1000" => -- 8 seg(6 downto 0) <= "0000000"; when "1001" => -- 9 seg(6 downto 0) <= "0010000"; when "1010" => -- 10 | A seg(6 downto 0) <= "0001000"; when "1011" => -- 11|B seg(6 downto 0) <= "0000011"; when "1100" => -- 12 |C seg(6 downto 0) <= "1000110"; when "1101" => -- 13 |D seg(6 downto 0) <= "0100001"; when "1110" => -- 14 |E seg(6 downto 0) <= "0000110"; when others => -- 15 | F seg(6 downto 0) <= "0001110"; end case; end process; end Behavioral;
24,915
https://github.com/nonbeyond/code-401-whiteboard-challenges/blob/master/whiteboard-challenge-07/__test__/solution.test.js
Github Open Source
Open Source
MIT
2,018
code-401-whiteboard-challenges
nonbeyond
JavaScript
Code
124
317
'use strict'; const str8 = {value: 42, next:{ value: 9000, next: {value: 13, next: null}}}; const cir = {value: 42, next: {value: 9000, next: {value: 13, next: null}}}; const solution = require('../lib/solution.js'); describe('checkLink Tests',() => { describe('Object Error', () => { test('should return error if not an object', () => { expect(() => solution.checkLink('')).toThrow('Not An Object!'); }); }); describe('Undefined Error', () => { test('should return error if undefined', () => { expect(() => !solution.checkLink()).toThrow('Undefined!'); }); }); describe('Correct Answer (Circular Lists)', () => { test('should return false if linked list is not circular', () => { expect(solution.checkLink(str8)).toEqual(false); }); }); describe('Correct Answer (Straight Lists)', () => { it('should return true if linked list is not circular', () => { cir.next.next = cir.next; expect(solution.checkLink(cir)).toBe(true); }); }); });
35,415
https://github.com/OctoAwesome/octoawesome/blob/master/OctoAwesome/OctoAwesome.Basics/SimulationComponents/ComponentContainerInteractionComponent.cs
Github Open Source
Open Source
MIT
2,023
octoawesome
OctoAwesome
C#
Code
149
420
using engenious; using OctoAwesome.Components; using OctoAwesome.EntityComponents; using OctoAwesome.Services; namespace OctoAwesome.Basics.SimulationComponents { /// <summary> /// Component for simulation with block interactions with entities. /// </summary> public class ComponentContainerInteractionComponent : SimulationComponent< Entity, SimulationComponentRecord<Entity, ControllableComponent, InventoryComponent>, ControllableComponent, InventoryComponent> { private readonly Simulation simulation; private readonly BlockInteractionService service; /// <summary> /// Initializes a new instance of the <see cref="ComponentContainerInteractionComponent"/> class. /// </summary> /// <param name="simulation">The simulation the block interactions should happen in.</param> /// <param name="interactionService"> /// The interaction service to actually interact with blocks in the simulation. /// </param> public ComponentContainerInteractionComponent(Simulation simulation, BlockInteractionService interactionService) { this.simulation = simulation; service = interactionService; } /// <inheritdoc /> protected override void UpdateValue(GameTime gameTime, SimulationComponentRecord<Entity, ControllableComponent, InventoryComponent> value) { var entity = value.Value; var controller = value.Component1; controller .Selection? .Visit( hitInfo => { }, applyInfo => { }, componentContainer => InternalUpdate(controller, entity, componentContainer) ); } private void InternalUpdate(ControllableComponent controller, Entity entity, ComponentContainer componentContainer) { } } }
40,375
https://github.com/bitflight-devops/github-action-jira-issues-fixversion-manager/blob/master/src/Jira.ts
Github Open Source
Open Source
MIT
null
github-action-jira-issues-fixversion-manager
bitflight-devops
TypeScript
Code
593
1,967
import * as core from '@actions/core' import {Version2Client} from 'jira.js' import {IssueBean, PageBeanVersion} from 'jira.js/out/version2/models' import { CreateVersion, EditIssue, GetEditIssueMeta, GetIssue, GetProject, GetProjectVersionsPaginated } from 'jira.js/out/version2/parameters' import {FixVersion, FixVersions, JiraConfig} from './@types' import {formatDate} from './utils' export default class Jira { baseUrl: string token: string email: string client: Version2Client projectKeyToId: Map<string, number> constructor(conf: JiraConfig) { this.baseUrl = conf.baseUrl this.token = conf.token this.email = conf.email this.projectKeyToId = new Map<string, number>() this.client = new Version2Client({ host: this.baseUrl, telemetry: false, authentication: { basic: { // username: this.email, // password: this.token email: this.email, apiToken: this.token } } }) } async getIssue( issueId: string, query?: { fields?: string[] expand?: string } ): Promise<IssueBean> { const params: GetIssue = { issueIdOrKey: issueId } if (query) { params.fields = query.fields || [] params.expand = query.expand || undefined } return this.client.issues.getIssue(params) } async getIssueMetaData(issueId: string): Promise<object> { const params: GetEditIssueMeta = { issueIdOrKey: issueId } return this.client.issues.getEditIssueMeta(params) } async hasFixVersion(projectIdOrKey: string, fixVersion: string): Promise<boolean> { let params: GetProjectVersionsPaginated = { projectIdOrKey: projectIdOrKey, status: 'released,unreleased', orderBy: 'sequence', query: fixVersion, startAt: -1, maxResults: 100 } core.debug(`Checking if Jira already has version '${fixVersion}'`) let getNextPage = true let pageBeanVersion: PageBeanVersion while (getNextPage === true) { pageBeanVersion = await this.client.projectVersions.getProjectVersionsPaginated(params) if ( pageBeanVersion.total != undefined && params.startAt != undefined && pageBeanVersion.maxResults != undefined ) { params.startAt = params.startAt + Math.min(pageBeanVersion.total, pageBeanVersion.maxResults) if (pageBeanVersion.values) { for (const version of pageBeanVersion.values) { core.debug(`Comparing Jira version '${version.name}' to '${fixVersion}'`) if (version.name) { if (version.name.toUpperCase() === fixVersion.toUpperCase()) { core.debug(`Jira already has version '${version.name}'`) return true } } } } } getNextPage = pageBeanVersion && !pageBeanVersion.isLast } core.debug(`Jira does not have version '${fixVersion}'`) return false } async getProjectByKey(key: string): Promise<number | undefined> { if (this.projectKeyToId.has(key)) { return this.projectKeyToId.get(key) } let params: GetProject = { projectIdOrKey: key, properties: ['id'] } try { const result = await this.client.projects.getProject(params) if (result.key && result.id) { const id = Number.parseInt(result.id) this.projectKeyToId.set(result.key, id) return id } else { throw new Error('Project not found') } } catch (err) { core.error('Project ID lookup errored') throw err } } async createFixVersion(projectId: number, fixVersion: string): Promise<boolean> { let params: CreateVersion = { name: fixVersion, description: `${fixVersion} (via GitHub)`, archived: false, released: false, startDate: formatDate(Date.now()), projectId: projectId } try { core.info(`Creating new FixVersion: ${fixVersion}`) const result = await this.client.projectVersions.createVersion(params) core.debug(`Result of createVersion: ${JSON.stringify(result)}`) } catch (err) { core.error(`Failed creating new FixVersion: ${fixVersion}`) throw err } return true } async getFixVersions(projectIdOrKey: string): Promise<Map<string, string>> { let params: GetProjectVersionsPaginated = { projectIdOrKey: projectIdOrKey, status: 'released,unreleased', orderBy: 'sequence', startAt: 0, maxResults: 100 } const logMsg: string[] = [] const versionsAvailable = new Map<string, string>() let getNextPage = true let pageBeanVersion: PageBeanVersion while (getNextPage === true) { pageBeanVersion = await this.client.projectVersions.getProjectVersionsPaginated(params) core.debug( `StartAt:${pageBeanVersion.startAt}, Total: ${pageBeanVersion.total}, Max: ${pageBeanVersion.maxResults}` ) if ( pageBeanVersion.total != undefined && params.startAt != undefined && pageBeanVersion.maxResults != undefined ) { params.startAt = params.startAt + Math.min(pageBeanVersion.total, pageBeanVersion.maxResults) if (pageBeanVersion.values) { for (const version of pageBeanVersion.values) { logMsg.push( `Project ${projectIdOrKey} includes version ${version.name} [Start: ${version.startDate}, Release: ${version.releaseDate}, ID: ${version.id}]` ) if (version.name && version.id) { versionsAvailable.set(version.name, version.id) } } } } else { break } getNextPage = pageBeanVersion && !pageBeanVersion.isLast } core.debug(logMsg.join('\n')) return versionsAvailable } async updateIssueFixVersions(issueIdOrKey: string, fixVersions: string[]): Promise<object> { const project = issueIdOrKey.split('-')[0].toUpperCase() for (const fV of fixVersions) { const needsCreation = !(await this.hasFixVersion(project, fV)) if (needsCreation) { const id = await this.getProjectByKey(project) if (id) { await this.createFixVersion(id, fV) } } } let update: FixVersions = [] for (const fV of fixVersions) { const fixedVersion: FixVersion = { add: {name: fV} } update.push(fixedVersion) } const params: EditIssue = { issueIdOrKey: issueIdOrKey, update: { fixVersions: update } } return this.client.issues.editIssue(params) } }
11,459
https://github.com/CodaFi/swift-compiler-crashes/blob/master/unique-crash-locations/swift_sildeserializer_getbbfordefinition_swift_silfunction_unsigned_int_287.swift
Github Open Source
Open Source
MIT
2,015
swift-compiler-crashes
CodaFi
Swift
Code
1
25
../crashes-duplicates/22559-swift-modulefile-loadallconformances.swift
44,353
https://github.com/kkarczewski/strona_o_domowym_winie/blob/master/app/js/myscripts.js
Github Open Source
Open Source
MIT
null
strona_o_domowym_winie
kkarczewski
JavaScript
Code
37
134
var update = function () { var date = moment(new Date()); datetime.html(date.format('DD.MM.YYYY, HH:mm:ss')); }; $(document).ready(function(){ datetime = $('#datetime') update(); setInterval(update, 1000); }); //var log = new Log(Log.DEBUG, Log.consoleLogger); var log = Log4js.getLogger('MyLogger'); log.setLevel(Log4js.Level.ALL); log.addAppender( new ConsoleAppender(true) );
36,812
https://github.com/CMSgov/managed-care-review/blob/master/services/app-web/src/routeHelpers/index.ts
Github Open Source
Open Source
CC0-1.0
null
managed-care-review
CMSgov
TypeScript
Code
18
44
export { getRelativePath } from './getRelativePath' export { getRouteName } from './getRouteName' export { isWildcardPath } from './isWildcardPath'
28,515
https://github.com/CaelestisZ/HeraQ/blob/master/scripts/replace_dir.sh
Github Open Source
Open Source
MIT
null
HeraQ
CaelestisZ
Shell
Code
63
172
#!/bin/sh # Support selinux version # replace_directory dst src DST="$1/$2" SRC="$1/$3" if [ "x${DST}" == "x${SRC}" ] then #echo "${DST} and ${SRC} is same" exit 0 else if [ -d ${SRC} ] then if [ -L ${DST} ] || [ -d ${DST} ] then rm -rf ${DST} fi ln -s $(basename ${SRC}) ${DST} else echo "${SRC} does not exit" exit -1 fi fi
41,954
https://github.com/rbieniek/BGP4J/blob/master/lib/netty-bgp4/src/main/java/org/bgp4j/netty/fsm/InternalFSMChannelManager.java
Github Open Source
Open Source
Apache-2.0, MIT
2,015
BGP4J
rbieniek
Java
Code
372
1,228
/** * Copyright 2012 Rainer Bieniek (Rainer.Bieniek@web.de) * * 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. * * File: org.bgp4j.netty.fsm.FSMChannelManager.java */ package org.bgp4j.netty.fsm; import java.util.LinkedList; import java.util.List; /** * @author Rainer Bieniek (Rainer.Bieniek@web.de) * */ class InternalFSMChannelManager { private FSMChannel managedChannel; private InternalFSMCallbacks callbacks; private List<FSMEventType> inboundEventStream = new LinkedList<FSMEventType>(); private List<FSMEventType> outboundEventStream = new LinkedList<FSMEventType>(); InternalFSMChannelManager(InternalFSMCallbacks callbacks) { this.callbacks = callbacks; } void connect(FSMChannel managedChannel) { disconnect(); this.managedChannel = managedChannel; } void disconnect() { if(isConnected()) fireDisconnectRemotePeer(); clear(); } /** * The remote connection to the peer (if established) shall be disconnected and closed */ void fireDisconnectRemotePeer() { if(managedChannel != null) callbacks.fireDisconnectRemotePeer(managedChannel); } /** * Sent an <code>OPEN</code> message to the remote peer. */ void fireSendOpenMessage() { if(managedChannel != null) { callbacks.fireSendOpenMessage(managedChannel); this.outboundEventStream.add(FSMEventType.BGPOpen); } } /** * send an FSM error notification to the remote peer */ void fireSendInternalErrorNotification() { if(managedChannel != null) { callbacks.fireSendInternalErrorNotification(managedChannel); this.outboundEventStream.add(FSMEventType.NotifyMsg); } } /** * send a CEASE notification to the remote peer */ void fireSendCeaseNotification() { if(managedChannel != null) { callbacks.fireSendCeaseNotification(managedChannel); this.outboundEventStream.add(FSMEventType.NotifyMsg); } } /** * send a keepalive message to the remote peer */ void fireSendKeepaliveMessage() { if(managedChannel != null) { callbacks.fireSendKeepaliveMessage(managedChannel); this.outboundEventStream.add(FSMEventType.KeepAliveMsg); } } /** * fire a notification to the peer that the hold timer expired */ void fireSendHoldTimerExpiredNotification() { if(managedChannel != null) { callbacks.fireSendHoldTimerExpiredNotification(managedChannel); this.outboundEventStream.add(FSMEventType.NotifyMsg); } } /** * fire an notification to the peer that it sent a bad update */ void fireSendUpdateErrorNotification() { if(managedChannel != null) { callbacks.fireSendUpdateErrorNotification(managedChannel); this.outboundEventStream.add(FSMEventType.NotifyMsg); } } boolean isConnected() { return (this.managedChannel != null); } boolean isManagedChannel(FSMChannel channel) { return (this.managedChannel == channel); } void clear() { this.managedChannel = null; this.inboundEventStream.clear(); this.outboundEventStream.clear(); } boolean hasSeenInboundFSMEvent(FSMEventType event) { return this.inboundEventStream.contains(event); } boolean hasSeenOutbboundFSMEvent(FSMEventType event) { return this.outboundEventStream.contains(event); } void pushInboundFSMEvent(FSMEventType event) { if(isConnected()) this.inboundEventStream.add(event); } }
41,103
https://github.com/simon-ritchie/pconst/blob/master/build/lib/pconst/__init__.py
Github Open Source
Open Source
MIT
2,022
pconst
simon-ritchie
Python
Code
10
23
# coding: UTF-8 from pconst.const import Const const = Const()
45,038
https://github.com/kalekundert/ligrna/blob/master/analysis/tests/01_test_sequence.py
Github Open Source
Open Source
MIT
2,020
ligrna
kalekundert
Python
Code
753
2,626
#!/usr/bin/env python import pytest from sgrna_sensor import * def test_domain_class(): domain = Domain('Alice', 'ACTG') assert domain.name == 'Alice' assert domain.seq == 'ACTG' assert domain.dna == 'ACTG' assert domain.rna == 'ACUG' assert domain.indices == range(4) assert domain.mass('rna') == 1444.8 assert domain.mass('dna') == 2347.6 assert domain.mass('ssdna') == 1173.8 assert domain.copy().seq == domain.seq assert len(domain) == 4 assert domain[0] == 'A' assert domain[1] == 'C' assert domain[2] == 'T' assert domain[3] == 'G' assert domain[1:3] == 'CT' assert domain.constraints == '....' assert domain.attachment_sites == [] assert domain.format(color='never') == 'ACTG' for i, base in enumerate(domain): assert base == domain[i] with pytest.raises(ValueError): domain.constraints = '.' domain.constraints = '.(.)' assert domain.constraints == '.(.)' domain.attachment_sites = range(len(domain)) assert domain.attachment_sites == [0, 1, 2, 3] domain.mutable = True domain.constraints = None domain.seq = 'GTCA' assert domain.seq == 'GTCA' domain[1] = 'A' assert domain.seq == 'GACA' domain[1] = 'TATA' assert domain.seq == 'GTATACA' domain[1:3] = 'CT' assert domain.seq == 'GCTTACA' domain[1:3] = 'GCGC' assert domain.seq == 'GGCGCTACA' del domain[5] assert domain.seq == 'GGCGCACA' del domain[1:5] assert domain.seq == 'GACA' domain.mutate(1, 'A') assert domain.seq == 'GACA' domain.insert(2, 'TTT') assert domain.seq == 'GATTTCA' domain.replace(2, 5, 'GG') assert domain.seq == 'GAGGCA' domain.delete(2, 4) assert domain.seq == 'GACA' domain.append('UU') assert domain.seq == 'GACAUU' domain.prepend('UU') assert domain.seq == 'UUGACAUU' def test_construct_class(): ## Test making a one domain construct. bob = Construct('Bob') bob += Domain('A', 'AAAAAA') assert bob.seq == 'AAAAAA' assert bob.seq == bob.copy().seq assert bob.format(color='never') == bob.seq assert bob.constraints == 6 * '.' assert len(bob) == 6 with pytest.raises(KeyError): bob['not a domain'] for i, expected_nucleotide in enumerate(bob.seq): assert bob[i] == expected_nucleotide ## Test making a two domain construct. bob += Domain('C', 'CCCCCC') assert bob.seq == 'AAAAAACCCCCC' assert bob.seq == bob.copy().seq assert bob.format(color='never') == bob.seq assert bob.constraints == 12 * '.' assert len(bob) == 12 ## Test appending one construct onto another. carol = Construct('Carol') carol += Domain('G', 'GGGGGG') carol = carol + bob assert carol.seq == 'GGGGGGAAAAAACCCCCC' assert carol.constraints == 18 * '.' assert len(carol) == 18 carol.prepend(Domain('T', 'TTTTTT')) assert carol.seq == 'TTTTTTGGGGGGAAAAAACCCCCC' assert carol.constraints == 24 * '.' assert len(carol) == 24 carol.replace('G', Domain('CG', 'CGCGCG')) assert carol.seq == 'TTTTTTCGCGCGAAAAAACCCCCC' assert carol.constraints == 24 * '.' assert len(carol) == 24 carol.remove('CG') assert carol.seq == 'TTTTTTAAAAAACCCCCC' assert carol.constraints == 18 * '.' assert len(carol) == 18 ## Test attaching one construct into another. dave = Construct('Dave') dave += Domain('G', 'GGGGGG') dave += Domain('T', 'TTTTTT') dave['G'].attachment_sites = 0, 3, 6 dave['T'].attachment_sites = 0, 3, 6 with pytest.raises(ValueError): dave.attach(bob, 'G', 0, 'T', 5, check_attachment_sites=True) with pytest.raises(ValueError): dave.attach(bob, 'G', 1, 'T', 6, check_attachment_sites=True) with pytest.raises(KeyError): dave.attach(bob, '?', 0, 'T', 6, check_attachment_sites=True) dave.attach(bob, 'G', 0, 'G', 3) assert dave.seq == 'AAAAAACCCCCCGGGTTTTTT' assert dave.format(color='never') == dave.seq assert dave.constraints == 21 * '.' assert len(dave) == 21 dave.reattach(bob, 'G', 3, 'G', 6) assert dave.seq == 'GGGAAAAAACCCCCCTTTTTT' assert dave.format(color='never') == dave.seq assert dave.constraints == 21 * '.' assert len(dave) == 21 dave.reattach(bob, 'G', 0, 'G', 6) assert dave.seq == 'AAAAAACCCCCCTTTTTT' assert dave.format(color='never') == dave.seq assert dave.constraints == 18 * '.' assert len(dave) == 18 dave.reattach(bob, 'G', 0, 'T', 0) assert dave.seq == 'AAAAAACCCCCCTTTTTT' assert dave.format(color='never') == dave.seq assert dave.constraints == 18 * '.' assert len(dave) == 18 dave.reattach(bob, 'G', 0, 'T', 6) assert dave.seq == 'AAAAAACCCCCC' assert dave.format(color='never') == dave.seq assert dave.constraints == 12 * '.' assert len(dave) == 12 dave.reattach(bob, 'G', 6, 'T', 0) assert dave.seq == 'GGGGGGAAAAAACCCCCCTTTTTT' assert dave.format(color='never') == dave.seq assert dave.constraints == 24 * '.' assert len(dave) == 24 dave.reattach(bob, 'G', 6, 'T', 6) assert dave.seq == 'GGGGGGAAAAAACCCCCC' assert dave.format(color='never') == dave.seq assert dave.constraints == 18 * '.' assert len(dave) == 18 dave.reattach(bob, 'G', 3, 'T', 3) assert dave.seq == 'GGGAAAAAACCCCCCTTT' assert dave.format(color='never') == dave.seq assert dave.constraints == 18 * '.' assert len(dave) == 18 ## Test removing a domain with an attached construct. dave_copy = dave.copy() dave_copy.remove('G') assert dave_copy.seq == 'TTTTTT' dave_copy = dave.copy() dave_copy.remove('T') assert dave_copy.seq == 'GGGGGG' ## Test accessing domains by index. expected_domains = [ (dave['G'], 0), (dave['G'], 1), (dave['G'], 2), (dave['A'], 0), (dave['A'], 1), (dave['A'], 2), (dave['A'], 3), (dave['A'], 4), (dave['A'], 5), (dave['C'], 0), (dave['C'], 1), (dave['C'], 2), (dave['C'], 3), (dave['C'], 4), (dave['C'], 5), (dave['T'], 3), (dave['T'], 4), (dave['T'], 5), ] for i, domain in enumerate(expected_domains): assert dave.domain_from_index(i) == domain assert dave.index_from_domain(domain[0].name, domain[1]) == i for i, domain in enumerate(reversed(expected_domains), 1): assert dave.domain_from_index(-i) == domain with pytest.raises(IndexError): dave.domain_from_index(len(dave)) ## Test changing the sequence of a domain. bob['A'].mutable = True bob['A'].seq = 'AAAA' assert bob.seq == 'AAAACCCCCC' assert carol.seq == 'TTTTTTAAAACCCCCC' assert dave.seq == 'GGGAAAACCCCCCTTT' ## Test adding constraints to a domain. bob['A'].constraints = '(())' assert bob.constraints == '(())......' assert carol.constraints == '......(())......' assert dave.constraints == '...(()).........'
29,528
https://github.com/luanx/stat/blob/master/stat-web/src/main/java/com/wantdo/stat/web/account/ProfileController.java
Github Open Source
Open Source
Apache-2.0
null
stat
luanx
Java
Code
180
822
package com.wantdo.stat.web.account; import com.wantdo.stat.entity.account.User; import com.wantdo.stat.service.account.ShiroDbRealm.ShiroUser; import com.wantdo.stat.service.account.UserService; import org.apache.shiro.SecurityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.validation.Valid; /** * 用户修改自己资料的Controller * * @Date : 2015-8-25 * @From : stat * @Author : luanx@wantdo.com */ @Controller @RequestMapping(value = "/profile") public class ProfileController { private UserService userService; @RequestMapping(method = RequestMethod.GET) public String updateForm(Model model){ Long id = getCurrentUserId(); model.addAttribute("user", userService.getUser(id)); return "account/profile"; } @RequestMapping(value = "account", method = RequestMethod.POST) public String updateAccount(@Valid @ModelAttribute("user") User user){ userService.updateUser(user); updateCurrentUserName(user.getName()); return "redirect:/profile"; } @RequestMapping(value = "basic", method = RequestMethod.POST) public String updateBasic(@Valid @ModelAttribute("user") User user) { userService.updateUser(user); updateCurrentUserName(user.getName()); return "redirect:/profile"; } /** * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出User对象,再把Form提交的内容绑定到该对象上。 * 因为仅update()方法的form中有id属性,因此仅在update时实际执行. */ @ModelAttribute public void getUser(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) { if (id != -1) { model.addAttribute("user", userService.getUser(id)); } } /** * 取出Shiro中的当前用户Id */ public Long getCurrentUserId() { ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal(); return user.id; } /** * 更新Shiro中当前用户的用户名 */ private void updateCurrentUserName(String userName){ ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal(); user.name = userName; } @Autowired public void setUserService(UserService userService) { this.userService = userService; } }
45,644
https://github.com/tewtal/alttp_sm_combo_randomizer_rom/blob/master/src/sm/randomizer/seed_display.asm
Github Open Source
Open Source
MIT
2,023
alttp_sm_combo_randomizer_rom
tewtal
Assembly
Code
379
1,521
org $c2ecbb base $82ecbb jsr seed_display org $c2f800 base $82f800 seed_display: pha phx php rep #$30 lda.l $420000 and #$003f asl asl asl tay ldx #$0000 - lda WordTable, y and #$00ff asl phx tax lda CharTable, x plx sta $7fc052, x inx inx iny cpx #$000E bne - lda.l $420001 and #$003f asl asl asl tay ldx #$0000 - lda WordTable, y and #$00ff asl phx tax lda CharTable, x plx sta $7fc060, x inx inx iny cpx #$000E bne - lda.l $420002 and #$003f asl asl asl tay ldx #$0000 - lda WordTable, y and #$00ff asl phx tax lda CharTable, x plx sta $7fc092, x inx inx iny cpx #$000E bne - lda.l $420003 and #$003f asl asl asl tay ldx #$0000 - lda WordTable, y and #$00ff asl phx tax lda CharTable, x plx sta $7fc0a0, x inx inx iny cpx #$000E bne - plp plx pla ldx #$07fe rts CharTable: ; 0x00 0x0F dw $000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f ; 0x10 0x0F dw $000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f,$000f ; 0x20 0x0F dw $000f,$0084,$002d,$000f,$000f,$000f,$000f,$0022,$008a,$008b,$000f,$0086,$0089,$0087,$0088,$000f NumTable: ; 0x30 0x0F dw $0060,$0061,$0062,$0063,$0064,$0065,$0066,$0067,$0068,$0069,$000f,$000f,$000f,$000f,$000f,$0085 ; 0x40 0x0F dw $000f,$006a,$006b,$006c,$006d,$006e,$006f,$0070,$0071,$0072,$0073,$0074,$0075,$0076,$0077,$0078 ; 0x50 0x0F dw $0079,$007a,$007b,$007c,$007d,$007e,$007f,$0080,$0081,$0082,$0083,$000f,$000f,$000f,$000f,$000f WordTable: db "GEEMER " db "RIPPER " db "ATOMIC " db "POWAMP " db "SCISER " db "NAMIHE " db "PUROMI " db "ALCOON " db "BEETOM " db "OWTCH " db "ZEBBO " db "ZEELA " db "HOLTZ " db "VIOLA " db "WAVER " db "RINKA " db "BOYON " db "CHOOT " db "KAGO " db "SKREE " db "COVERN " db "EVIR " db "TATORI " db "OUM " db "PUYO " db "YARD " db "ZOA " db "FUNE " db "GAMET " db "GERUTA " db "SOVA " db "BULL " db "ARRGI " db "BABUSU " db "BORU " db "HACHI " db "BABURU " db "TAINON " db "GERUDO " db "GIBO " db "KOPPI " db "PON " db "HOBA " db "HYU " db "KISU " db "KYUNE " db "RIBA " db "MEDUSA " db "TERU " db "FANGIN " db "PIKKU " db "POPO " db "NOMOSU " db "GUZU " db "AIGORU " db "ROPA " db "GAPURA " db "HEISHI " db "SUTARU " db "TOZOKU " db "TOPPO " db "WAINDA " db "KURIPI " db "ZORA "
48,566
https://github.com/IMRZ/tw-db/blob/master/dist/generated/threekingdoms/collections/EffectBonusValueUnitAttributeJunctions.d.ts
Github Open Source
Open Source
MIT
2,021
tw-db
IMRZ
TypeScript
Code
72
193
import { CollectionCache, CollectionKey } from "../../../common"; import { Effects } from "./Effects"; import { CampaignBonusValueIdsUnitAttributes } from "./CampaignBonusValueIdsUnitAttributes"; import { UnitAttributes } from "./UnitAttributes"; export declare namespace EffectBonusValueUnitAttributeJunctions { const KEY: CollectionKey; class Entry { private readonly collectionCache; readonly _effect: string; readonly _bonusValueId: string; readonly _unitAttribute: string; constructor(collectionCache: CollectionCache, values: any); get effect(): Effects.Entry | undefined; get bonusValueId(): CampaignBonusValueIdsUnitAttributes.Entry | undefined; get unitAttribute(): UnitAttributes.Entry | undefined; } } export default EffectBonusValueUnitAttributeJunctions;
35,754
https://github.com/ananasGit/materialui-daterange-picker/blob/master/.eslintrc.js
Github Open Source
Open Source
MIT
null
materialui-daterange-picker
ananasGit
JavaScript
Code
74
405
module.exports = { root: true, parser: "@typescript-eslint/parser", parserOptions: { tsconfigRootDir: __dirname, project: ["./tsconfig.json"], }, plugins: ["@typescript-eslint", "react", "simple-import-sort"], extends: [ "eslint:recommended", "plugin:import/errors", "plugin:import/warnings", "plugin:import/typescript", "plugin:eslint-comments/recommended", "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", "plugin:react/recommended", "plugin:react-hooks/recommended", "prettier", ], settings: { react: { version: "detect", }, }, rules: { // this rule doesn't play well with nested styled-components interpolations "@typescript-eslint/restrict-template-expressions": 0, "@typescript-eslint/no-unsafe-return": 0, "@typescript-eslint/no-unsafe-assignment": 0, "@typescript-eslint/ban-ts-comment": 0, "@typescript-eslint/no-unsafe-member-access": 0, // simple-import-sort rules aren't enabled by default "simple-import-sort/imports": 2, "simple-import-sort/exports": 2, }, };
36,278
https://github.com/p-org/PSharp/blob/master/Tests/TestingServices.Tests/Machines/Transitions/GotoStateMultipleInActionFailTest.cs
Github Open Source
Open Source
MIT
2,022
PSharp
p-org
C#
Code
333
1,081
// ------------------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------------------------------------------ using Xunit; using Xunit.Abstractions; namespace Microsoft.PSharp.TestingServices.Tests { public class GotoStateTopLevelActionFailTest : BaseTest { public GotoStateTopLevelActionFailTest(ITestOutputHelper output) : base(output) { } public enum ErrorType { CallGoto, CallPush, CallRaise, CallSend, OnExit } private class Configure : Event { public ErrorType ErrorTypeVal; public Configure(ErrorType errorTypeVal) { this.ErrorTypeVal = errorTypeVal; } } private class E : Event { } private class M : Machine { [Start] [OnEntry(nameof(InitOnEntry))] [OnExit(nameof(ExitMethod))] private class Init : MachineState { } private void InitOnEntry() { var errorType = (this.ReceivedEvent as Configure).ErrorTypeVal; this.Foo(); switch (errorType) { case ErrorType.CallGoto: this.Goto<Done>(); break; case ErrorType.CallPush: this.Push<Done>(); break; case ErrorType.CallRaise: this.Raise(new E()); break; case ErrorType.CallSend: this.Send(this.Id, new E()); break; case ErrorType.OnExit: break; default: break; } } private void ExitMethod() { this.Pop(); } private void Foo() { this.Goto<Done>(); } private class Done : MachineState { } } [Fact(Timeout=5000)] public void TestGotoStateTopLevelActionFail1() { var expectedError = "Machine 'M()' has called multiple raise, goto, push or pop in the same action."; this.TestWithError(r => { r.CreateMachine(typeof(M), new Configure(ErrorType.CallGoto)); }, expectedError: expectedError, replay: true); } [Fact(Timeout=5000)] public void TestGotoStateTopLevelActionFail2() { var expectedError = "Machine 'M()' has called multiple raise, goto, push or pop in the same action."; this.TestWithError(r => { r.CreateMachine(typeof(M), new Configure(ErrorType.CallRaise)); }, expectedError: expectedError, replay: true); } [Fact(Timeout=5000)] public void TestGotoStateTopLevelActionFail3() { var expectedError = "Machine 'M()' cannot send an event after calling raise, goto, push or pop in the same action."; this.TestWithError(r => { r.CreateMachine(typeof(M), new Configure(ErrorType.CallSend)); }, expectedError: expectedError, replay: true); } [Fact(Timeout=5000)] public void TestGotoStateTopLevelActionFail4() { var expectedError = "Machine 'M()' has called raise, goto, push or pop inside an OnExit method."; this.TestWithError(r => { r.CreateMachine(typeof(M), new Configure(ErrorType.OnExit)); }, expectedError: expectedError, replay: true); } [Fact(Timeout=5000)] public void TestGotoStateTopLevelActionFail5() { var expectedError = "Machine 'M()' has called multiple raise, goto, push or pop in the same action."; this.TestWithError(r => { r.CreateMachine(typeof(M), new Configure(ErrorType.CallPush)); }, expectedError: expectedError, replay: true); } } }
49,702
https://github.com/svetlyak40wt/cl-pgpass/blob/master/pgpass.asd
Github Open Source
Open Source
BSD-3-Clause
2,016
cl-pgpass
svetlyak40wt
Common Lisp
Code
89
363
#| This file is a part of pgpass project. Copyright (c) 2016 Alexander Artemenko (svetlyak.40wt@gmail.com) |# #| Author: Alexander Artemenko (svetlyak.40wt@gmail.com) |# (in-package :cl-user) (defpackage pgpass-asd (:use :cl :asdf)) (in-package :pgpass-asd) (defsystem pgpass :version "0.4.0" :author "Alexander Artemenko" :license "BSD" :depends-on (:split-sequence :alexandria) :components ((:module "src" :components ((:file "features") (:file "pgpass") (:file "postmodern")))) :description "" :long-description #.(with-open-file (stream (merge-pathnames #p"README.rst" (or *load-pathname* *compile-file-pathname*)) :if-does-not-exist nil :direction :input) (when stream (let ((seq (make-array (file-length stream) :element-type 'character :fill-pointer t))) (setf (fill-pointer seq) (read-sequence seq stream)) seq))) :in-order-to ((test-op (test-op pgpass-test))))
9,291
https://github.com/zhouxiexuan/pDeep3/blob/master/pDeep/tf_ops.py
Github Open Source
Open Source
Apache-2.0
2,021
pDeep3
zhouxiexuan
Python
Code
315
1,106
import numpy as np import tensorflow as tf def count_parameters(): total_parameters = 0 for variable in tf.trainable_variables(): # shape is an array of tf.Dimension shape = variable.get_shape() print(variable.name) print(shape) # print(len(shape)) variable_parameters = 1 for dim in shape: # print(dim) variable_parameters *= dim.value print(variable_parameters) total_parameters += variable_parameters return total_parameters def attention_through_time(x, num_units): # shape of x: batch, time, num_units) s = tf.reduce_max(x, axis=1) s = tf.layers.Dense(num_units, use_bias = False)(s) s = tf.nn.softmax(s) s = tf.tile(s[:, tf.newaxis, :], [1, tf.shape(x)[1], 1]) return tf.multiply(x, s) # def CapsuleLayer(x, def positional_encoding(output_dim): position_enc = np.array([[pos / np.power(10000, 2. * i / output_dim) for i in range(output_dim)] for pos in range(200)]) position_enc[:, 0::2] = np.sin(position_enc[:, 0::2]) # dim 2i position_enc[:, 1::2] = np.cos(position_enc[:, 1::2]) # dim 2i+1 # return tf.Variable(tf.convert_to_tensor(position_enc, dtype=tf.float32), trainable=False, name="pos_encode") return tf.convert_to_tensor(position_enc, dtype=tf.float32) def get_pos_embedding(position_code, time_step, batch_size): src_pos = tf.tile(tf.reshape(tf.range(time_step), [1, -1]), [batch_size, 1]) pos_embedding = tf.nn.embedding_lookup(position_code, src_pos) return pos_embedding # batch, time_step, output_dim def multihead_self_attention(input, output_dim): # input: batch_size, time_step, input_dim # https://zhuanlan.zhihu.com/p/47282410 # https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/layers/common_attention.py q, k, v = compute_qkv(input, output_dim) x = dot_product_attention(q, k, v) x = tf.layers.Dense(output_dim, use_bias=False)(x) return x def compute_qkv(input, output_dim): """Computes query, key and value. Args: input: a Tensor with shape [batch, length_q, input_shape] Returns: q, k, v : [batch, length, depth] tensors """ q = compute_attention_component(input, output_dim) k = compute_attention_component(input, output_dim) v = compute_attention_component(input, output_dim) return q, k, v def compute_attention_component(x, output_dim): """Computes attention compoenent (query, key or value). Args: x: a Tensor with shape [batch, time_step, input_dim] Returns: c : [batch, time_step, output_dim] tensor """ return tf.layers.Dense(output_dim, use_bias=False)(x) def dot_product_attention(q, k, v): """Dot-product attention. Args: q: Tensor with shape [batch, time_step, output_dim]. k: Tensor with shape [batch, time_step, output_dim]. Leading dimensions must match with q. v: Tensor with shape [batch, time_step, output_dim] Leading dimensions must match with q. Returns: Tensor with shape [batch , time_step, output_dim]. """ logits = tf.matmul(q, k, transpose_b=True) weights = tf.nn.softmax(logits, name="attention_weights") return tf.matmul(weights, v)
31,198
https://github.com/link4rkv/e-commerce-frontend-framework/blob/master/node_modules/reakit/ts/use.d.ts
Github Open Source
Open Source
MIT
2,019
e-commerce-frontend-framework
link4rkv
TypeScript
Code
7
14
import use from "reuse"; export default use;
21,436
https://github.com/ScalablyTyped/Distribution/blob/master/e/ecmarkup/src/main/scala/typings/ecmarkup/libFormatterHeaderMod.scala
Github Open Source
Open Source
MIT
2,023
Distribution
ScalablyTyped
Scala
Code
61
321
package typings.ecmarkup import typings.ecmarkup.anon.`5` import typings.ecmarkup.libFormatterLineBuilderMod.LineBuilder import typings.ecmarkup.libHeaderParserMod.ParsedHeaderOrFailure import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object libFormatterHeaderMod { @JSImport("ecmarkup/lib/formatter/header", JSImport.Namespace) @js.native val ^ : js.Any = js.native inline def printHeader(parseResult: ParsedHeaderOrFailure & `5`, clauseType: String, indent: Double): LineBuilder = (^.asInstanceOf[js.Dynamic].applyDynamic("printHeader")(parseResult.asInstanceOf[js.Any], clauseType.asInstanceOf[js.Any], indent.asInstanceOf[js.Any])).asInstanceOf[LineBuilder] inline def printHeader(parseResult: ParsedHeaderOrFailure & `5`, clauseType: Null, indent: Double): LineBuilder = (^.asInstanceOf[js.Dynamic].applyDynamic("printHeader")(parseResult.asInstanceOf[js.Any], clauseType.asInstanceOf[js.Any], indent.asInstanceOf[js.Any])).asInstanceOf[LineBuilder] }
26,388
https://github.com/preachermanx/sensu-client-go/blob/master/vendor/github.com/upfluence/sensu-go/sensu/transport/rabbitmq/rabbitmq.go
Github Open Source
Open Source
MIT
2,021
sensu-client-go
preachermanx
Go
Code
868
2,771
package rabbitmq import ( "errors" "fmt" "math/rand" "strconv" "time" "github.com/streadway/amqp" "github.com/upfluence/goutils/log" ) // AMQPChannel is an interface over amqp.Channel type AMQPChannel interface { Consume(string, string, bool, bool, bool, bool, amqp.Table) (<-chan amqp.Delivery, error) ExchangeDeclare(string, string, bool, bool, bool, bool, amqp.Table) error NotifyClose(chan *amqp.Error) chan *amqp.Error Publish(string, string, bool, bool, amqp.Publishing) error Qos(int, int, bool) error QueueBind(string, string, string, bool, amqp.Table) error QueueDeclare(string, bool, bool, bool, bool, amqp.Table) (amqp.Queue, error) } // AMQPConnection is an interface over amqp.Connection type AMQPConnection interface { Channel() (AMQPChannel, error) Close() error } // Connection is a wrapper for amqp.Connection needed to be able // to assign the result of the dialer function to // RabbitMQTransport.Connection, because Go doesn't support // covariant return types // Relevant discussion: https://github.com/streadway/amqp/issues/164 type Connection struct { *amqp.Connection } // Channel is a wrapper for amqp.Connection.Channel() func (c *Connection) Channel() (AMQPChannel, error) { return c.Connection.Channel() } // Close is a wrapper for amqp.Connection.Close() func (c *Connection) Close() error { return c.Connection.Close() } // RabbitMQTransport contains AMQP objects required to communicate with RabbitMQ type RabbitMQTransport struct { Connection AMQPConnection Channel AMQPChannel ClosingChannel chan bool Configs []*TransportConfig dialer func(string) (AMQPConnection, error) dialerConfig func(string, amqp.Config) (AMQPConnection, error) } // NewRabbitMQTransport creates a RabbitMQTransport instance from a given URI func NewRabbitMQTransport(uri string) (*RabbitMQTransport, error) { config, err := NewTransportConfig(uri) if err != nil { return nil, fmt.Errorf("Received invalid URI: %s", err) } return NewRabbitMQHATransport([]*TransportConfig{config}), nil } func amqpDialer(url string) (AMQPConnection, error) { var conn = &Connection{} var err error conn.Connection, err = amqp.Dial(url) return conn, err } func amqpDialerConfig(url string, config amqp.Config) (AMQPConnection, error) { var conn = &Connection{} var err error conn.Connection, err = amqp.DialConfig(url, config) return conn, err } // NewRabbitMQHATransport creates a RabbitMQTransport instance from a list of // TransportConfig objects in order to connect to a // High Availability RabbitMQ cluster func NewRabbitMQHATransport(configs []*TransportConfig) *RabbitMQTransport { return &RabbitMQTransport{ ClosingChannel: make(chan bool), Configs: configs, dialer: amqpDialer, dialerConfig: amqpDialerConfig, } } func (t *RabbitMQTransport) GetClosingChan() chan bool { return t.ClosingChannel } func (t *RabbitMQTransport) Connect() error { var ( uri string err error randGenerator = rand.New(rand.NewSource(time.Now().UnixNano())) ) var config *TransportConfig for _, idx := range randGenerator.Perm(len(t.Configs)) { config = t.Configs[idx] uri = config.GetURI() log.Noticef("Trying to connect to URI: %s", uri) // TODO: Add SSL support via amqp.DialTLS if heartbeatString := config.Heartbeat.String(); heartbeatString != "" { var heartbeat time.Duration heartbeat, err = time.ParseDuration(heartbeatString + "s") if err != nil { log.Warningf( "Failed to parse the heartbeat value \"%s\": %s", heartbeat, err.Error(), ) continue } t.Connection, err = t.dialerConfig( uri, amqp.Config{Heartbeat: heartbeat}, ) } else { t.Connection, err = t.dialer(uri) } if err != nil { log.Warningf("Failed to connect to URI \"%s\": %s", uri, err.Error()) continue } break } if err != nil { log.Errorf("RabbitMQ connection error: %s", err.Error()) return err } t.Channel, err = t.Connection.Channel() if err != nil { log.Errorf("RabbitMQ channel error: %s", err.Error()) return err } if prefetchString := config.Prefetch.String(); prefetchString != "" { var prefetch int prefetch, err = strconv.Atoi(prefetchString) if err != nil { log.Warningf( "Failed to parse the prefetch value \"%s\": %s", prefetchString, err.Error(), ) } else { // Relevant code for what https://github.com/sensu/sensu is doing with this value: // https://github.com/sensu/sensu-transport/blob/f9c8cc0900fbef5fe9048c86116bd49efc71d801/lib/sensu/transport/rabbitmq.rb#L249 // https://github.com/ruby-amqp/amqp/blob/9880a2b5dcfe4b27cefbdb3b3e2ea3ec58ea348a/lib/amqp/channel.rb#L998 // https://github.com/ruby-amqp/amqp/blob/9880a2b5dcfe4b27cefbdb3b3e2ea3ec58ea348a/lib/amqp/channel.rb#L1214 if err = t.Channel.Qos(prefetch, 0, false); err != nil { log.Warningf("Failed to set the prefetch value: %s", err.Error()) } } } log.Noticef("RabbitMQ connection and channel opened to %s", uri) closeChan := make(chan *amqp.Error) t.Channel.NotifyClose(closeChan) go func() { <-closeChan t.ClosingChannel <- true }() return nil } func (t *RabbitMQTransport) IsConnected() bool { if t.Connection == nil || t.Channel == nil { return false } return true } func (t *RabbitMQTransport) Close() error { if t.Connection == nil { return errors.New("The connection is not opened") } defer func() { t.Channel = nil t.Connection = nil }() err := t.Connection.Close() if err != nil { return fmt.Errorf("Failed to close the connection: %s", err.Error()) } return nil } func (t *RabbitMQTransport) Publish(exchangeType, exchangeName, key string, message []byte) error { if t.Channel == nil { return errors.New("The channel is not opened") } if err := t.Channel.ExchangeDeclare(exchangeName, exchangeType, false, false, false, false, nil); err != nil { return err } err := t.Channel.Publish(exchangeName, key, false, false, amqp.Publishing{Body: message}) return err } func (t *RabbitMQTransport) Subscribe(key, exchangeName, queueName string, messageChan chan []byte, stopChan chan bool) error { if t.Channel == nil { return errors.New("The channel is not opened") } if err := t.Channel.ExchangeDeclare( exchangeName, "fanout", false, false, false, false, amqp.Table{}, ); err != nil { log.Errorf("Can't declare the exchange: %s", err.Error()) return err } log.Infof("Exchange %s declared", exchangeName) if _, err := t.Channel.QueueDeclare( queueName, false, true, false, false, nil, ); err != nil { log.Errorf("Can't declare the queue: %s", err.Error()) return err } log.Infof("Queue %s declared", queueName) if err := t.Channel.QueueBind(queueName, key, exchangeName, false, nil); err != nil { log.Errorf("Can't bind the queue: %s", err.Error()) return err } log.Noticef("Queue %s binded to %s for key %s", queueName, exchangeName, key) deliveryChange, err := t.Channel.Consume(queueName, "", true, false, false, false, nil) log.Infof("Consuming the queue %s", queueName) if err != nil { log.Errorf("Can't consume the queue: %s", err.Error()) return err } for { select { case delivery, ok := <-deliveryChange: if ok { messageChan <- delivery.Body } else { t.ClosingChannel <- true return nil } case <-stopChan: return nil } } }
48,037
https://github.com/KishkinJ10/graphicsfuzz/blob/master/generator/src/test/java/com/graphicsfuzz/generator/semanticschanging/Expr2ArgMutationFinderTest.java
Github Open Source
Open Source
Apache-2.0
2,022
graphicsfuzz
KishkinJ10
Java
Code
206
498
/* * Copyright 2019 The GraphicsFuzz Project 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphicsfuzz.generator.semanticschanging; import static org.junit.Assert.assertEquals; import com.graphicsfuzz.common.ast.TranslationUnit; import com.graphicsfuzz.common.util.CompareAsts; import com.graphicsfuzz.common.util.ParseHelper; import com.graphicsfuzz.generator.mutateapi.Expr2ExprMutation; import java.util.List; import org.junit.Test; public class Expr2ArgMutationFinderTest { @Test public void testExpr2ArgMiner() throws Exception { final String program = "#version 100\n" + "void main() {" + " int a, b, c, d, e;" + " a + (b + c) * (d - e);" + "}"; final String expected = "#version 100\n" + "void main() {" + " int a, b, c, d, e;" + " a + (b) * (d - e);" + "}"; final TranslationUnit tu = ParseHelper.parse(program); final List<Expr2ExprMutation> ops = new Expr2ArgMutationFinder(tu) .findMutations(); assertEquals(10, ops.size()); ops.get(0).apply(); CompareAsts.assertEqualAsts(expected, tu); } }
28,512
https://github.com/TeamSPoon/CYC_JRTL_with_CommonLisp_OLD/blob/master/platform/main/KBAPI-1.0.0-Preview-SNAPSHOT-src/com/cyc/kb/Sentence.java
Github Open Source
Open Source
Apache-2.0
2,020
CYC_JRTL_with_CommonLisp_OLD
TeamSPoon
Java
Code
66
170
package com.cyc.kb; import java.util.List; import com.cyc.kb.exception.KBApiException; public interface Sentence extends KBObject { /** * NOT PART OF KB API 1.0 */ public Assertion assertIn(Context ctx) throws KBApiException; /** * NOT PART OF KB API 1.0 */ public List<Object> getArguments(); /** * NOT PART OF KB API 1.0 */ public void setArguments(List<Object> arguments); /** * NOT PART OF KB API 1.0 */ public void addArguments(Object arguments); }
627
https://github.com/Chemchu/ERPBack/blob/master/src/apollo/schema/tpv/tpvResolver.js
Github Open Source
Open Source
MIT
null
ERPBack
Chemchu
JavaScript
Code
724
2,286
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.freeTpvResolver = exports.ocupyTpvResolver = exports.updateTpvResolver = exports.deleteTpvResolver = exports.addTpvResolver = exports.tpvsResolver = exports.tpvResolver = void 0; const apollo_server_express_1 = require("apollo-server-express"); const database_1 = require("../../../databases/database"); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const tpvResolver = (parent, args, context, info) => __awaiter(void 0, void 0, void 0, function* () { if ((!args.find.nombre && !args.find._id)) throw new apollo_server_express_1.UserInputError('Argumentos inválidos: Find no puede estar vacío'); const db = database_1.Database.Instance(); if (!args.find.empleadoId) { if (args.find._id) { return yield db.TPVDBController.CollectionModel.findOne({ _id: args.find._id }).exec(); } return yield db.TPVDBController.CollectionModel.findOne({ nombre: args.find.nombre }).exec(); } const empleado = yield db.EmployeeDBController.CollectionModel.findOne({ _id: args.find.empleadoId }); if (args.find.nombre) { const tpv = yield db.TPVDBController.CollectionModel.findOne({ nombre: args.find.nombre }).exec(); if (tpv) { if (empleado) { const empleadoClean = { _id: empleado._id, nombre: empleado.nombre, apellidos: empleado.apellidos, rol: empleado.rol, email: empleado.email, dni: "", genero: "", hashPassword: "", horasPorSemana: 0 }; tpv.enUsoPor = empleadoClean; } return tpv; } return undefined; } if (args.find._id) { const tpv = yield db.TPVDBController.CollectionModel.findOne({ _id: args.find._id }).exec(); if (tpv) { if (empleado) { const empleadoClean = { _id: empleado._id, nombre: empleado.nombre, apellidos: empleado.apellidos, rol: empleado.rol, email: empleado.email, dni: "", genero: "", hashPassword: "", horasPorSemana: 0 }; tpv.enUsoPor = empleadoClean; } return tpv; } return undefined; } return yield db.TPVDBController.CollectionModel.findOne({ _id: args.find._id }).exec(); }); exports.tpvResolver = tpvResolver; const tpvsResolver = (parent, args, context, info) => __awaiter(void 0, void 0, void 0, function* () { const db = database_1.Database.Instance(); if (args.find === null || !args.find || Object.keys(args.find).length === 0 && args.find.constructor === Object) { const tpv = yield db.TPVDBController.CollectionModel.find({}) .limit(150) .exec(); return tpv; } if (args.find) { const tpv = yield db.TPVDBController.CollectionModel.find({ abierta: args.find.libre }) .limit(150) .exec(); return tpv; } return []; }); exports.tpvsResolver = tpvsResolver; const addTpvResolver = (root, args, context) => __awaiter(void 0, void 0, void 0, function* () { const db = database_1.Database.Instance(); }); exports.addTpvResolver = addTpvResolver; const deleteTpvResolver = (root, args, context) => __awaiter(void 0, void 0, void 0, function* () { const db = database_1.Database.Instance(); }); exports.deleteTpvResolver = deleteTpvResolver; const updateTpvResolver = (root, args, context) => __awaiter(void 0, void 0, void 0, function* () { const db = database_1.Database.Instance(); }); exports.updateTpvResolver = updateTpvResolver; const ocupyTpvResolver = (root, args, context) => __awaiter(void 0, void 0, void 0, function* () { const db = database_1.Database.Instance(); const secret = process.env.JWT_SECRET; if (secret) { const empleado = yield db.EmployeeDBController.CollectionModel.findOne({ _id: args.idEmpleado }).exec(); if (!empleado) { throw new apollo_server_express_1.UserInputError('Empleado no encontrado'); } const tpv = yield db.TPVDBController.CollectionModel.findOne({ _id: args.idTPV }).exec(); if (!tpv) throw new apollo_server_express_1.UserInputError('TPV no encontrada'); const empleadoClean = { _id: empleado._id, nombre: empleado.nombre, apellidos: empleado.apellidos, rol: empleado.rol, email: empleado.email, dni: "", genero: "", hashPassword: "", horasPorSemana: 0 }; yield tpv.updateOne({ libre: false, enUsoPor: empleadoClean, cajaInicial: args.cajaInicial }); const payload = { _id: empleado._id, nombre: empleado.nombre, apellidos: empleado.apellidos, email: empleado.email, rol: empleado.rol, TPV: tpv._id }; const jwtHoursDuration = process.env.JWT_HOURS_DURATION || 1; const token = yield jsonwebtoken_1.default.sign(payload, secret, { expiresIn: 3600 * Number(jwtHoursDuration) }); return { token: `Bearer ${token}` }; } }); exports.ocupyTpvResolver = ocupyTpvResolver; const freeTpvResolver = (root, args, context) => __awaiter(void 0, void 0, void 0, function* () { const db = database_1.Database.Instance(); const secret = process.env.JWT_SECRET; if (secret) { const empleado = yield db.EmployeeDBController.CollectionModel.findOne({ _id: args.idEmpleado }).exec(); if (!empleado) { throw new apollo_server_express_1.UserInputError('Empleado no encontrado'); } const tpv = yield db.TPVDBController.CollectionModel.findOne({ _id: args.idTPV }).exec(); if (!tpv) throw new apollo_server_express_1.UserInputError('TPV no encontrada'); const empleadoClean = { _id: empleado._id, nombre: empleado.nombre, apellidos: empleado.apellidos, rol: empleado.rol, email: empleado.email, dni: "", genero: "", hashPassword: "", horasPorSemana: 0 }; yield tpv.updateOne({ libre: true, enUsoPor: empleadoClean }); const payload = { _id: empleado._id, nombre: empleado.nombre, apellidos: empleado.apellidos, email: empleado.email, rol: empleado.rol }; const jwtHoursDuration = process.env.JWT_HOURS_DURATION || 1; const token = yield jsonwebtoken_1.default.sign(payload, secret, { expiresIn: 3600 * Number(jwtHoursDuration) }); return { token: `Bearer ${token}` }; } }); exports.freeTpvResolver = freeTpvResolver;
14,919
https://github.com/suyanhanx/hpr/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,018
hpr
suyanhanx
Ignore List
Code
10
55
/doc/ /lib/ /bin/ /deps/ /.shards/ /logs/ /repositories/ /config/hpr*.json docker-compose.dev.yml hpr
14,018
https://github.com/apache/cassandra/blob/master/src/java/org/apache/cassandra/auth/PasswordAuthenticator.java
Github Open Source
Open Source
Apache-2.0, MIT, CC0-1.0, BSD-3-Clause, LicenseRef-scancode-public-domain
2,023
cassandra
apache
Java
Code
1,295
3,421
/* * 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.cassandra.auth; import java.net.InetAddress; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.ConsistencyLevel; import org.apache.cassandra.exceptions.RequestExecutionException; import org.apache.cassandra.schema.SchemaConstants; import org.apache.cassandra.cql3.QueryOptions; import org.apache.cassandra.cql3.QueryProcessor; import org.apache.cassandra.cql3.UntypedResultSet; import org.apache.cassandra.cql3.statements.SelectStatement; import org.apache.cassandra.exceptions.AuthenticationException; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.service.ClientState; import org.apache.cassandra.service.QueryState; import org.apache.cassandra.transport.messages.ResultMessage; import org.apache.cassandra.utils.ByteBufferUtil; import org.mindrot.jbcrypt.BCrypt; import static org.apache.cassandra.auth.CassandraRoleManager.consistencyForRoleRead; import static org.apache.cassandra.utils.Clock.Global.nanoTime; /** * PasswordAuthenticator is an IAuthenticator implementation * that keeps credentials (rolenames and bcrypt-hashed passwords) * internally in C* - in system_auth.roles CQL3 table. * Since 2.2, the management of roles (creation, modification, * querying etc is the responsibility of IRoleManager. Use of * PasswordAuthenticator requires the use of CassandraRoleManager * for storage and retrieval of encrypted passwords. */ public class PasswordAuthenticator implements IAuthenticator, AuthCache.BulkLoader<String, String> { private static final Logger logger = LoggerFactory.getLogger(PasswordAuthenticator.class); /** We intentionally use an empty string sentinel to allow object equality comparison */ private static final String NO_SUCH_CREDENTIAL = ""; // name of the hash column. private static final String SALTED_HASH = "salted_hash"; // really this is a rolename now, but as it only matters for Thrift, we leave it for backwards compatibility public static final String USERNAME_KEY = "username"; public static final String PASSWORD_KEY = "password"; static final byte NUL = 0; private SelectStatement authenticateStatement; private final CredentialsCache cache; public PasswordAuthenticator() { cache = new CredentialsCache(this); AuthCacheService.instance.register(cache); } // No anonymous access. public boolean requireAuthentication() { return true; } @Override public Supplier<Map<String, String>> bulkLoader() { return () -> { Map<String, String> entries = new HashMap<>(); logger.info("Pre-warming credentials cache from roles table"); UntypedResultSet results = process("SELECT role, salted_hash FROM system_auth.roles", CassandraAuthorizer.authReadConsistencyLevel()); results.forEach(row -> { if (row.has("salted_hash")) { entries.put(row.getString("role"), row.getString("salted_hash")); } }); return entries; }; } public CredentialsCache getCredentialsCache() { return cache; } protected static boolean checkpw(String password, String hash) { try { return BCrypt.checkpw(password, hash); } catch (Exception e) { // Improperly formatted hashes may cause BCrypt.checkpw to throw, so trap any other exception as a failure logger.warn("Error: invalid password hash encountered, rejecting user", e); return false; } } /** * This is exposed so we can override the consistency level for tests that are single node */ @VisibleForTesting UntypedResultSet process(String query, ConsistencyLevel cl) { return QueryProcessor.process(query, cl); } private AuthenticatedUser authenticate(String username, String password) throws AuthenticationException { String hash = cache.get(username); // intentional use of object equality if (hash == NO_SUCH_CREDENTIAL) { // The cache was unable to load credentials via queryHashedPassword, probably because the supplied // rolename doesn't exist. If caching is enabled we will have now cached the sentinel value for that key // so we should invalidate it otherwise the cache will continue to serve that until it expires which // will be a problem if the role is added in the meantime. // // We can't just throw the AuthenticationException directly from queryHashedPassword for a similar reason: // if an existing role is dropped and active updates are enabled for the cache, the refresh in // CacheRefresher::run will log and swallow the exception and keep serving the stale credentials until they // eventually expire. // // So whenever we encounter the sentinal value, here and also in CacheRefresher (if active updates are // enabled), we manually expunge the key from the cache. If caching is not enabled, AuthCache::invalidate // is a safe no-op. cache.invalidateCredentials(username); throw new AuthenticationException(String.format("Provided username %s and/or password are incorrect", username)); } if (!checkpw(password, hash)) throw new AuthenticationException(String.format("Provided username %s and/or password are incorrect", username)); return new AuthenticatedUser(username); } private String queryHashedPassword(String username) { try { QueryOptions options = QueryOptions.forInternalCalls(consistencyForRoleRead(username), Lists.newArrayList(ByteBufferUtil.bytes(username))); ResultMessage.Rows rows = select(authenticateStatement, options); // If either a non-existent role name was supplied, or no credentials // were found for that role, we don't want to cache the result so we // return a sentinel value. On receiving the sentinel, the caller can // invalidate the cache and throw an appropriate exception. if (rows.result.isEmpty()) return NO_SUCH_CREDENTIAL; UntypedResultSet result = UntypedResultSet.create(rows.result); if (!result.one().has(SALTED_HASH)) return NO_SUCH_CREDENTIAL; return result.one().getString(SALTED_HASH); } catch (RequestExecutionException e) { throw new AuthenticationException("Unable to perform authentication: " + e.getMessage(), e); } } @VisibleForTesting ResultMessage.Rows select(SelectStatement statement, QueryOptions options) { return statement.execute(QueryState.forInternalCalls(), options, nanoTime()); } public Set<DataResource> protectedResources() { // Also protected by CassandraRoleManager, but the duplication doesn't hurt and is more explicit return ImmutableSet.of(DataResource.table(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES)); } public void validateConfiguration() throws ConfigurationException { } public void setup() { String query = String.format("SELECT %s FROM %s.%s WHERE role = ?", SALTED_HASH, SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES); authenticateStatement = prepare(query); } public AuthenticatedUser legacyAuthenticate(Map<String, String> credentials) throws AuthenticationException { String username = credentials.get(USERNAME_KEY); if (username == null) throw new AuthenticationException(String.format("Required key '%s' is missing", USERNAME_KEY)); String password = credentials.get(PASSWORD_KEY); if (password == null) throw new AuthenticationException(String.format("Required key '%s' is missing for provided username %s", PASSWORD_KEY, username)); return authenticate(username, password); } public SaslNegotiator newSaslNegotiator(InetAddress clientAddress) { return new PlainTextSaslAuthenticator(); } private static SelectStatement prepare(String query) { return (SelectStatement) QueryProcessor.getStatement(query, ClientState.forInternalCalls()); } @VisibleForTesting class PlainTextSaslAuthenticator implements SaslNegotiator { private boolean complete = false; private String username; private String password; public byte[] evaluateResponse(byte[] clientResponse) throws AuthenticationException { decodeCredentials(clientResponse); complete = true; return null; } public boolean isComplete() { return complete; } public AuthenticatedUser getAuthenticatedUser() throws AuthenticationException { if (!complete) throw new AuthenticationException("SASL negotiation not complete"); return authenticate(username, password); } /** * SASL PLAIN mechanism specifies that credentials are encoded in a * sequence of UTF-8 bytes, delimited by 0 (US-ASCII NUL). * The form is : {code}authzId<NUL>authnId<NUL>password<NUL>{code} * authzId is optional, and in fact we don't care about it here as we'll * set the authzId to match the authnId (that is, there is no concept of * a user being authorized to act on behalf of another with this IAuthenticator). * * @param bytes encoded credentials string sent by the client * @throws org.apache.cassandra.exceptions.AuthenticationException if either the * authnId or password is null */ private void decodeCredentials(byte[] bytes) throws AuthenticationException { logger.trace("Decoding credentials from client token"); byte[] user = null; byte[] pass = null; int end = bytes.length; for (int i = bytes.length - 1; i >= 0; i--) { if (bytes[i] == NUL) { if (pass == null) pass = Arrays.copyOfRange(bytes, i + 1, end); else if (user == null) user = Arrays.copyOfRange(bytes, i + 1, end); else throw new AuthenticationException("Credential format error: username or password is empty or contains NUL(\\0) character"); end = i; } } if (pass == null || pass.length == 0) throw new AuthenticationException("Password must not be null"); if (user == null || user.length == 0) throw new AuthenticationException("Authentication ID must not be null"); username = new String(user, StandardCharsets.UTF_8); password = new String(pass, StandardCharsets.UTF_8); } } public static class CredentialsCache extends AuthCache<String, String> implements CredentialsCacheMBean { private CredentialsCache(PasswordAuthenticator authenticator) { super(CACHE_NAME, DatabaseDescriptor::setCredentialsValidity, DatabaseDescriptor::getCredentialsValidity, DatabaseDescriptor::setCredentialsUpdateInterval, DatabaseDescriptor::getCredentialsUpdateInterval, DatabaseDescriptor::setCredentialsCacheMaxEntries, DatabaseDescriptor::getCredentialsCacheMaxEntries, DatabaseDescriptor::setCredentialsCacheActiveUpdate, DatabaseDescriptor::getCredentialsCacheActiveUpdate, authenticator::queryHashedPassword, authenticator.bulkLoader(), () -> true, (k,v) -> NO_SUCH_CREDENTIAL == v); // use a known object as a sentinel value. CacheRefresher will // invalidate the key if the sentinel is loaded during a refresh } public void invalidateCredentials(String roleName) { invalidate(roleName); } } public static interface CredentialsCacheMBean extends AuthCacheMBean { public static final String CACHE_NAME = "CredentialsCache"; public void invalidateCredentials(String roleName); } }
191
https://github.com/GoncaloBMN/Insuchain-Front-End/blob/master/src/app/pages/peer-info/peer-info.component.ts
Github Open Source
Open Source
MIT
null
Insuchain-Front-End
GoncaloBMN
TypeScript
Code
113
392
import { Component, OnInit, OnDestroy } from '@angular/core'; import { BlockchainService } from 'src/app/services/blockchain.service'; import { ActivatedRoute } from '@angular/router' @Component({ selector: 'app-peer-info', templateUrl: './peer-info.component.html', styleUrls: ['./peer-info.component.scss'] }) export class PeerInfoComponent implements OnInit, OnDestroy { public peerAddress = ''; public contracts = []; public peer_info = {}; private sub: any; constructor(private route: ActivatedRoute, private blockchainService: BlockchainService) { } ngOnInit() { this.sub = this.route.params.subscribe( (params) => { this.peerAddress = params['address']; const blockchain = this.blockchainService.blockchainInstance; this.contracts = blockchain.getAllContractsFrom(this.peerAddress); for(var i = this.contracts.length - 1; i >= 0; i--) { if(this.contracts[i].insurer.pubkey === this.peerAddress) { this.peer_info = this.contracts[i].insurer; break; } if(this.contracts[i].beneficiary.pubkey === this.peerAddress) { this.peer_info = this.contracts[i].beneficiary; break; } } }); } ngOnDestroy() { this.sub.unsubscribe(); } }
21,195
https://github.com/tkw1536/UVoteJ/blob/master/src/Frontend/Run/http/routes.js
Github Open Source
Open Source
MIT
2,015
UVoteJ
tkw1536
JavaScript
Code
251
1,019
var bodyParser = require('body-parser') express = require("express"); module.exports = function(state, logger, next){ //support the post forms state.app.use(bodyParser.json()); state.app.use(bodyParser.urlencoded({extended: false })); // GET /lib state.app.use("/lib/client/protocol.js", function(req, res){ res.sendfile(state.dirs.src+"Frontend/Server/protocol.js") }); state.app.use("/lib/client", express.static(state.dirs.src+"Client")); state.app.use("/lib/gui", express.static(state.dirs.src+"Gui")) state.app.use("/lib", express.static(state.dirs.static+"lib")); //GET /api state.app.use("/api", express.static(state.dirs.static+"api")); //GET /help state.app.use("/help", express.static(state.dirs.static+"help")); //GET /admin state.app.use("/admin/", function(req, res){ res.set('Content-Type', 'text/html'); res.send(state.templates.admin()); }); //returns a var resolveUUID = function(callback){ return function(req, res, next){ var voteDB = state.votes; //Check if we can handle this with a uuid if(voteDB.votes.hasOwnProperty(req.params.name)){ callback(req.params.name, req, res); return; } //Try and resolve the machine name var tryUUID = voteDB.machine_to_uuid(req.params.name); if(tryUUID !== ""){ callback(tryUUID, req, res); return; } next(); } } //Edit URLs, for administrators so that they can edit the vote. //Always available even once vote is closed / public. state.app.all("/edit/:name", resolveUUID(state.handleVoteEdit.bind(state))); //Vote URLs, for the public so that they can vote. //hanldes the "leaving" of the vote state.app.all("/vote/:name/vote", resolveUUID(state.handleVoteVote.bind(state))); //handles the login of the Vote state.app.all("/vote/:name/login", resolveUUID(state.handleVoteLogin.bind(state))); //handles the initiall login dialog of the vote. state.app.all("/vote/:name", resolveUUID(state.handleVoteWelcome.bind(state))); // HTML Result URLs, for the public so that they can view results //Will result in a 404 if the results are not yet available. state.app.all("/results/:name", resolveUUID(state.handleVoteRes.bind(state))); //Public URLs, these redirect either to /vote/:name or /results/:nam //dependening on the state of the vote. state.app.all("/:name", resolveUUID(function(uuid, req, res){ res.redirect(303, "/vote/"+req.params.name); })); //just for the root state.app.get("/", function(req, res){ res.sendfile(state.dirs.static+"/index.html"); }) // 404 Page state.app.use(function(req, res){ res.set('Content-Type', 'text/html'); res.send(404, state.templates.error_404({"url": req.protocol + '://' + req.get('host') + req.originalUrl})) }); //500 page state.app.use(function(error, req, res, next){ state.templates.send_500(req, res, error); }); //run the next thing next(state); }
39,892
https://github.com/EIDSS/EIDSS-Legacy/blob/master/EIDSS v6/eidss.model/Schema/VetCase.model.cs
Github Open Source
Open Source
BSD-2-Clause
2,017
EIDSS-Legacy
EIDSS
C#
Code
19,886
84,640
#pragma warning disable 0472 using System; using System.Text; using System.IO; using System.Collections; using System.ComponentModel; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Xml.Serialization; using BLToolkit.Aspects; using BLToolkit.DataAccess; using BLToolkit.EditableObjects; using BLToolkit.Data; using BLToolkit.Data.DataProvider; using BLToolkit.Mapping; using BLToolkit.Reflection; using bv.common.Configuration; using bv.common.Enums; using bv.common.Core; using bv.model.BLToolkit; using bv.model.Model; using bv.model.Helpers; using bv.model.Model.Extenders; using bv.model.Model.Core; using bv.model.Model.Handlers; using bv.model.Model.Validators; using eidss.model.Core; using eidss.model.Enums; namespace eidss.model.Schema { [XmlType(AnonymousType = true)] public abstract partial class VetCase : EditableObject<VetCase> , IObject , IDisposable , ILookupUsage { [MapField(_str_idfCase), NonUpdatable, PrimaryKey] public abstract Int64 idfCase { get; set; } [LocalizedDisplayName(_str_idfsCaseClassification)] [MapField(_str_idfsCaseClassification)] public abstract Int64? idfsCaseClassification { get; set; } protected Int64? idfsCaseClassification_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCaseClassification).OriginalValue; } } protected Int64? idfsCaseClassification_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCaseClassification).PreviousValue; } } [LocalizedDisplayName(_str_idfsCaseProgressStatus)] [MapField(_str_idfsCaseProgressStatus)] public abstract Int64? idfsCaseProgressStatus { get; set; } protected Int64? idfsCaseProgressStatus_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCaseProgressStatus).OriginalValue; } } protected Int64? idfsCaseProgressStatus_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCaseProgressStatus).PreviousValue; } } [LocalizedDisplayName(_str_idfsShowDiagnosis)] [MapField(_str_idfsShowDiagnosis)] public abstract Int64? idfsShowDiagnosis { get; set; } protected Int64? idfsShowDiagnosis_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsShowDiagnosis).OriginalValue; } } protected Int64? idfsShowDiagnosis_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsShowDiagnosis).PreviousValue; } } [LocalizedDisplayName(_str_idfsCaseType)] [MapField(_str_idfsCaseType)] public abstract Int64 idfsCaseType { get; set; } protected Int64 idfsCaseType_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfsCaseType).OriginalValue; } } protected Int64 idfsCaseType_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfsCaseType).PreviousValue; } } [LocalizedDisplayName(_str_idfOutbreak)] [MapField(_str_idfOutbreak)] public abstract Int64? idfOutbreak { get; set; } protected Int64? idfOutbreak_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfOutbreak).OriginalValue; } } protected Int64? idfOutbreak_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfOutbreak).PreviousValue; } } [LocalizedDisplayName(_str_strOutbreakID)] [MapField(_str_strOutbreakID)] public abstract String strOutbreakID { get; set; } protected String strOutbreakID_Original { get { return ((EditableValue<String>)((dynamic)this)._strOutbreakID).OriginalValue; } } protected String strOutbreakID_Previous { get { return ((EditableValue<String>)((dynamic)this)._strOutbreakID).PreviousValue; } } [LocalizedDisplayName(_str_idfParentMonitoringSession)] [MapField(_str_idfParentMonitoringSession)] public abstract Int64? idfParentMonitoringSession { get; set; } protected Int64? idfParentMonitoringSession_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfParentMonitoringSession).OriginalValue; } } protected Int64? idfParentMonitoringSession_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfParentMonitoringSession).PreviousValue; } } [LocalizedDisplayName(_str_strMonitoringSessionID)] [MapField(_str_strMonitoringSessionID)] public abstract String strMonitoringSessionID { get; set; } protected String strMonitoringSessionID_Original { get { return ((EditableValue<String>)((dynamic)this)._strMonitoringSessionID).OriginalValue; } } protected String strMonitoringSessionID_Previous { get { return ((EditableValue<String>)((dynamic)this)._strMonitoringSessionID).PreviousValue; } } [LocalizedDisplayName(_str_datEnteredDate)] [MapField(_str_datEnteredDate)] public abstract DateTime? datEnteredDate { get; set; } protected DateTime? datEnteredDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datEnteredDate).OriginalValue; } } protected DateTime? datEnteredDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datEnteredDate).PreviousValue; } } [LocalizedDisplayName(_str_uidOfflineCaseID)] [MapField(_str_uidOfflineCaseID)] public abstract Guid? uidOfflineCaseID { get; set; } protected Guid? uidOfflineCaseID_Original { get { return ((EditableValue<Guid?>)((dynamic)this)._uidOfflineCaseID).OriginalValue; } } protected Guid? uidOfflineCaseID_Previous { get { return ((EditableValue<Guid?>)((dynamic)this)._uidOfflineCaseID).PreviousValue; } } [LocalizedDisplayName(_str_strCaseID)] [MapField(_str_strCaseID)] public abstract String strCaseID { get; set; } protected String strCaseID_Original { get { return ((EditableValue<String>)((dynamic)this)._strCaseID).OriginalValue; } } protected String strCaseID_Previous { get { return ((EditableValue<String>)((dynamic)this)._strCaseID).PreviousValue; } } [LocalizedDisplayName("VetCase.TentativeDiagnosis1")] [MapField(_str_idfsTentativeDiagnosis)] public abstract Int64? idfsTentativeDiagnosis { get; set; } protected Int64? idfsTentativeDiagnosis_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsTentativeDiagnosis).OriginalValue; } } protected Int64? idfsTentativeDiagnosis_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsTentativeDiagnosis).PreviousValue; } } [LocalizedDisplayName("VetCase.TentativeDiagnosis2")] [MapField(_str_idfsTentativeDiagnosis1)] public abstract Int64? idfsTentativeDiagnosis1 { get; set; } protected Int64? idfsTentativeDiagnosis1_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsTentativeDiagnosis1).OriginalValue; } } protected Int64? idfsTentativeDiagnosis1_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsTentativeDiagnosis1).PreviousValue; } } [LocalizedDisplayName("VetCase.TentativeDiagnosis3")] [MapField(_str_idfsTentativeDiagnosis2)] public abstract Int64? idfsTentativeDiagnosis2 { get; set; } protected Int64? idfsTentativeDiagnosis2_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsTentativeDiagnosis2).OriginalValue; } } protected Int64? idfsTentativeDiagnosis2_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsTentativeDiagnosis2).PreviousValue; } } [LocalizedDisplayName("VetCase.FinalDiagnogis")] [MapField(_str_idfsFinalDiagnosis)] public abstract Int64? idfsFinalDiagnosis { get; set; } protected Int64? idfsFinalDiagnosis_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsFinalDiagnosis).OriginalValue; } } protected Int64? idfsFinalDiagnosis_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsFinalDiagnosis).PreviousValue; } } [LocalizedDisplayName(_str_idfsYNTestsConducted)] [MapField(_str_idfsYNTestsConducted)] public abstract Int64? idfsYNTestsConducted { get; set; } protected Int64? idfsYNTestsConducted_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsYNTestsConducted).OriginalValue; } } protected Int64? idfsYNTestsConducted_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsYNTestsConducted).PreviousValue; } } [LocalizedDisplayName(_str_blnEnableTestsConducted)] [MapField(_str_blnEnableTestsConducted)] public abstract Boolean? blnEnableTestsConducted { get; set; } protected Boolean? blnEnableTestsConducted_Original { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnEnableTestsConducted).OriginalValue; } } protected Boolean? blnEnableTestsConducted_Previous { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnEnableTestsConducted).PreviousValue; } } [LocalizedDisplayName(_str_idfInvestigatedByOffice)] [MapField(_str_idfInvestigatedByOffice)] public abstract Int64? idfInvestigatedByOffice { get; set; } protected Int64? idfInvestigatedByOffice_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfInvestigatedByOffice).OriginalValue; } } protected Int64? idfInvestigatedByOffice_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfInvestigatedByOffice).PreviousValue; } } [LocalizedDisplayName(_str_strInvestigatedByOffice)] [MapField(_str_strInvestigatedByOffice)] public abstract String strInvestigatedByOffice { get; set; } protected String strInvestigatedByOffice_Original { get { return ((EditableValue<String>)((dynamic)this)._strInvestigatedByOffice).OriginalValue; } } protected String strInvestigatedByOffice_Previous { get { return ((EditableValue<String>)((dynamic)this)._strInvestigatedByOffice).PreviousValue; } } [LocalizedDisplayName(_str_idfPersonInvestigatedBy)] [MapField(_str_idfPersonInvestigatedBy)] public abstract Int64? idfPersonInvestigatedBy { get; set; } protected Int64? idfPersonInvestigatedBy_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfPersonInvestigatedBy).OriginalValue; } } protected Int64? idfPersonInvestigatedBy_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfPersonInvestigatedBy).PreviousValue; } } [LocalizedDisplayName(_str_strPersonInvestigatedBy)] [MapField(_str_strPersonInvestigatedBy)] public abstract String strPersonInvestigatedBy { get; set; } protected String strPersonInvestigatedBy_Original { get { return ((EditableValue<String>)((dynamic)this)._strPersonInvestigatedBy).OriginalValue; } } protected String strPersonInvestigatedBy_Previous { get { return ((EditableValue<String>)((dynamic)this)._strPersonInvestigatedBy).PreviousValue; } } [LocalizedDisplayName(_str_idfPersonEnteredBy)] [MapField(_str_idfPersonEnteredBy)] public abstract Int64? idfPersonEnteredBy { get; set; } protected Int64? idfPersonEnteredBy_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfPersonEnteredBy).OriginalValue; } } protected Int64? idfPersonEnteredBy_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfPersonEnteredBy).PreviousValue; } } [LocalizedDisplayName(_str_strPersonEnteredByName)] [MapField(_str_strPersonEnteredByName)] public abstract String strPersonEnteredByName { get; set; } protected String strPersonEnteredByName_Original { get { return ((EditableValue<String>)((dynamic)this)._strPersonEnteredByName).OriginalValue; } } protected String strPersonEnteredByName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strPersonEnteredByName).PreviousValue; } } [LocalizedDisplayName(_str_idfReportedByOffice)] [MapField(_str_idfReportedByOffice)] public abstract Int64? idfReportedByOffice { get; set; } protected Int64? idfReportedByOffice_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfReportedByOffice).OriginalValue; } } protected Int64? idfReportedByOffice_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfReportedByOffice).PreviousValue; } } [LocalizedDisplayName(_str_strReportedByOffice)] [MapField(_str_strReportedByOffice)] public abstract String strReportedByOffice { get; set; } protected String strReportedByOffice_Original { get { return ((EditableValue<String>)((dynamic)this)._strReportedByOffice).OriginalValue; } } protected String strReportedByOffice_Previous { get { return ((EditableValue<String>)((dynamic)this)._strReportedByOffice).PreviousValue; } } [LocalizedDisplayName(_str_idfPersonReportedBy)] [MapField(_str_idfPersonReportedBy)] public abstract Int64? idfPersonReportedBy { get; set; } protected Int64? idfPersonReportedBy_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfPersonReportedBy).OriginalValue; } } protected Int64? idfPersonReportedBy_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfPersonReportedBy).PreviousValue; } } [LocalizedDisplayName(_str_strPersonReportedBy)] [MapField(_str_strPersonReportedBy)] public abstract String strPersonReportedBy { get; set; } protected String strPersonReportedBy_Original { get { return ((EditableValue<String>)((dynamic)this)._strPersonReportedBy).OriginalValue; } } protected String strPersonReportedBy_Previous { get { return ((EditableValue<String>)((dynamic)this)._strPersonReportedBy).PreviousValue; } } [LocalizedDisplayName(_str_idfObservation)] [MapField(_str_idfObservation)] public abstract Int64? idfObservation { get; set; } protected Int64? idfObservation_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfObservation).OriginalValue; } } protected Int64? idfObservation_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfObservation).PreviousValue; } } [LocalizedDisplayName(_str_idfsFormTemplate)] [MapField(_str_idfsFormTemplate)] public abstract Int64? idfsFormTemplate { get; set; } protected Int64? idfsFormTemplate_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsFormTemplate).OriginalValue; } } protected Int64? idfsFormTemplate_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsFormTemplate).PreviousValue; } } [LocalizedDisplayName(_str_idfsSite)] [MapField(_str_idfsSite)] public abstract Int64 idfsSite { get; set; } protected Int64 idfsSite_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfsSite).OriginalValue; } } protected Int64 idfsSite_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfsSite).PreviousValue; } } [LocalizedDisplayName("datInitialReportDate")] [MapField(_str_datReportDate)] public abstract DateTime? datReportDate { get; set; } protected DateTime? datReportDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datReportDate).OriginalValue; } } protected DateTime? datReportDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datReportDate).PreviousValue; } } [LocalizedDisplayName(_str_datAssignedDate)] [MapField(_str_datAssignedDate)] public abstract DateTime? datAssignedDate { get; set; } protected DateTime? datAssignedDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datAssignedDate).OriginalValue; } } protected DateTime? datAssignedDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datAssignedDate).PreviousValue; } } [LocalizedDisplayName(_str_datInvestigationDate)] [MapField(_str_datInvestigationDate)] public abstract DateTime? datInvestigationDate { get; set; } protected DateTime? datInvestigationDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datInvestigationDate).OriginalValue; } } protected DateTime? datInvestigationDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datInvestigationDate).PreviousValue; } } [LocalizedDisplayName("datTentativeDiagnosisDateLbl")] [MapField(_str_datTentativeDiagnosisDate)] public abstract DateTime? datTentativeDiagnosisDate { get; set; } protected DateTime? datTentativeDiagnosisDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datTentativeDiagnosisDate).OriginalValue; } } protected DateTime? datTentativeDiagnosisDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datTentativeDiagnosisDate).PreviousValue; } } [LocalizedDisplayName("datTentativeDiagnosis1DateLbl")] [MapField(_str_datTentativeDiagnosis1Date)] public abstract DateTime? datTentativeDiagnosis1Date { get; set; } protected DateTime? datTentativeDiagnosis1Date_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datTentativeDiagnosis1Date).OriginalValue; } } protected DateTime? datTentativeDiagnosis1Date_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datTentativeDiagnosis1Date).PreviousValue; } } [LocalizedDisplayName("datTentativeDiagnosis2DateLbl")] [MapField(_str_datTentativeDiagnosis2Date)] public abstract DateTime? datTentativeDiagnosis2Date { get; set; } protected DateTime? datTentativeDiagnosis2Date_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datTentativeDiagnosis2Date).OriginalValue; } } protected DateTime? datTentativeDiagnosis2Date_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datTentativeDiagnosis2Date).PreviousValue; } } [LocalizedDisplayName(_str_datFinalDiagnosisDate)] [MapField(_str_datFinalDiagnosisDate)] public abstract DateTime? datFinalDiagnosisDate { get; set; } protected DateTime? datFinalDiagnosisDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datFinalDiagnosisDate).OriginalValue; } } protected DateTime? datFinalDiagnosisDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datFinalDiagnosisDate).PreviousValue; } } [LocalizedDisplayName(_str_idfsCaseReportType)] [MapField(_str_idfsCaseReportType)] public abstract Int64? idfsCaseReportType { get; set; } protected Int64? idfsCaseReportType_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCaseReportType).OriginalValue; } } protected Int64? idfsCaseReportType_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCaseReportType).PreviousValue; } } [LocalizedDisplayName("VetCase.strSampleNotes")] [MapField(_str_strSampleNotes)] public abstract String strSampleNotes { get; set; } protected String strSampleNotes_Original { get { return ((EditableValue<String>)((dynamic)this)._strSampleNotes).OriginalValue; } } protected String strSampleNotes_Previous { get { return ((EditableValue<String>)((dynamic)this)._strSampleNotes).PreviousValue; } } [LocalizedDisplayName(_str_strTestNotes)] [MapField(_str_strTestNotes)] public abstract String strTestNotes { get; set; } protected String strTestNotes_Original { get { return ((EditableValue<String>)((dynamic)this)._strTestNotes).OriginalValue; } } protected String strTestNotes_Previous { get { return ((EditableValue<String>)((dynamic)this)._strTestNotes).PreviousValue; } } [LocalizedDisplayName(_str_strSummaryNotes)] [MapField(_str_strSummaryNotes)] public abstract String strSummaryNotes { get; set; } protected String strSummaryNotes_Original { get { return ((EditableValue<String>)((dynamic)this)._strSummaryNotes).OriginalValue; } } protected String strSummaryNotes_Previous { get { return ((EditableValue<String>)((dynamic)this)._strSummaryNotes).PreviousValue; } } [LocalizedDisplayName(_str_strClinicalNotes)] [MapField(_str_strClinicalNotes)] public abstract String strClinicalNotes { get; set; } protected String strClinicalNotes_Original { get { return ((EditableValue<String>)((dynamic)this)._strClinicalNotes).OriginalValue; } } protected String strClinicalNotes_Previous { get { return ((EditableValue<String>)((dynamic)this)._strClinicalNotes).PreviousValue; } } [LocalizedDisplayName(_str_strFieldAccessionID)] [MapField(_str_strFieldAccessionID)] public abstract String strFieldAccessionID { get; set; } protected String strFieldAccessionID_Original { get { return ((EditableValue<String>)((dynamic)this)._strFieldAccessionID).OriginalValue; } } protected String strFieldAccessionID_Previous { get { return ((EditableValue<String>)((dynamic)this)._strFieldAccessionID).PreviousValue; } } [LocalizedDisplayName(_str_idfFarm)] [MapField(_str_idfFarm)] public abstract Int64 idfFarm { get; set; } protected Int64 idfFarm_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfFarm).OriginalValue; } } protected Int64 idfFarm_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfFarm).PreviousValue; } } [LocalizedDisplayName(_str_idfRootFarm)] [MapField(_str_idfRootFarm)] public abstract Int64? idfRootFarm { get; set; } protected Int64? idfRootFarm_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfRootFarm).OriginalValue; } } protected Int64? idfRootFarm_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfRootFarm).PreviousValue; } } [LocalizedDisplayName(_str_strFinalDiagnosisOIECode)] [MapField(_str_strFinalDiagnosisOIECode)] public abstract String strFinalDiagnosisOIECode { get; set; } protected String strFinalDiagnosisOIECode_Original { get { return ((EditableValue<String>)((dynamic)this)._strFinalDiagnosisOIECode).OriginalValue; } } protected String strFinalDiagnosisOIECode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strFinalDiagnosisOIECode).PreviousValue; } } [LocalizedDisplayName(_str_strTentativeDiagnosisOIECode)] [MapField(_str_strTentativeDiagnosisOIECode)] public abstract String strTentativeDiagnosisOIECode { get; set; } protected String strTentativeDiagnosisOIECode_Original { get { return ((EditableValue<String>)((dynamic)this)._strTentativeDiagnosisOIECode).OriginalValue; } } protected String strTentativeDiagnosisOIECode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strTentativeDiagnosisOIECode).PreviousValue; } } [LocalizedDisplayName(_str_strTentativeDiagnosis1OIECode)] [MapField(_str_strTentativeDiagnosis1OIECode)] public abstract String strTentativeDiagnosis1OIECode { get; set; } protected String strTentativeDiagnosis1OIECode_Original { get { return ((EditableValue<String>)((dynamic)this)._strTentativeDiagnosis1OIECode).OriginalValue; } } protected String strTentativeDiagnosis1OIECode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strTentativeDiagnosis1OIECode).PreviousValue; } } [LocalizedDisplayName(_str_strTentativeDiagnosis2OIECode)] [MapField(_str_strTentativeDiagnosis2OIECode)] public abstract String strTentativeDiagnosis2OIECode { get; set; } protected String strTentativeDiagnosis2OIECode_Original { get { return ((EditableValue<String>)((dynamic)this)._strTentativeDiagnosis2OIECode).OriginalValue; } } protected String strTentativeDiagnosis2OIECode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strTentativeDiagnosis2OIECode).PreviousValue; } } [LocalizedDisplayName(_str_datModificationForArchiveDate)] [MapField(_str_datModificationForArchiveDate)] public abstract DateTime? datModificationForArchiveDate { get; set; } protected DateTime? datModificationForArchiveDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datModificationForArchiveDate).OriginalValue; } } protected DateTime? datModificationForArchiveDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datModificationForArchiveDate).PreviousValue; } } #region Set/Get values #region filed_info definifion protected class field_info { internal string _name; internal string _formname; internal string _type; internal Func<VetCase, object> _get_func; internal Action<VetCase, string> _set_func; internal Action<VetCase, VetCase, CompareModel> _compare_func; } internal const string _str_Parent = "Parent"; internal const string _str_IsNew = "IsNew"; internal const string _str_idfCase = "idfCase"; internal const string _str_idfsCaseClassification = "idfsCaseClassification"; internal const string _str_idfsCaseProgressStatus = "idfsCaseProgressStatus"; internal const string _str_idfsShowDiagnosis = "idfsShowDiagnosis"; internal const string _str_idfsCaseType = "idfsCaseType"; internal const string _str_idfOutbreak = "idfOutbreak"; internal const string _str_strOutbreakID = "strOutbreakID"; internal const string _str_idfParentMonitoringSession = "idfParentMonitoringSession"; internal const string _str_strMonitoringSessionID = "strMonitoringSessionID"; internal const string _str_datEnteredDate = "datEnteredDate"; internal const string _str_uidOfflineCaseID = "uidOfflineCaseID"; internal const string _str_strCaseID = "strCaseID"; internal const string _str_idfsTentativeDiagnosis = "idfsTentativeDiagnosis"; internal const string _str_idfsTentativeDiagnosis1 = "idfsTentativeDiagnosis1"; internal const string _str_idfsTentativeDiagnosis2 = "idfsTentativeDiagnosis2"; internal const string _str_idfsFinalDiagnosis = "idfsFinalDiagnosis"; internal const string _str_idfsYNTestsConducted = "idfsYNTestsConducted"; internal const string _str_blnEnableTestsConducted = "blnEnableTestsConducted"; internal const string _str_idfInvestigatedByOffice = "idfInvestigatedByOffice"; internal const string _str_strInvestigatedByOffice = "strInvestigatedByOffice"; internal const string _str_idfPersonInvestigatedBy = "idfPersonInvestigatedBy"; internal const string _str_strPersonInvestigatedBy = "strPersonInvestigatedBy"; internal const string _str_idfPersonEnteredBy = "idfPersonEnteredBy"; internal const string _str_strPersonEnteredByName = "strPersonEnteredByName"; internal const string _str_idfReportedByOffice = "idfReportedByOffice"; internal const string _str_strReportedByOffice = "strReportedByOffice"; internal const string _str_idfPersonReportedBy = "idfPersonReportedBy"; internal const string _str_strPersonReportedBy = "strPersonReportedBy"; internal const string _str_idfObservation = "idfObservation"; internal const string _str_idfsFormTemplate = "idfsFormTemplate"; internal const string _str_idfsSite = "idfsSite"; internal const string _str_datReportDate = "datReportDate"; internal const string _str_datAssignedDate = "datAssignedDate"; internal const string _str_datInvestigationDate = "datInvestigationDate"; internal const string _str_datTentativeDiagnosisDate = "datTentativeDiagnosisDate"; internal const string _str_datTentativeDiagnosis1Date = "datTentativeDiagnosis1Date"; internal const string _str_datTentativeDiagnosis2Date = "datTentativeDiagnosis2Date"; internal const string _str_datFinalDiagnosisDate = "datFinalDiagnosisDate"; internal const string _str_idfsCaseReportType = "idfsCaseReportType"; internal const string _str_strSampleNotes = "strSampleNotes"; internal const string _str_strTestNotes = "strTestNotes"; internal const string _str_strSummaryNotes = "strSummaryNotes"; internal const string _str_strClinicalNotes = "strClinicalNotes"; internal const string _str_strFieldAccessionID = "strFieldAccessionID"; internal const string _str_idfFarm = "idfFarm"; internal const string _str_idfRootFarm = "idfRootFarm"; internal const string _str_strFinalDiagnosisOIECode = "strFinalDiagnosisOIECode"; internal const string _str_strTentativeDiagnosisOIECode = "strTentativeDiagnosisOIECode"; internal const string _str_strTentativeDiagnosis1OIECode = "strTentativeDiagnosis1OIECode"; internal const string _str_strTentativeDiagnosis2OIECode = "strTentativeDiagnosis2OIECode"; internal const string _str_datModificationForArchiveDate = "datModificationForArchiveDate"; internal const string _str_strDiagnosis = "strDiagnosis"; internal const string _str_DiagnosisAll = "DiagnosisAll"; internal const string _str_strDiseaseNames = "strDiseaseNames"; internal const string _str_IsClosed = "IsClosed"; internal const string _str_IsEnabledCaseProgressStatus = "IsEnabledCaseProgressStatus"; internal const string _str_idfsDiagnosis = "idfsDiagnosis"; internal const string _str_strSiteCode = "strSiteCode"; internal const string _str_strIdfsDiagnosis = "strIdfsDiagnosis"; internal const string _str_strReadOnlyEnteredDate = "strReadOnlyEnteredDate"; internal const string _str_buttonSelectFarm = "buttonSelectFarm"; internal const string _str_buttonCoordinatesPicker = "buttonCoordinatesPicker"; internal const string _str_blnEnableTestsConductedCalc = "blnEnableTestsConductedCalc"; internal const string _str_Site = "Site"; internal const string _str_CaseReportType = "CaseReportType"; internal const string _str_CaseType = "CaseType"; internal const string _str_CaseClassification = "CaseClassification"; internal const string _str_CaseProgressStatus = "CaseProgressStatus"; internal const string _str_TestsConducted = "TestsConducted"; internal const string _str_TentativeDiagnosis = "TentativeDiagnosis"; internal const string _str_TentativeDiagnosis1 = "TentativeDiagnosis1"; internal const string _str_TentativeDiagnosis2 = "TentativeDiagnosis2"; internal const string _str_FinalDiagnosis = "FinalDiagnosis"; internal const string _str_ShowDiagnosis = "ShowDiagnosis"; internal const string _str_PersonInvestigatedBy = "PersonInvestigatedBy"; internal const string _str_FFPresenterControlMeasures = "FFPresenterControlMeasures"; internal const string _str_Farm = "Farm"; internal const string _str_Vaccination = "Vaccination"; internal const string _str_CaseTests = "CaseTests"; internal const string _str_CaseTestValidations = "CaseTestValidations"; internal const string _str_PensideTests = "PensideTests"; internal const string _str_AnimalList = "AnimalList"; internal const string _str_Samples = "Samples"; internal const string _str_Logs = "Logs"; private static readonly field_info[] _field_infos = { new field_info { _name = _str_idfCase, _formname = _str_idfCase, _type = "Int64", _get_func = o => o.idfCase, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfCase != newval) o.idfCase = newval; }, _compare_func = (o, c, m) => { if (o.idfCase != c.idfCase || o.IsRIRPropChanged(_str_idfCase, c)) m.Add(_str_idfCase, o.ObjectIdent + _str_idfCase, o.ObjectIdent2 + _str_idfCase, o.ObjectIdent3 + _str_idfCase, "Int64", o.idfCase == null ? "" : o.idfCase.ToString(), o.IsReadOnly(_str_idfCase), o.IsInvisible(_str_idfCase), o.IsRequired(_str_idfCase)); } }, new field_info { _name = _str_idfsCaseClassification, _formname = _str_idfsCaseClassification, _type = "Int64?", _get_func = o => o.idfsCaseClassification, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsCaseClassification != newval) o.CaseClassification = o.CaseClassificationLookup.FirstOrDefault(c => c.idfsBaseReference == newval); if (o.idfsCaseClassification != newval) o.idfsCaseClassification = newval; }, _compare_func = (o, c, m) => { if (o.idfsCaseClassification != c.idfsCaseClassification || o.IsRIRPropChanged(_str_idfsCaseClassification, c)) m.Add(_str_idfsCaseClassification, o.ObjectIdent + _str_idfsCaseClassification, o.ObjectIdent2 + _str_idfsCaseClassification, o.ObjectIdent3 + _str_idfsCaseClassification, "Int64?", o.idfsCaseClassification == null ? "" : o.idfsCaseClassification.ToString(), o.IsReadOnly(_str_idfsCaseClassification), o.IsInvisible(_str_idfsCaseClassification), o.IsRequired(_str_idfsCaseClassification)); } }, new field_info { _name = _str_idfsCaseProgressStatus, _formname = _str_idfsCaseProgressStatus, _type = "Int64?", _get_func = o => o.idfsCaseProgressStatus, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsCaseProgressStatus != newval) o.CaseProgressStatus = o.CaseProgressStatusLookup.FirstOrDefault(c => c.idfsBaseReference == newval); if (o.idfsCaseProgressStatus != newval) o.idfsCaseProgressStatus = newval; }, _compare_func = (o, c, m) => { if (o.idfsCaseProgressStatus != c.idfsCaseProgressStatus || o.IsRIRPropChanged(_str_idfsCaseProgressStatus, c)) m.Add(_str_idfsCaseProgressStatus, o.ObjectIdent + _str_idfsCaseProgressStatus, o.ObjectIdent2 + _str_idfsCaseProgressStatus, o.ObjectIdent3 + _str_idfsCaseProgressStatus, "Int64?", o.idfsCaseProgressStatus == null ? "" : o.idfsCaseProgressStatus.ToString(), o.IsReadOnly(_str_idfsCaseProgressStatus), o.IsInvisible(_str_idfsCaseProgressStatus), o.IsRequired(_str_idfsCaseProgressStatus)); } }, new field_info { _name = _str_idfsShowDiagnosis, _formname = _str_idfsShowDiagnosis, _type = "Int64?", _get_func = o => o.idfsShowDiagnosis, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsShowDiagnosis != newval) o.ShowDiagnosis = o.ShowDiagnosisLookup.FirstOrDefault(c => c.idfsDiagnosis == newval); if (o.idfsShowDiagnosis != newval) o.idfsShowDiagnosis = newval; }, _compare_func = (o, c, m) => { if (o.idfsShowDiagnosis != c.idfsShowDiagnosis || o.IsRIRPropChanged(_str_idfsShowDiagnosis, c)) m.Add(_str_idfsShowDiagnosis, o.ObjectIdent + _str_idfsShowDiagnosis, o.ObjectIdent2 + _str_idfsShowDiagnosis, o.ObjectIdent3 + _str_idfsShowDiagnosis, "Int64?", o.idfsShowDiagnosis == null ? "" : o.idfsShowDiagnosis.ToString(), o.IsReadOnly(_str_idfsShowDiagnosis), o.IsInvisible(_str_idfsShowDiagnosis), o.IsRequired(_str_idfsShowDiagnosis)); } }, new field_info { _name = _str_idfsCaseType, _formname = _str_idfsCaseType, _type = "Int64", _get_func = o => o.idfsCaseType, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsCaseType != newval) o.CaseType = o.CaseTypeLookup.FirstOrDefault(c => c.idfsBaseReference == newval); if (o.idfsCaseType != newval) o.idfsCaseType = newval; }, _compare_func = (o, c, m) => { if (o.idfsCaseType != c.idfsCaseType || o.IsRIRPropChanged(_str_idfsCaseType, c)) m.Add(_str_idfsCaseType, o.ObjectIdent + _str_idfsCaseType, o.ObjectIdent2 + _str_idfsCaseType, o.ObjectIdent3 + _str_idfsCaseType, "Int64", o.idfsCaseType == null ? "" : o.idfsCaseType.ToString(), o.IsReadOnly(_str_idfsCaseType), o.IsInvisible(_str_idfsCaseType), o.IsRequired(_str_idfsCaseType)); } }, new field_info { _name = _str_idfOutbreak, _formname = _str_idfOutbreak, _type = "Int64?", _get_func = o => o.idfOutbreak, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfOutbreak != newval) o.idfOutbreak = newval; }, _compare_func = (o, c, m) => { if (o.idfOutbreak != c.idfOutbreak || o.IsRIRPropChanged(_str_idfOutbreak, c)) m.Add(_str_idfOutbreak, o.ObjectIdent + _str_idfOutbreak, o.ObjectIdent2 + _str_idfOutbreak, o.ObjectIdent3 + _str_idfOutbreak, "Int64?", o.idfOutbreak == null ? "" : o.idfOutbreak.ToString(), o.IsReadOnly(_str_idfOutbreak), o.IsInvisible(_str_idfOutbreak), o.IsRequired(_str_idfOutbreak)); } }, new field_info { _name = _str_strOutbreakID, _formname = _str_strOutbreakID, _type = "String", _get_func = o => o.strOutbreakID, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strOutbreakID != newval) o.strOutbreakID = newval; }, _compare_func = (o, c, m) => { if (o.strOutbreakID != c.strOutbreakID || o.IsRIRPropChanged(_str_strOutbreakID, c)) m.Add(_str_strOutbreakID, o.ObjectIdent + _str_strOutbreakID, o.ObjectIdent2 + _str_strOutbreakID, o.ObjectIdent3 + _str_strOutbreakID, "String", o.strOutbreakID == null ? "" : o.strOutbreakID.ToString(), o.IsReadOnly(_str_strOutbreakID), o.IsInvisible(_str_strOutbreakID), o.IsRequired(_str_strOutbreakID)); } }, new field_info { _name = _str_idfParentMonitoringSession, _formname = _str_idfParentMonitoringSession, _type = "Int64?", _get_func = o => o.idfParentMonitoringSession, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfParentMonitoringSession != newval) o.idfParentMonitoringSession = newval; }, _compare_func = (o, c, m) => { if (o.idfParentMonitoringSession != c.idfParentMonitoringSession || o.IsRIRPropChanged(_str_idfParentMonitoringSession, c)) m.Add(_str_idfParentMonitoringSession, o.ObjectIdent + _str_idfParentMonitoringSession, o.ObjectIdent2 + _str_idfParentMonitoringSession, o.ObjectIdent3 + _str_idfParentMonitoringSession, "Int64?", o.idfParentMonitoringSession == null ? "" : o.idfParentMonitoringSession.ToString(), o.IsReadOnly(_str_idfParentMonitoringSession), o.IsInvisible(_str_idfParentMonitoringSession), o.IsRequired(_str_idfParentMonitoringSession)); } }, new field_info { _name = _str_strMonitoringSessionID, _formname = _str_strMonitoringSessionID, _type = "String", _get_func = o => o.strMonitoringSessionID, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strMonitoringSessionID != newval) o.strMonitoringSessionID = newval; }, _compare_func = (o, c, m) => { if (o.strMonitoringSessionID != c.strMonitoringSessionID || o.IsRIRPropChanged(_str_strMonitoringSessionID, c)) m.Add(_str_strMonitoringSessionID, o.ObjectIdent + _str_strMonitoringSessionID, o.ObjectIdent2 + _str_strMonitoringSessionID, o.ObjectIdent3 + _str_strMonitoringSessionID, "String", o.strMonitoringSessionID == null ? "" : o.strMonitoringSessionID.ToString(), o.IsReadOnly(_str_strMonitoringSessionID), o.IsInvisible(_str_strMonitoringSessionID), o.IsRequired(_str_strMonitoringSessionID)); } }, new field_info { _name = _str_datEnteredDate, _formname = _str_datEnteredDate, _type = "DateTime?", _get_func = o => o.datEnteredDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datEnteredDate != newval) o.datEnteredDate = newval; }, _compare_func = (o, c, m) => { if (o.datEnteredDate != c.datEnteredDate || o.IsRIRPropChanged(_str_datEnteredDate, c)) m.Add(_str_datEnteredDate, o.ObjectIdent + _str_datEnteredDate, o.ObjectIdent2 + _str_datEnteredDate, o.ObjectIdent3 + _str_datEnteredDate, "DateTime?", o.datEnteredDate == null ? "" : o.datEnteredDate.ToString(), o.IsReadOnly(_str_datEnteredDate), o.IsInvisible(_str_datEnteredDate), o.IsRequired(_str_datEnteredDate)); } }, new field_info { _name = _str_uidOfflineCaseID, _formname = _str_uidOfflineCaseID, _type = "Guid?", _get_func = o => o.uidOfflineCaseID, _set_func = (o, val) => { var newval = o.uidOfflineCaseID; if (o.uidOfflineCaseID != newval) o.uidOfflineCaseID = newval; }, _compare_func = (o, c, m) => { if (o.uidOfflineCaseID != c.uidOfflineCaseID || o.IsRIRPropChanged(_str_uidOfflineCaseID, c)) m.Add(_str_uidOfflineCaseID, o.ObjectIdent + _str_uidOfflineCaseID, o.ObjectIdent2 + _str_uidOfflineCaseID, o.ObjectIdent3 + _str_uidOfflineCaseID, "Guid?", o.uidOfflineCaseID == null ? "" : o.uidOfflineCaseID.ToString(), o.IsReadOnly(_str_uidOfflineCaseID), o.IsInvisible(_str_uidOfflineCaseID), o.IsRequired(_str_uidOfflineCaseID)); } }, new field_info { _name = _str_strCaseID, _formname = _str_strCaseID, _type = "String", _get_func = o => o.strCaseID, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strCaseID != newval) o.strCaseID = newval; }, _compare_func = (o, c, m) => { if (o.strCaseID != c.strCaseID || o.IsRIRPropChanged(_str_strCaseID, c)) m.Add(_str_strCaseID, o.ObjectIdent + _str_strCaseID, o.ObjectIdent2 + _str_strCaseID, o.ObjectIdent3 + _str_strCaseID, "String", o.strCaseID == null ? "" : o.strCaseID.ToString(), o.IsReadOnly(_str_strCaseID), o.IsInvisible(_str_strCaseID), o.IsRequired(_str_strCaseID)); } }, new field_info { _name = _str_idfsTentativeDiagnosis, _formname = _str_idfsTentativeDiagnosis, _type = "Int64?", _get_func = o => o.idfsTentativeDiagnosis, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsTentativeDiagnosis != newval) o.TentativeDiagnosis = o.TentativeDiagnosisLookup.FirstOrDefault(c => c.idfsDiagnosis == newval); if (o.idfsTentativeDiagnosis != newval) o.idfsTentativeDiagnosis = newval; }, _compare_func = (o, c, m) => { if (o.idfsTentativeDiagnosis != c.idfsTentativeDiagnosis || o.IsRIRPropChanged(_str_idfsTentativeDiagnosis, c)) m.Add(_str_idfsTentativeDiagnosis, o.ObjectIdent + _str_idfsTentativeDiagnosis, o.ObjectIdent2 + _str_idfsTentativeDiagnosis, o.ObjectIdent3 + _str_idfsTentativeDiagnosis, "Int64?", o.idfsTentativeDiagnosis == null ? "" : o.idfsTentativeDiagnosis.ToString(), o.IsReadOnly(_str_idfsTentativeDiagnosis), o.IsInvisible(_str_idfsTentativeDiagnosis), o.IsRequired(_str_idfsTentativeDiagnosis)); } }, new field_info { _name = _str_idfsTentativeDiagnosis1, _formname = _str_idfsTentativeDiagnosis1, _type = "Int64?", _get_func = o => o.idfsTentativeDiagnosis1, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsTentativeDiagnosis1 != newval) o.TentativeDiagnosis1 = o.TentativeDiagnosis1Lookup.FirstOrDefault(c => c.idfsDiagnosis == newval); if (o.idfsTentativeDiagnosis1 != newval) o.idfsTentativeDiagnosis1 = newval; }, _compare_func = (o, c, m) => { if (o.idfsTentativeDiagnosis1 != c.idfsTentativeDiagnosis1 || o.IsRIRPropChanged(_str_idfsTentativeDiagnosis1, c)) m.Add(_str_idfsTentativeDiagnosis1, o.ObjectIdent + _str_idfsTentativeDiagnosis1, o.ObjectIdent2 + _str_idfsTentativeDiagnosis1, o.ObjectIdent3 + _str_idfsTentativeDiagnosis1, "Int64?", o.idfsTentativeDiagnosis1 == null ? "" : o.idfsTentativeDiagnosis1.ToString(), o.IsReadOnly(_str_idfsTentativeDiagnosis1), o.IsInvisible(_str_idfsTentativeDiagnosis1), o.IsRequired(_str_idfsTentativeDiagnosis1)); } }, new field_info { _name = _str_idfsTentativeDiagnosis2, _formname = _str_idfsTentativeDiagnosis2, _type = "Int64?", _get_func = o => o.idfsTentativeDiagnosis2, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsTentativeDiagnosis2 != newval) o.TentativeDiagnosis2 = o.TentativeDiagnosis2Lookup.FirstOrDefault(c => c.idfsDiagnosis == newval); if (o.idfsTentativeDiagnosis2 != newval) o.idfsTentativeDiagnosis2 = newval; }, _compare_func = (o, c, m) => { if (o.idfsTentativeDiagnosis2 != c.idfsTentativeDiagnosis2 || o.IsRIRPropChanged(_str_idfsTentativeDiagnosis2, c)) m.Add(_str_idfsTentativeDiagnosis2, o.ObjectIdent + _str_idfsTentativeDiagnosis2, o.ObjectIdent2 + _str_idfsTentativeDiagnosis2, o.ObjectIdent3 + _str_idfsTentativeDiagnosis2, "Int64?", o.idfsTentativeDiagnosis2 == null ? "" : o.idfsTentativeDiagnosis2.ToString(), o.IsReadOnly(_str_idfsTentativeDiagnosis2), o.IsInvisible(_str_idfsTentativeDiagnosis2), o.IsRequired(_str_idfsTentativeDiagnosis2)); } }, new field_info { _name = _str_idfsFinalDiagnosis, _formname = _str_idfsFinalDiagnosis, _type = "Int64?", _get_func = o => o.idfsFinalDiagnosis, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsFinalDiagnosis != newval) o.FinalDiagnosis = o.FinalDiagnosisLookup.FirstOrDefault(c => c.idfsDiagnosis == newval); if (o.idfsFinalDiagnosis != newval) o.idfsFinalDiagnosis = newval; }, _compare_func = (o, c, m) => { if (o.idfsFinalDiagnosis != c.idfsFinalDiagnosis || o.IsRIRPropChanged(_str_idfsFinalDiagnosis, c)) m.Add(_str_idfsFinalDiagnosis, o.ObjectIdent + _str_idfsFinalDiagnosis, o.ObjectIdent2 + _str_idfsFinalDiagnosis, o.ObjectIdent3 + _str_idfsFinalDiagnosis, "Int64?", o.idfsFinalDiagnosis == null ? "" : o.idfsFinalDiagnosis.ToString(), o.IsReadOnly(_str_idfsFinalDiagnosis), o.IsInvisible(_str_idfsFinalDiagnosis), o.IsRequired(_str_idfsFinalDiagnosis)); } }, new field_info { _name = _str_idfsYNTestsConducted, _formname = _str_idfsYNTestsConducted, _type = "Int64?", _get_func = o => o.idfsYNTestsConducted, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsYNTestsConducted != newval) o.TestsConducted = o.TestsConductedLookup.FirstOrDefault(c => c.idfsBaseReference == newval); if (o.idfsYNTestsConducted != newval) o.idfsYNTestsConducted = newval; }, _compare_func = (o, c, m) => { if (o.idfsYNTestsConducted != c.idfsYNTestsConducted || o.IsRIRPropChanged(_str_idfsYNTestsConducted, c)) m.Add(_str_idfsYNTestsConducted, o.ObjectIdent + _str_idfsYNTestsConducted, o.ObjectIdent2 + _str_idfsYNTestsConducted, o.ObjectIdent3 + _str_idfsYNTestsConducted, "Int64?", o.idfsYNTestsConducted == null ? "" : o.idfsYNTestsConducted.ToString(), o.IsReadOnly(_str_idfsYNTestsConducted), o.IsInvisible(_str_idfsYNTestsConducted), o.IsRequired(_str_idfsYNTestsConducted)); } }, new field_info { _name = _str_blnEnableTestsConducted, _formname = _str_blnEnableTestsConducted, _type = "Boolean?", _get_func = o => o.blnEnableTestsConducted, _set_func = (o, val) => { var newval = ParsingHelper.ParseBooleanNullable(val); if (o.blnEnableTestsConducted != newval) o.blnEnableTestsConducted = newval; }, _compare_func = (o, c, m) => { if (o.blnEnableTestsConducted != c.blnEnableTestsConducted || o.IsRIRPropChanged(_str_blnEnableTestsConducted, c)) m.Add(_str_blnEnableTestsConducted, o.ObjectIdent + _str_blnEnableTestsConducted, o.ObjectIdent2 + _str_blnEnableTestsConducted, o.ObjectIdent3 + _str_blnEnableTestsConducted, "Boolean?", o.blnEnableTestsConducted == null ? "" : o.blnEnableTestsConducted.ToString(), o.IsReadOnly(_str_blnEnableTestsConducted), o.IsInvisible(_str_blnEnableTestsConducted), o.IsRequired(_str_blnEnableTestsConducted)); } }, new field_info { _name = _str_idfInvestigatedByOffice, _formname = _str_idfInvestigatedByOffice, _type = "Int64?", _get_func = o => o.idfInvestigatedByOffice, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfInvestigatedByOffice != newval) o.idfInvestigatedByOffice = newval; }, _compare_func = (o, c, m) => { if (o.idfInvestigatedByOffice != c.idfInvestigatedByOffice || o.IsRIRPropChanged(_str_idfInvestigatedByOffice, c)) m.Add(_str_idfInvestigatedByOffice, o.ObjectIdent + _str_idfInvestigatedByOffice, o.ObjectIdent2 + _str_idfInvestigatedByOffice, o.ObjectIdent3 + _str_idfInvestigatedByOffice, "Int64?", o.idfInvestigatedByOffice == null ? "" : o.idfInvestigatedByOffice.ToString(), o.IsReadOnly(_str_idfInvestigatedByOffice), o.IsInvisible(_str_idfInvestigatedByOffice), o.IsRequired(_str_idfInvestigatedByOffice)); } }, new field_info { _name = _str_strInvestigatedByOffice, _formname = _str_strInvestigatedByOffice, _type = "String", _get_func = o => o.strInvestigatedByOffice, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strInvestigatedByOffice != newval) o.strInvestigatedByOffice = newval; }, _compare_func = (o, c, m) => { if (o.strInvestigatedByOffice != c.strInvestigatedByOffice || o.IsRIRPropChanged(_str_strInvestigatedByOffice, c)) m.Add(_str_strInvestigatedByOffice, o.ObjectIdent + _str_strInvestigatedByOffice, o.ObjectIdent2 + _str_strInvestigatedByOffice, o.ObjectIdent3 + _str_strInvestigatedByOffice, "String", o.strInvestigatedByOffice == null ? "" : o.strInvestigatedByOffice.ToString(), o.IsReadOnly(_str_strInvestigatedByOffice), o.IsInvisible(_str_strInvestigatedByOffice), o.IsRequired(_str_strInvestigatedByOffice)); } }, new field_info { _name = _str_idfPersonInvestigatedBy, _formname = _str_idfPersonInvestigatedBy, _type = "Int64?", _get_func = o => o.idfPersonInvestigatedBy, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfPersonInvestigatedBy != newval) o.PersonInvestigatedBy = o.PersonInvestigatedByLookup.FirstOrDefault(c => c.idfPerson == newval); if (o.idfPersonInvestigatedBy != newval) o.idfPersonInvestigatedBy = newval; }, _compare_func = (o, c, m) => { if (o.idfPersonInvestigatedBy != c.idfPersonInvestigatedBy || o.IsRIRPropChanged(_str_idfPersonInvestigatedBy, c)) m.Add(_str_idfPersonInvestigatedBy, o.ObjectIdent + _str_idfPersonInvestigatedBy, o.ObjectIdent2 + _str_idfPersonInvestigatedBy, o.ObjectIdent3 + _str_idfPersonInvestigatedBy, "Int64?", o.idfPersonInvestigatedBy == null ? "" : o.idfPersonInvestigatedBy.ToString(), o.IsReadOnly(_str_idfPersonInvestigatedBy), o.IsInvisible(_str_idfPersonInvestigatedBy), o.IsRequired(_str_idfPersonInvestigatedBy)); } }, new field_info { _name = _str_strPersonInvestigatedBy, _formname = _str_strPersonInvestigatedBy, _type = "String", _get_func = o => o.strPersonInvestigatedBy, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strPersonInvestigatedBy != newval) o.strPersonInvestigatedBy = newval; }, _compare_func = (o, c, m) => { if (o.strPersonInvestigatedBy != c.strPersonInvestigatedBy || o.IsRIRPropChanged(_str_strPersonInvestigatedBy, c)) m.Add(_str_strPersonInvestigatedBy, o.ObjectIdent + _str_strPersonInvestigatedBy, o.ObjectIdent2 + _str_strPersonInvestigatedBy, o.ObjectIdent3 + _str_strPersonInvestigatedBy, "String", o.strPersonInvestigatedBy == null ? "" : o.strPersonInvestigatedBy.ToString(), o.IsReadOnly(_str_strPersonInvestigatedBy), o.IsInvisible(_str_strPersonInvestigatedBy), o.IsRequired(_str_strPersonInvestigatedBy)); } }, new field_info { _name = _str_idfPersonEnteredBy, _formname = _str_idfPersonEnteredBy, _type = "Int64?", _get_func = o => o.idfPersonEnteredBy, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfPersonEnteredBy != newval) o.idfPersonEnteredBy = newval; }, _compare_func = (o, c, m) => { if (o.idfPersonEnteredBy != c.idfPersonEnteredBy || o.IsRIRPropChanged(_str_idfPersonEnteredBy, c)) m.Add(_str_idfPersonEnteredBy, o.ObjectIdent + _str_idfPersonEnteredBy, o.ObjectIdent2 + _str_idfPersonEnteredBy, o.ObjectIdent3 + _str_idfPersonEnteredBy, "Int64?", o.idfPersonEnteredBy == null ? "" : o.idfPersonEnteredBy.ToString(), o.IsReadOnly(_str_idfPersonEnteredBy), o.IsInvisible(_str_idfPersonEnteredBy), o.IsRequired(_str_idfPersonEnteredBy)); } }, new field_info { _name = _str_strPersonEnteredByName, _formname = _str_strPersonEnteredByName, _type = "String", _get_func = o => o.strPersonEnteredByName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strPersonEnteredByName != newval) o.strPersonEnteredByName = newval; }, _compare_func = (o, c, m) => { if (o.strPersonEnteredByName != c.strPersonEnteredByName || o.IsRIRPropChanged(_str_strPersonEnteredByName, c)) m.Add(_str_strPersonEnteredByName, o.ObjectIdent + _str_strPersonEnteredByName, o.ObjectIdent2 + _str_strPersonEnteredByName, o.ObjectIdent3 + _str_strPersonEnteredByName, "String", o.strPersonEnteredByName == null ? "" : o.strPersonEnteredByName.ToString(), o.IsReadOnly(_str_strPersonEnteredByName), o.IsInvisible(_str_strPersonEnteredByName), o.IsRequired(_str_strPersonEnteredByName)); } }, new field_info { _name = _str_idfReportedByOffice, _formname = _str_idfReportedByOffice, _type = "Int64?", _get_func = o => o.idfReportedByOffice, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfReportedByOffice != newval) o.idfReportedByOffice = newval; }, _compare_func = (o, c, m) => { if (o.idfReportedByOffice != c.idfReportedByOffice || o.IsRIRPropChanged(_str_idfReportedByOffice, c)) m.Add(_str_idfReportedByOffice, o.ObjectIdent + _str_idfReportedByOffice, o.ObjectIdent2 + _str_idfReportedByOffice, o.ObjectIdent3 + _str_idfReportedByOffice, "Int64?", o.idfReportedByOffice == null ? "" : o.idfReportedByOffice.ToString(), o.IsReadOnly(_str_idfReportedByOffice), o.IsInvisible(_str_idfReportedByOffice), o.IsRequired(_str_idfReportedByOffice)); } }, new field_info { _name = _str_strReportedByOffice, _formname = _str_strReportedByOffice, _type = "String", _get_func = o => o.strReportedByOffice, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strReportedByOffice != newval) o.strReportedByOffice = newval; }, _compare_func = (o, c, m) => { if (o.strReportedByOffice != c.strReportedByOffice || o.IsRIRPropChanged(_str_strReportedByOffice, c)) m.Add(_str_strReportedByOffice, o.ObjectIdent + _str_strReportedByOffice, o.ObjectIdent2 + _str_strReportedByOffice, o.ObjectIdent3 + _str_strReportedByOffice, "String", o.strReportedByOffice == null ? "" : o.strReportedByOffice.ToString(), o.IsReadOnly(_str_strReportedByOffice), o.IsInvisible(_str_strReportedByOffice), o.IsRequired(_str_strReportedByOffice)); } }, new field_info { _name = _str_idfPersonReportedBy, _formname = _str_idfPersonReportedBy, _type = "Int64?", _get_func = o => o.idfPersonReportedBy, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfPersonReportedBy != newval) o.idfPersonReportedBy = newval; }, _compare_func = (o, c, m) => { if (o.idfPersonReportedBy != c.idfPersonReportedBy || o.IsRIRPropChanged(_str_idfPersonReportedBy, c)) m.Add(_str_idfPersonReportedBy, o.ObjectIdent + _str_idfPersonReportedBy, o.ObjectIdent2 + _str_idfPersonReportedBy, o.ObjectIdent3 + _str_idfPersonReportedBy, "Int64?", o.idfPersonReportedBy == null ? "" : o.idfPersonReportedBy.ToString(), o.IsReadOnly(_str_idfPersonReportedBy), o.IsInvisible(_str_idfPersonReportedBy), o.IsRequired(_str_idfPersonReportedBy)); } }, new field_info { _name = _str_strPersonReportedBy, _formname = _str_strPersonReportedBy, _type = "String", _get_func = o => o.strPersonReportedBy, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strPersonReportedBy != newval) o.strPersonReportedBy = newval; }, _compare_func = (o, c, m) => { if (o.strPersonReportedBy != c.strPersonReportedBy || o.IsRIRPropChanged(_str_strPersonReportedBy, c)) m.Add(_str_strPersonReportedBy, o.ObjectIdent + _str_strPersonReportedBy, o.ObjectIdent2 + _str_strPersonReportedBy, o.ObjectIdent3 + _str_strPersonReportedBy, "String", o.strPersonReportedBy == null ? "" : o.strPersonReportedBy.ToString(), o.IsReadOnly(_str_strPersonReportedBy), o.IsInvisible(_str_strPersonReportedBy), o.IsRequired(_str_strPersonReportedBy)); } }, new field_info { _name = _str_idfObservation, _formname = _str_idfObservation, _type = "Int64?", _get_func = o => o.idfObservation, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfObservation != newval) o.idfObservation = newval; }, _compare_func = (o, c, m) => { if (o.idfObservation != c.idfObservation || o.IsRIRPropChanged(_str_idfObservation, c)) m.Add(_str_idfObservation, o.ObjectIdent + _str_idfObservation, o.ObjectIdent2 + _str_idfObservation, o.ObjectIdent3 + _str_idfObservation, "Int64?", o.idfObservation == null ? "" : o.idfObservation.ToString(), o.IsReadOnly(_str_idfObservation), o.IsInvisible(_str_idfObservation), o.IsRequired(_str_idfObservation)); } }, new field_info { _name = _str_idfsFormTemplate, _formname = _str_idfsFormTemplate, _type = "Int64?", _get_func = o => o.idfsFormTemplate, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsFormTemplate != newval) o.idfsFormTemplate = newval; }, _compare_func = (o, c, m) => { if (o.idfsFormTemplate != c.idfsFormTemplate || o.IsRIRPropChanged(_str_idfsFormTemplate, c)) m.Add(_str_idfsFormTemplate, o.ObjectIdent + _str_idfsFormTemplate, o.ObjectIdent2 + _str_idfsFormTemplate, o.ObjectIdent3 + _str_idfsFormTemplate, "Int64?", o.idfsFormTemplate == null ? "" : o.idfsFormTemplate.ToString(), o.IsReadOnly(_str_idfsFormTemplate), o.IsInvisible(_str_idfsFormTemplate), o.IsRequired(_str_idfsFormTemplate)); } }, new field_info { _name = _str_idfsSite, _formname = _str_idfsSite, _type = "Int64", _get_func = o => o.idfsSite, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsSite != newval) o.Site = o.SiteLookup.FirstOrDefault(c => c.idfsSite == newval); if (o.idfsSite != newval) o.idfsSite = newval; }, _compare_func = (o, c, m) => { if (o.idfsSite != c.idfsSite || o.IsRIRPropChanged(_str_idfsSite, c)) m.Add(_str_idfsSite, o.ObjectIdent + _str_idfsSite, o.ObjectIdent2 + _str_idfsSite, o.ObjectIdent3 + _str_idfsSite, "Int64", o.idfsSite == null ? "" : o.idfsSite.ToString(), o.IsReadOnly(_str_idfsSite), o.IsInvisible(_str_idfsSite), o.IsRequired(_str_idfsSite)); } }, new field_info { _name = _str_datReportDate, _formname = _str_datReportDate, _type = "DateTime?", _get_func = o => o.datReportDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datReportDate != newval) o.datReportDate = newval; }, _compare_func = (o, c, m) => { if (o.datReportDate != c.datReportDate || o.IsRIRPropChanged(_str_datReportDate, c)) m.Add(_str_datReportDate, o.ObjectIdent + _str_datReportDate, o.ObjectIdent2 + _str_datReportDate, o.ObjectIdent3 + _str_datReportDate, "DateTime?", o.datReportDate == null ? "" : o.datReportDate.ToString(), o.IsReadOnly(_str_datReportDate), o.IsInvisible(_str_datReportDate), o.IsRequired(_str_datReportDate)); } }, new field_info { _name = _str_datAssignedDate, _formname = _str_datAssignedDate, _type = "DateTime?", _get_func = o => o.datAssignedDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datAssignedDate != newval) o.datAssignedDate = newval; }, _compare_func = (o, c, m) => { if (o.datAssignedDate != c.datAssignedDate || o.IsRIRPropChanged(_str_datAssignedDate, c)) m.Add(_str_datAssignedDate, o.ObjectIdent + _str_datAssignedDate, o.ObjectIdent2 + _str_datAssignedDate, o.ObjectIdent3 + _str_datAssignedDate, "DateTime?", o.datAssignedDate == null ? "" : o.datAssignedDate.ToString(), o.IsReadOnly(_str_datAssignedDate), o.IsInvisible(_str_datAssignedDate), o.IsRequired(_str_datAssignedDate)); } }, new field_info { _name = _str_datInvestigationDate, _formname = _str_datInvestigationDate, _type = "DateTime?", _get_func = o => o.datInvestigationDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datInvestigationDate != newval) o.datInvestigationDate = newval; }, _compare_func = (o, c, m) => { if (o.datInvestigationDate != c.datInvestigationDate || o.IsRIRPropChanged(_str_datInvestigationDate, c)) m.Add(_str_datInvestigationDate, o.ObjectIdent + _str_datInvestigationDate, o.ObjectIdent2 + _str_datInvestigationDate, o.ObjectIdent3 + _str_datInvestigationDate, "DateTime?", o.datInvestigationDate == null ? "" : o.datInvestigationDate.ToString(), o.IsReadOnly(_str_datInvestigationDate), o.IsInvisible(_str_datInvestigationDate), o.IsRequired(_str_datInvestigationDate)); } }, new field_info { _name = _str_datTentativeDiagnosisDate, _formname = _str_datTentativeDiagnosisDate, _type = "DateTime?", _get_func = o => o.datTentativeDiagnosisDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datTentativeDiagnosisDate != newval) o.datTentativeDiagnosisDate = newval; }, _compare_func = (o, c, m) => { if (o.datTentativeDiagnosisDate != c.datTentativeDiagnosisDate || o.IsRIRPropChanged(_str_datTentativeDiagnosisDate, c)) m.Add(_str_datTentativeDiagnosisDate, o.ObjectIdent + _str_datTentativeDiagnosisDate, o.ObjectIdent2 + _str_datTentativeDiagnosisDate, o.ObjectIdent3 + _str_datTentativeDiagnosisDate, "DateTime?", o.datTentativeDiagnosisDate == null ? "" : o.datTentativeDiagnosisDate.ToString(), o.IsReadOnly(_str_datTentativeDiagnosisDate), o.IsInvisible(_str_datTentativeDiagnosisDate), o.IsRequired(_str_datTentativeDiagnosisDate)); } }, new field_info { _name = _str_datTentativeDiagnosis1Date, _formname = _str_datTentativeDiagnosis1Date, _type = "DateTime?", _get_func = o => o.datTentativeDiagnosis1Date, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datTentativeDiagnosis1Date != newval) o.datTentativeDiagnosis1Date = newval; }, _compare_func = (o, c, m) => { if (o.datTentativeDiagnosis1Date != c.datTentativeDiagnosis1Date || o.IsRIRPropChanged(_str_datTentativeDiagnosis1Date, c)) m.Add(_str_datTentativeDiagnosis1Date, o.ObjectIdent + _str_datTentativeDiagnosis1Date, o.ObjectIdent2 + _str_datTentativeDiagnosis1Date, o.ObjectIdent3 + _str_datTentativeDiagnosis1Date, "DateTime?", o.datTentativeDiagnosis1Date == null ? "" : o.datTentativeDiagnosis1Date.ToString(), o.IsReadOnly(_str_datTentativeDiagnosis1Date), o.IsInvisible(_str_datTentativeDiagnosis1Date), o.IsRequired(_str_datTentativeDiagnosis1Date)); } }, new field_info { _name = _str_datTentativeDiagnosis2Date, _formname = _str_datTentativeDiagnosis2Date, _type = "DateTime?", _get_func = o => o.datTentativeDiagnosis2Date, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datTentativeDiagnosis2Date != newval) o.datTentativeDiagnosis2Date = newval; }, _compare_func = (o, c, m) => { if (o.datTentativeDiagnosis2Date != c.datTentativeDiagnosis2Date || o.IsRIRPropChanged(_str_datTentativeDiagnosis2Date, c)) m.Add(_str_datTentativeDiagnosis2Date, o.ObjectIdent + _str_datTentativeDiagnosis2Date, o.ObjectIdent2 + _str_datTentativeDiagnosis2Date, o.ObjectIdent3 + _str_datTentativeDiagnosis2Date, "DateTime?", o.datTentativeDiagnosis2Date == null ? "" : o.datTentativeDiagnosis2Date.ToString(), o.IsReadOnly(_str_datTentativeDiagnosis2Date), o.IsInvisible(_str_datTentativeDiagnosis2Date), o.IsRequired(_str_datTentativeDiagnosis2Date)); } }, new field_info { _name = _str_datFinalDiagnosisDate, _formname = _str_datFinalDiagnosisDate, _type = "DateTime?", _get_func = o => o.datFinalDiagnosisDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datFinalDiagnosisDate != newval) o.datFinalDiagnosisDate = newval; }, _compare_func = (o, c, m) => { if (o.datFinalDiagnosisDate != c.datFinalDiagnosisDate || o.IsRIRPropChanged(_str_datFinalDiagnosisDate, c)) m.Add(_str_datFinalDiagnosisDate, o.ObjectIdent + _str_datFinalDiagnosisDate, o.ObjectIdent2 + _str_datFinalDiagnosisDate, o.ObjectIdent3 + _str_datFinalDiagnosisDate, "DateTime?", o.datFinalDiagnosisDate == null ? "" : o.datFinalDiagnosisDate.ToString(), o.IsReadOnly(_str_datFinalDiagnosisDate), o.IsInvisible(_str_datFinalDiagnosisDate), o.IsRequired(_str_datFinalDiagnosisDate)); } }, new field_info { _name = _str_idfsCaseReportType, _formname = _str_idfsCaseReportType, _type = "Int64?", _get_func = o => o.idfsCaseReportType, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsCaseReportType != newval) o.CaseReportType = o.CaseReportTypeLookup.FirstOrDefault(c => c.idfsBaseReference == newval); if (o.idfsCaseReportType != newval) o.idfsCaseReportType = newval; }, _compare_func = (o, c, m) => { if (o.idfsCaseReportType != c.idfsCaseReportType || o.IsRIRPropChanged(_str_idfsCaseReportType, c)) m.Add(_str_idfsCaseReportType, o.ObjectIdent + _str_idfsCaseReportType, o.ObjectIdent2 + _str_idfsCaseReportType, o.ObjectIdent3 + _str_idfsCaseReportType, "Int64?", o.idfsCaseReportType == null ? "" : o.idfsCaseReportType.ToString(), o.IsReadOnly(_str_idfsCaseReportType), o.IsInvisible(_str_idfsCaseReportType), o.IsRequired(_str_idfsCaseReportType)); } }, new field_info { _name = _str_strSampleNotes, _formname = _str_strSampleNotes, _type = "String", _get_func = o => o.strSampleNotes, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strSampleNotes != newval) o.strSampleNotes = newval; }, _compare_func = (o, c, m) => { if (o.strSampleNotes != c.strSampleNotes || o.IsRIRPropChanged(_str_strSampleNotes, c)) m.Add(_str_strSampleNotes, o.ObjectIdent + _str_strSampleNotes, o.ObjectIdent2 + _str_strSampleNotes, o.ObjectIdent3 + _str_strSampleNotes, "String", o.strSampleNotes == null ? "" : o.strSampleNotes.ToString(), o.IsReadOnly(_str_strSampleNotes), o.IsInvisible(_str_strSampleNotes), o.IsRequired(_str_strSampleNotes)); } }, new field_info { _name = _str_strTestNotes, _formname = _str_strTestNotes, _type = "String", _get_func = o => o.strTestNotes, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strTestNotes != newval) o.strTestNotes = newval; }, _compare_func = (o, c, m) => { if (o.strTestNotes != c.strTestNotes || o.IsRIRPropChanged(_str_strTestNotes, c)) m.Add(_str_strTestNotes, o.ObjectIdent + _str_strTestNotes, o.ObjectIdent2 + _str_strTestNotes, o.ObjectIdent3 + _str_strTestNotes, "String", o.strTestNotes == null ? "" : o.strTestNotes.ToString(), o.IsReadOnly(_str_strTestNotes), o.IsInvisible(_str_strTestNotes), o.IsRequired(_str_strTestNotes)); } }, new field_info { _name = _str_strSummaryNotes, _formname = _str_strSummaryNotes, _type = "String", _get_func = o => o.strSummaryNotes, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strSummaryNotes != newval) o.strSummaryNotes = newval; }, _compare_func = (o, c, m) => { if (o.strSummaryNotes != c.strSummaryNotes || o.IsRIRPropChanged(_str_strSummaryNotes, c)) m.Add(_str_strSummaryNotes, o.ObjectIdent + _str_strSummaryNotes, o.ObjectIdent2 + _str_strSummaryNotes, o.ObjectIdent3 + _str_strSummaryNotes, "String", o.strSummaryNotes == null ? "" : o.strSummaryNotes.ToString(), o.IsReadOnly(_str_strSummaryNotes), o.IsInvisible(_str_strSummaryNotes), o.IsRequired(_str_strSummaryNotes)); } }, new field_info { _name = _str_strClinicalNotes, _formname = _str_strClinicalNotes, _type = "String", _get_func = o => o.strClinicalNotes, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strClinicalNotes != newval) o.strClinicalNotes = newval; }, _compare_func = (o, c, m) => { if (o.strClinicalNotes != c.strClinicalNotes || o.IsRIRPropChanged(_str_strClinicalNotes, c)) m.Add(_str_strClinicalNotes, o.ObjectIdent + _str_strClinicalNotes, o.ObjectIdent2 + _str_strClinicalNotes, o.ObjectIdent3 + _str_strClinicalNotes, "String", o.strClinicalNotes == null ? "" : o.strClinicalNotes.ToString(), o.IsReadOnly(_str_strClinicalNotes), o.IsInvisible(_str_strClinicalNotes), o.IsRequired(_str_strClinicalNotes)); } }, new field_info { _name = _str_strFieldAccessionID, _formname = _str_strFieldAccessionID, _type = "String", _get_func = o => o.strFieldAccessionID, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strFieldAccessionID != newval) o.strFieldAccessionID = newval; }, _compare_func = (o, c, m) => { if (o.strFieldAccessionID != c.strFieldAccessionID || o.IsRIRPropChanged(_str_strFieldAccessionID, c)) m.Add(_str_strFieldAccessionID, o.ObjectIdent + _str_strFieldAccessionID, o.ObjectIdent2 + _str_strFieldAccessionID, o.ObjectIdent3 + _str_strFieldAccessionID, "String", o.strFieldAccessionID == null ? "" : o.strFieldAccessionID.ToString(), o.IsReadOnly(_str_strFieldAccessionID), o.IsInvisible(_str_strFieldAccessionID), o.IsRequired(_str_strFieldAccessionID)); } }, new field_info { _name = _str_idfFarm, _formname = _str_idfFarm, _type = "Int64", _get_func = o => o.idfFarm, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfFarm != newval) o.idfFarm = newval; }, _compare_func = (o, c, m) => { if (o.idfFarm != c.idfFarm || o.IsRIRPropChanged(_str_idfFarm, c)) m.Add(_str_idfFarm, o.ObjectIdent + _str_idfFarm, o.ObjectIdent2 + _str_idfFarm, o.ObjectIdent3 + _str_idfFarm, "Int64", o.idfFarm == null ? "" : o.idfFarm.ToString(), o.IsReadOnly(_str_idfFarm), o.IsInvisible(_str_idfFarm), o.IsRequired(_str_idfFarm)); } }, new field_info { _name = _str_idfRootFarm, _formname = _str_idfRootFarm, _type = "Int64?", _get_func = o => o.idfRootFarm, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfRootFarm != newval) o.idfRootFarm = newval; }, _compare_func = (o, c, m) => { if (o.idfRootFarm != c.idfRootFarm || o.IsRIRPropChanged(_str_idfRootFarm, c)) m.Add(_str_idfRootFarm, o.ObjectIdent + _str_idfRootFarm, o.ObjectIdent2 + _str_idfRootFarm, o.ObjectIdent3 + _str_idfRootFarm, "Int64?", o.idfRootFarm == null ? "" : o.idfRootFarm.ToString(), o.IsReadOnly(_str_idfRootFarm), o.IsInvisible(_str_idfRootFarm), o.IsRequired(_str_idfRootFarm)); } }, new field_info { _name = _str_strFinalDiagnosisOIECode, _formname = _str_strFinalDiagnosisOIECode, _type = "String", _get_func = o => o.strFinalDiagnosisOIECode, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strFinalDiagnosisOIECode != newval) o.strFinalDiagnosisOIECode = newval; }, _compare_func = (o, c, m) => { if (o.strFinalDiagnosisOIECode != c.strFinalDiagnosisOIECode || o.IsRIRPropChanged(_str_strFinalDiagnosisOIECode, c)) m.Add(_str_strFinalDiagnosisOIECode, o.ObjectIdent + _str_strFinalDiagnosisOIECode, o.ObjectIdent2 + _str_strFinalDiagnosisOIECode, o.ObjectIdent3 + _str_strFinalDiagnosisOIECode, "String", o.strFinalDiagnosisOIECode == null ? "" : o.strFinalDiagnosisOIECode.ToString(), o.IsReadOnly(_str_strFinalDiagnosisOIECode), o.IsInvisible(_str_strFinalDiagnosisOIECode), o.IsRequired(_str_strFinalDiagnosisOIECode)); } }, new field_info { _name = _str_strTentativeDiagnosisOIECode, _formname = _str_strTentativeDiagnosisOIECode, _type = "String", _get_func = o => o.strTentativeDiagnosisOIECode, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strTentativeDiagnosisOIECode != newval) o.strTentativeDiagnosisOIECode = newval; }, _compare_func = (o, c, m) => { if (o.strTentativeDiagnosisOIECode != c.strTentativeDiagnosisOIECode || o.IsRIRPropChanged(_str_strTentativeDiagnosisOIECode, c)) m.Add(_str_strTentativeDiagnosisOIECode, o.ObjectIdent + _str_strTentativeDiagnosisOIECode, o.ObjectIdent2 + _str_strTentativeDiagnosisOIECode, o.ObjectIdent3 + _str_strTentativeDiagnosisOIECode, "String", o.strTentativeDiagnosisOIECode == null ? "" : o.strTentativeDiagnosisOIECode.ToString(), o.IsReadOnly(_str_strTentativeDiagnosisOIECode), o.IsInvisible(_str_strTentativeDiagnosisOIECode), o.IsRequired(_str_strTentativeDiagnosisOIECode)); } }, new field_info { _name = _str_strTentativeDiagnosis1OIECode, _formname = _str_strTentativeDiagnosis1OIECode, _type = "String", _get_func = o => o.strTentativeDiagnosis1OIECode, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strTentativeDiagnosis1OIECode != newval) o.strTentativeDiagnosis1OIECode = newval; }, _compare_func = (o, c, m) => { if (o.strTentativeDiagnosis1OIECode != c.strTentativeDiagnosis1OIECode || o.IsRIRPropChanged(_str_strTentativeDiagnosis1OIECode, c)) m.Add(_str_strTentativeDiagnosis1OIECode, o.ObjectIdent + _str_strTentativeDiagnosis1OIECode, o.ObjectIdent2 + _str_strTentativeDiagnosis1OIECode, o.ObjectIdent3 + _str_strTentativeDiagnosis1OIECode, "String", o.strTentativeDiagnosis1OIECode == null ? "" : o.strTentativeDiagnosis1OIECode.ToString(), o.IsReadOnly(_str_strTentativeDiagnosis1OIECode), o.IsInvisible(_str_strTentativeDiagnosis1OIECode), o.IsRequired(_str_strTentativeDiagnosis1OIECode)); } }, new field_info { _name = _str_strTentativeDiagnosis2OIECode, _formname = _str_strTentativeDiagnosis2OIECode, _type = "String", _get_func = o => o.strTentativeDiagnosis2OIECode, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strTentativeDiagnosis2OIECode != newval) o.strTentativeDiagnosis2OIECode = newval; }, _compare_func = (o, c, m) => { if (o.strTentativeDiagnosis2OIECode != c.strTentativeDiagnosis2OIECode || o.IsRIRPropChanged(_str_strTentativeDiagnosis2OIECode, c)) m.Add(_str_strTentativeDiagnosis2OIECode, o.ObjectIdent + _str_strTentativeDiagnosis2OIECode, o.ObjectIdent2 + _str_strTentativeDiagnosis2OIECode, o.ObjectIdent3 + _str_strTentativeDiagnosis2OIECode, "String", o.strTentativeDiagnosis2OIECode == null ? "" : o.strTentativeDiagnosis2OIECode.ToString(), o.IsReadOnly(_str_strTentativeDiagnosis2OIECode), o.IsInvisible(_str_strTentativeDiagnosis2OIECode), o.IsRequired(_str_strTentativeDiagnosis2OIECode)); } }, new field_info { _name = _str_datModificationForArchiveDate, _formname = _str_datModificationForArchiveDate, _type = "DateTime?", _get_func = o => o.datModificationForArchiveDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datModificationForArchiveDate != newval) o.datModificationForArchiveDate = newval; }, _compare_func = (o, c, m) => { if (o.datModificationForArchiveDate != c.datModificationForArchiveDate || o.IsRIRPropChanged(_str_datModificationForArchiveDate, c)) m.Add(_str_datModificationForArchiveDate, o.ObjectIdent + _str_datModificationForArchiveDate, o.ObjectIdent2 + _str_datModificationForArchiveDate, o.ObjectIdent3 + _str_datModificationForArchiveDate, "DateTime?", o.datModificationForArchiveDate == null ? "" : o.datModificationForArchiveDate.ToString(), o.IsReadOnly(_str_datModificationForArchiveDate), o.IsInvisible(_str_datModificationForArchiveDate), o.IsRequired(_str_datModificationForArchiveDate)); } }, new field_info { _name = _str_strDiagnosis, _formname = _str_strDiagnosis, _type = "string", _get_func = o => o.strDiagnosis, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.strDiagnosis != c.strDiagnosis || o.IsRIRPropChanged(_str_strDiagnosis, c)) { m.Add(_str_strDiagnosis, o.ObjectIdent + _str_strDiagnosis, o.ObjectIdent2 + _str_strDiagnosis, o.ObjectIdent3 + _str_strDiagnosis, "string", o.strDiagnosis == null ? "" : o.strDiagnosis.ToString(), o.IsReadOnly(_str_strDiagnosis), o.IsInvisible(_str_strDiagnosis), o.IsRequired(_str_strDiagnosis)); } } }, new field_info { _name = _str_DiagnosisAll, _formname = _str_DiagnosisAll, _type = "List<DiagnosisLookup>", _get_func = o => o.DiagnosisAll, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { } }, new field_info { _name = _str_strDiseaseNames, _formname = _str_strDiseaseNames, _type = "string", _get_func = o => o.strDiseaseNames, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.strDiseaseNames != c.strDiseaseNames || o.IsRIRPropChanged(_str_strDiseaseNames, c)) { m.Add(_str_strDiseaseNames, o.ObjectIdent + _str_strDiseaseNames, o.ObjectIdent2 + _str_strDiseaseNames, o.ObjectIdent3 + _str_strDiseaseNames, "string", o.strDiseaseNames == null ? "" : o.strDiseaseNames.ToString(), o.IsReadOnly(_str_strDiseaseNames), o.IsInvisible(_str_strDiseaseNames), o.IsRequired(_str_strDiseaseNames)); } } }, new field_info { _name = _str_IsClosed, _formname = _str_IsClosed, _type = "bool", _get_func = o => o.IsClosed, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.IsClosed != c.IsClosed || o.IsRIRPropChanged(_str_IsClosed, c)) { m.Add(_str_IsClosed, o.ObjectIdent + _str_IsClosed, o.ObjectIdent2 + _str_IsClosed, o.ObjectIdent3 + _str_IsClosed, "bool", o.IsClosed == null ? "" : o.IsClosed.ToString(), o.IsReadOnly(_str_IsClosed), o.IsInvisible(_str_IsClosed), o.IsRequired(_str_IsClosed)); } } }, new field_info { _name = _str_IsEnabledCaseProgressStatus, _formname = _str_IsEnabledCaseProgressStatus, _type = "bool", _get_func = o => o.IsEnabledCaseProgressStatus, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.IsEnabledCaseProgressStatus != c.IsEnabledCaseProgressStatus || o.IsRIRPropChanged(_str_IsEnabledCaseProgressStatus, c)) { m.Add(_str_IsEnabledCaseProgressStatus, o.ObjectIdent + _str_IsEnabledCaseProgressStatus, o.ObjectIdent2 + _str_IsEnabledCaseProgressStatus, o.ObjectIdent3 + _str_IsEnabledCaseProgressStatus, "bool", o.IsEnabledCaseProgressStatus == null ? "" : o.IsEnabledCaseProgressStatus.ToString(), o.IsReadOnly(_str_IsEnabledCaseProgressStatus), o.IsInvisible(_str_IsEnabledCaseProgressStatus), o.IsRequired(_str_IsEnabledCaseProgressStatus)); } } }, new field_info { _name = _str_idfsDiagnosis, _formname = _str_idfsDiagnosis, _type = "long?", _get_func = o => o.idfsDiagnosis, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.idfsDiagnosis != c.idfsDiagnosis || o.IsRIRPropChanged(_str_idfsDiagnosis, c)) { m.Add(_str_idfsDiagnosis, o.ObjectIdent + _str_idfsDiagnosis, o.ObjectIdent2 + _str_idfsDiagnosis, o.ObjectIdent3 + _str_idfsDiagnosis, "long?", o.idfsDiagnosis == null ? "" : o.idfsDiagnosis.ToString(), o.IsReadOnly(_str_idfsDiagnosis), o.IsInvisible(_str_idfsDiagnosis), o.IsRequired(_str_idfsDiagnosis)); } } }, new field_info { _name = _str_strSiteCode, _formname = _str_strSiteCode, _type = "string", _get_func = o => o.strSiteCode, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.strSiteCode != c.strSiteCode || o.IsRIRPropChanged(_str_strSiteCode, c)) { m.Add(_str_strSiteCode, o.ObjectIdent + _str_strSiteCode, o.ObjectIdent2 + _str_strSiteCode, o.ObjectIdent3 + _str_strSiteCode, "string", o.strSiteCode == null ? "" : o.strSiteCode.ToString(), o.IsReadOnly(_str_strSiteCode), o.IsInvisible(_str_strSiteCode), o.IsRequired(_str_strSiteCode)); } } }, new field_info { _name = _str_strIdfsDiagnosis, _formname = _str_strIdfsDiagnosis, _type = "string", _get_func = o => o.strIdfsDiagnosis, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.strIdfsDiagnosis != c.strIdfsDiagnosis || o.IsRIRPropChanged(_str_strIdfsDiagnosis, c)) { m.Add(_str_strIdfsDiagnosis, o.ObjectIdent + _str_strIdfsDiagnosis, o.ObjectIdent2 + _str_strIdfsDiagnosis, o.ObjectIdent3 + _str_strIdfsDiagnosis, "string", o.strIdfsDiagnosis == null ? "" : o.strIdfsDiagnosis.ToString(), o.IsReadOnly(_str_strIdfsDiagnosis), o.IsInvisible(_str_strIdfsDiagnosis), o.IsRequired(_str_strIdfsDiagnosis)); } } }, new field_info { _name = _str_strReadOnlyEnteredDate, _formname = _str_strReadOnlyEnteredDate, _type = "string", _get_func = o => o.strReadOnlyEnteredDate, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.strReadOnlyEnteredDate != c.strReadOnlyEnteredDate || o.IsRIRPropChanged(_str_strReadOnlyEnteredDate, c)) { m.Add(_str_strReadOnlyEnteredDate, o.ObjectIdent + _str_strReadOnlyEnteredDate, o.ObjectIdent2 + _str_strReadOnlyEnteredDate, o.ObjectIdent3 + _str_strReadOnlyEnteredDate, "string", o.strReadOnlyEnteredDate == null ? "" : o.strReadOnlyEnteredDate.ToString(), o.IsReadOnly(_str_strReadOnlyEnteredDate), o.IsInvisible(_str_strReadOnlyEnteredDate), o.IsRequired(_str_strReadOnlyEnteredDate)); } } }, new field_info { _name = _str_buttonSelectFarm, _formname = _str_buttonSelectFarm, _type = "string", _get_func = o => o.buttonSelectFarm, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.buttonSelectFarm != c.buttonSelectFarm || o.IsRIRPropChanged(_str_buttonSelectFarm, c)) { m.Add(_str_buttonSelectFarm, o.ObjectIdent + _str_buttonSelectFarm, o.ObjectIdent2 + _str_buttonSelectFarm, o.ObjectIdent3 + _str_buttonSelectFarm, "string", o.buttonSelectFarm == null ? "" : o.buttonSelectFarm.ToString(), o.IsReadOnly(_str_buttonSelectFarm), o.IsInvisible(_str_buttonSelectFarm), o.IsRequired(_str_buttonSelectFarm)); } } }, new field_info { _name = _str_buttonCoordinatesPicker, _formname = _str_buttonCoordinatesPicker, _type = "string", _get_func = o => o.buttonCoordinatesPicker, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.buttonCoordinatesPicker != c.buttonCoordinatesPicker || o.IsRIRPropChanged(_str_buttonCoordinatesPicker, c)) { m.Add(_str_buttonCoordinatesPicker, o.ObjectIdent + _str_buttonCoordinatesPicker, o.ObjectIdent2 + _str_buttonCoordinatesPicker, o.ObjectIdent3 + _str_buttonCoordinatesPicker, "string", o.buttonCoordinatesPicker == null ? "" : o.buttonCoordinatesPicker.ToString(), o.IsReadOnly(_str_buttonCoordinatesPicker), o.IsInvisible(_str_buttonCoordinatesPicker), o.IsRequired(_str_buttonCoordinatesPicker)); } } }, new field_info { _name = _str_blnEnableTestsConductedCalc, _formname = _str_blnEnableTestsConductedCalc, _type = "bool", _get_func = o => o.blnEnableTestsConductedCalc, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.blnEnableTestsConductedCalc != c.blnEnableTestsConductedCalc || o.IsRIRPropChanged(_str_blnEnableTestsConductedCalc, c)) { m.Add(_str_blnEnableTestsConductedCalc, o.ObjectIdent + _str_blnEnableTestsConductedCalc, o.ObjectIdent2 + _str_blnEnableTestsConductedCalc, o.ObjectIdent3 + _str_blnEnableTestsConductedCalc, "bool", o.blnEnableTestsConductedCalc == null ? "" : o.blnEnableTestsConductedCalc.ToString(), o.IsReadOnly(_str_blnEnableTestsConductedCalc), o.IsInvisible(_str_blnEnableTestsConductedCalc), o.IsRequired(_str_blnEnableTestsConductedCalc)); } } }, new field_info { _name = _str_Site, _formname = _str_Site, _type = "Lookup", _get_func = o => { if (o.Site == null) return null; return o.Site.idfsSite; }, _set_func = (o, val) => { o.Site = o.SiteLookup.Where(c => c.idfsSite.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsSite != c.idfsSite || o.IsRIRPropChanged(_str_Site, c)) { m.Add(_str_Site, o.ObjectIdent + _str_Site, o.ObjectIdent2 + _str_Site, o.ObjectIdent3 + _str_Site, "Lookup", o.idfsSite == null ? "" : o.idfsSite.ToString(), o.IsReadOnly(_str_Site), o.IsInvisible(_str_Site), o.IsRequired(_str_Site)); } } }, new field_info { _name = _str_Site + "Lookup", _formname = _str_Site + "Lookup", _type = "LookupContent", _get_func = o => o.SiteLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_CaseReportType, _formname = _str_CaseReportType, _type = "Lookup", _get_func = o => { if (o.CaseReportType == null) return null; return o.CaseReportType.idfsBaseReference; }, _set_func = (o, val) => { o.CaseReportType = o.CaseReportTypeLookup.Where(c => c.idfsBaseReference.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsCaseReportType != c.idfsCaseReportType || o.IsRIRPropChanged(_str_CaseReportType, c)) { m.Add(_str_CaseReportType, o.ObjectIdent + _str_CaseReportType, o.ObjectIdent2 + _str_CaseReportType, o.ObjectIdent3 + _str_CaseReportType, "Lookup", o.idfsCaseReportType == null ? "" : o.idfsCaseReportType.ToString(), o.IsReadOnly(_str_CaseReportType), o.IsInvisible(_str_CaseReportType), o.IsRequired(_str_CaseReportType)); } } }, new field_info { _name = _str_CaseReportType + "Lookup", _formname = _str_CaseReportType + "Lookup", _type = "LookupContent", _get_func = o => o.CaseReportTypeLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_CaseType, _formname = _str_CaseType, _type = "Lookup", _get_func = o => { if (o.CaseType == null) return null; return o.CaseType.idfsBaseReference; }, _set_func = (o, val) => { o.CaseType = o.CaseTypeLookup.Where(c => c.idfsBaseReference.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsCaseType != c.idfsCaseType || o.IsRIRPropChanged(_str_CaseType, c)) { m.Add(_str_CaseType, o.ObjectIdent + _str_CaseType, o.ObjectIdent2 + _str_CaseType, o.ObjectIdent3 + _str_CaseType, "Lookup", o.idfsCaseType == null ? "" : o.idfsCaseType.ToString(), o.IsReadOnly(_str_CaseType), o.IsInvisible(_str_CaseType), o.IsRequired(_str_CaseType)); } } }, new field_info { _name = _str_CaseType + "Lookup", _formname = _str_CaseType + "Lookup", _type = "LookupContent", _get_func = o => o.CaseTypeLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_CaseClassification, _formname = _str_CaseClassification, _type = "Lookup", _get_func = o => { if (o.CaseClassification == null) return null; return o.CaseClassification.idfsBaseReference; }, _set_func = (o, val) => { o.CaseClassification = o.CaseClassificationLookup.Where(c => c.idfsBaseReference.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsCaseClassification != c.idfsCaseClassification || o.IsRIRPropChanged(_str_CaseClassification, c)) { m.Add(_str_CaseClassification, o.ObjectIdent + _str_CaseClassification, o.ObjectIdent2 + _str_CaseClassification, o.ObjectIdent3 + _str_CaseClassification, "Lookup", o.idfsCaseClassification == null ? "" : o.idfsCaseClassification.ToString(), o.IsReadOnly(_str_CaseClassification), o.IsInvisible(_str_CaseClassification), o.IsRequired(_str_CaseClassification)); } } }, new field_info { _name = _str_CaseClassification + "Lookup", _formname = _str_CaseClassification + "Lookup", _type = "LookupContent", _get_func = o => o.CaseClassificationLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_CaseProgressStatus, _formname = _str_CaseProgressStatus, _type = "Lookup", _get_func = o => { if (o.CaseProgressStatus == null) return null; return o.CaseProgressStatus.idfsBaseReference; }, _set_func = (o, val) => { o.CaseProgressStatus = o.CaseProgressStatusLookup.Where(c => c.idfsBaseReference.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsCaseProgressStatus != c.idfsCaseProgressStatus || o.IsRIRPropChanged(_str_CaseProgressStatus, c)) { m.Add(_str_CaseProgressStatus, o.ObjectIdent + _str_CaseProgressStatus, o.ObjectIdent2 + _str_CaseProgressStatus, o.ObjectIdent3 + _str_CaseProgressStatus, "Lookup", o.idfsCaseProgressStatus == null ? "" : o.idfsCaseProgressStatus.ToString(), o.IsReadOnly(_str_CaseProgressStatus), o.IsInvisible(_str_CaseProgressStatus), o.IsRequired(_str_CaseProgressStatus)); } } }, new field_info { _name = _str_CaseProgressStatus + "Lookup", _formname = _str_CaseProgressStatus + "Lookup", _type = "LookupContent", _get_func = o => o.CaseProgressStatusLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_TestsConducted, _formname = _str_TestsConducted, _type = "Lookup", _get_func = o => { if (o.TestsConducted == null) return null; return o.TestsConducted.idfsBaseReference; }, _set_func = (o, val) => { o.TestsConducted = o.TestsConductedLookup.Where(c => c.idfsBaseReference.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsYNTestsConducted != c.idfsYNTestsConducted || o.IsRIRPropChanged(_str_TestsConducted, c)) { m.Add(_str_TestsConducted, o.ObjectIdent + _str_TestsConducted, o.ObjectIdent2 + _str_TestsConducted, o.ObjectIdent3 + _str_TestsConducted, "Lookup", o.idfsYNTestsConducted == null ? "" : o.idfsYNTestsConducted.ToString(), o.IsReadOnly(_str_TestsConducted), o.IsInvisible(_str_TestsConducted), o.IsRequired(_str_TestsConducted)); } } }, new field_info { _name = _str_TestsConducted + "Lookup", _formname = _str_TestsConducted + "Lookup", _type = "LookupContent", _get_func = o => o.TestsConductedLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_TentativeDiagnosis, _formname = _str_TentativeDiagnosis, _type = "Lookup", _get_func = o => { if (o.TentativeDiagnosis == null) return null; return o.TentativeDiagnosis.idfsDiagnosis; }, _set_func = (o, val) => { o.TentativeDiagnosis = o.TentativeDiagnosisLookup.Where(c => c.idfsDiagnosis.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsTentativeDiagnosis != c.idfsTentativeDiagnosis || o.IsRIRPropChanged(_str_TentativeDiagnosis, c)) { m.Add(_str_TentativeDiagnosis, o.ObjectIdent + _str_TentativeDiagnosis, o.ObjectIdent2 + _str_TentativeDiagnosis, o.ObjectIdent3 + _str_TentativeDiagnosis, "Lookup", o.idfsTentativeDiagnosis == null ? "" : o.idfsTentativeDiagnosis.ToString(), o.IsReadOnly(_str_TentativeDiagnosis), o.IsInvisible(_str_TentativeDiagnosis), o.IsRequired(_str_TentativeDiagnosis)); } } }, new field_info { _name = _str_TentativeDiagnosis + "Lookup", _formname = _str_TentativeDiagnosis + "Lookup", _type = "LookupContent", _get_func = o => o.TentativeDiagnosisLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_TentativeDiagnosis1, _formname = _str_TentativeDiagnosis1, _type = "Lookup", _get_func = o => { if (o.TentativeDiagnosis1 == null) return null; return o.TentativeDiagnosis1.idfsDiagnosis; }, _set_func = (o, val) => { o.TentativeDiagnosis1 = o.TentativeDiagnosis1Lookup.Where(c => c.idfsDiagnosis.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsTentativeDiagnosis1 != c.idfsTentativeDiagnosis1 || o.IsRIRPropChanged(_str_TentativeDiagnosis1, c)) { m.Add(_str_TentativeDiagnosis1, o.ObjectIdent + _str_TentativeDiagnosis1, o.ObjectIdent2 + _str_TentativeDiagnosis1, o.ObjectIdent3 + _str_TentativeDiagnosis1, "Lookup", o.idfsTentativeDiagnosis1 == null ? "" : o.idfsTentativeDiagnosis1.ToString(), o.IsReadOnly(_str_TentativeDiagnosis1), o.IsInvisible(_str_TentativeDiagnosis1), o.IsRequired(_str_TentativeDiagnosis1)); } } }, new field_info { _name = _str_TentativeDiagnosis1 + "Lookup", _formname = _str_TentativeDiagnosis1 + "Lookup", _type = "LookupContent", _get_func = o => o.TentativeDiagnosis1Lookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_TentativeDiagnosis2, _formname = _str_TentativeDiagnosis2, _type = "Lookup", _get_func = o => { if (o.TentativeDiagnosis2 == null) return null; return o.TentativeDiagnosis2.idfsDiagnosis; }, _set_func = (o, val) => { o.TentativeDiagnosis2 = o.TentativeDiagnosis2Lookup.Where(c => c.idfsDiagnosis.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsTentativeDiagnosis2 != c.idfsTentativeDiagnosis2 || o.IsRIRPropChanged(_str_TentativeDiagnosis2, c)) { m.Add(_str_TentativeDiagnosis2, o.ObjectIdent + _str_TentativeDiagnosis2, o.ObjectIdent2 + _str_TentativeDiagnosis2, o.ObjectIdent3 + _str_TentativeDiagnosis2, "Lookup", o.idfsTentativeDiagnosis2 == null ? "" : o.idfsTentativeDiagnosis2.ToString(), o.IsReadOnly(_str_TentativeDiagnosis2), o.IsInvisible(_str_TentativeDiagnosis2), o.IsRequired(_str_TentativeDiagnosis2)); } } }, new field_info { _name = _str_TentativeDiagnosis2 + "Lookup", _formname = _str_TentativeDiagnosis2 + "Lookup", _type = "LookupContent", _get_func = o => o.TentativeDiagnosis2Lookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_FinalDiagnosis, _formname = _str_FinalDiagnosis, _type = "Lookup", _get_func = o => { if (o.FinalDiagnosis == null) return null; return o.FinalDiagnosis.idfsDiagnosis; }, _set_func = (o, val) => { o.FinalDiagnosis = o.FinalDiagnosisLookup.Where(c => c.idfsDiagnosis.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsFinalDiagnosis != c.idfsFinalDiagnosis || o.IsRIRPropChanged(_str_FinalDiagnosis, c)) { m.Add(_str_FinalDiagnosis, o.ObjectIdent + _str_FinalDiagnosis, o.ObjectIdent2 + _str_FinalDiagnosis, o.ObjectIdent3 + _str_FinalDiagnosis, "Lookup", o.idfsFinalDiagnosis == null ? "" : o.idfsFinalDiagnosis.ToString(), o.IsReadOnly(_str_FinalDiagnosis), o.IsInvisible(_str_FinalDiagnosis), o.IsRequired(_str_FinalDiagnosis)); } } }, new field_info { _name = _str_FinalDiagnosis + "Lookup", _formname = _str_FinalDiagnosis + "Lookup", _type = "LookupContent", _get_func = o => o.FinalDiagnosisLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_ShowDiagnosis, _formname = _str_ShowDiagnosis, _type = "Lookup", _get_func = o => { if (o.ShowDiagnosis == null) return null; return o.ShowDiagnosis.idfsDiagnosis; }, _set_func = (o, val) => { o.ShowDiagnosis = o.ShowDiagnosisLookup.Where(c => c.idfsDiagnosis.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsShowDiagnosis != c.idfsShowDiagnosis || o.IsRIRPropChanged(_str_ShowDiagnosis, c)) { m.Add(_str_ShowDiagnosis, o.ObjectIdent + _str_ShowDiagnosis, o.ObjectIdent2 + _str_ShowDiagnosis, o.ObjectIdent3 + _str_ShowDiagnosis, "Lookup", o.idfsShowDiagnosis == null ? "" : o.idfsShowDiagnosis.ToString(), o.IsReadOnly(_str_ShowDiagnosis), o.IsInvisible(_str_ShowDiagnosis), o.IsRequired(_str_ShowDiagnosis)); } } }, new field_info { _name = _str_ShowDiagnosis + "Lookup", _formname = _str_ShowDiagnosis + "Lookup", _type = "LookupContent", _get_func = o => o.ShowDiagnosisLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_PersonInvestigatedBy, _formname = _str_PersonInvestigatedBy, _type = "Lookup", _get_func = o => { if (o.PersonInvestigatedBy == null) return null; return o.PersonInvestigatedBy.idfPerson; }, _set_func = (o, val) => { o.PersonInvestigatedBy = o.PersonInvestigatedByLookup.Where(c => c.idfPerson.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfPersonInvestigatedBy != c.idfPersonInvestigatedBy || o.IsRIRPropChanged(_str_PersonInvestigatedBy, c)) { m.Add(_str_PersonInvestigatedBy, o.ObjectIdent + _str_PersonInvestigatedBy, o.ObjectIdent2 + _str_PersonInvestigatedBy, o.ObjectIdent3 + _str_PersonInvestigatedBy, "Lookup", o.idfPersonInvestigatedBy == null ? "" : o.idfPersonInvestigatedBy.ToString(), o.IsReadOnly(_str_PersonInvestigatedBy), o.IsInvisible(_str_PersonInvestigatedBy), o.IsRequired(_str_PersonInvestigatedBy)); } } }, new field_info { _name = _str_PersonInvestigatedBy + "Lookup", _formname = _str_PersonInvestigatedBy + "Lookup", _type = "LookupContent", _get_func = o => o.PersonInvestigatedByLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info { _name = _str_Vaccination, _formname = _str_Vaccination, _type = "Child", _get_func = o => null, _set_func = (o, val) => { o.Vaccination.ForEach(c => c.SetValue("blnChecked", "false")); if (!string.IsNullOrEmpty(val)) val.Split(',').ToList().ForEach(i => o.Vaccination.First(c => (long)c.Key == Int64.Parse(i)).SetValue("blnChecked", "true")); }, _compare_func = (o, c, m) => { if (o.Vaccination.Count != c.Vaccination.Count || o.IsReadOnly(_str_Vaccination) != c.IsReadOnly(_str_Vaccination) || o.IsInvisible(_str_Vaccination) != c.IsInvisible(_str_Vaccination) || o.IsRequired(_str_Vaccination) != c._isRequired(o.m_isRequired, _str_Vaccination)) { m.Add(_str_Vaccination, o.ObjectIdent + _str_Vaccination, o.ObjectIdent2 + _str_Vaccination, o.ObjectIdent3 + _str_Vaccination, "Child", o.idfCase == null ? "" : o.idfCase.ToString(), o.IsReadOnly(_str_Vaccination), o.IsInvisible(_str_Vaccination), o.IsRequired(_str_Vaccination)); } } }, new field_info { _name = _str_CaseTests, _formname = _str_CaseTests, _type = "Child", _get_func = o => null, _set_func = (o, val) => { o.CaseTests.ForEach(c => c.SetValue("blnChecked", "false")); if (!string.IsNullOrEmpty(val)) val.Split(',').ToList().ForEach(i => o.CaseTests.First(c => (long)c.Key == Int64.Parse(i)).SetValue("blnChecked", "true")); }, _compare_func = (o, c, m) => { if (o.CaseTests.Count != c.CaseTests.Count || o.IsReadOnly(_str_CaseTests) != c.IsReadOnly(_str_CaseTests) || o.IsInvisible(_str_CaseTests) != c.IsInvisible(_str_CaseTests) || o.IsRequired(_str_CaseTests) != c._isRequired(o.m_isRequired, _str_CaseTests)) { m.Add(_str_CaseTests, o.ObjectIdent + _str_CaseTests, o.ObjectIdent2 + _str_CaseTests, o.ObjectIdent3 + _str_CaseTests, "Child", o.idfCase == null ? "" : o.idfCase.ToString(), o.IsReadOnly(_str_CaseTests), o.IsInvisible(_str_CaseTests), o.IsRequired(_str_CaseTests)); } } }, new field_info { _name = _str_CaseTestValidations, _formname = _str_CaseTestValidations, _type = "Child", _get_func = o => null, _set_func = (o, val) => { o.CaseTestValidations.ForEach(c => c.SetValue("blnChecked", "false")); if (!string.IsNullOrEmpty(val)) val.Split(',').ToList().ForEach(i => o.CaseTestValidations.First(c => (long)c.Key == Int64.Parse(i)).SetValue("blnChecked", "true")); }, _compare_func = (o, c, m) => { if (o.CaseTestValidations.Count != c.CaseTestValidations.Count || o.IsReadOnly(_str_CaseTestValidations) != c.IsReadOnly(_str_CaseTestValidations) || o.IsInvisible(_str_CaseTestValidations) != c.IsInvisible(_str_CaseTestValidations) || o.IsRequired(_str_CaseTestValidations) != c._isRequired(o.m_isRequired, _str_CaseTestValidations)) { m.Add(_str_CaseTestValidations, o.ObjectIdent + _str_CaseTestValidations, o.ObjectIdent2 + _str_CaseTestValidations, o.ObjectIdent3 + _str_CaseTestValidations, "Child", o.idfCase == null ? "" : o.idfCase.ToString(), o.IsReadOnly(_str_CaseTestValidations), o.IsInvisible(_str_CaseTestValidations), o.IsRequired(_str_CaseTestValidations)); } } }, new field_info { _name = _str_PensideTests, _formname = _str_PensideTests, _type = "Child", _get_func = o => null, _set_func = (o, val) => { o.PensideTests.ForEach(c => c.SetValue("blnChecked", "false")); if (!string.IsNullOrEmpty(val)) val.Split(',').ToList().ForEach(i => o.PensideTests.First(c => (long)c.Key == Int64.Parse(i)).SetValue("blnChecked", "true")); }, _compare_func = (o, c, m) => { if (o.PensideTests.Count != c.PensideTests.Count || o.IsReadOnly(_str_PensideTests) != c.IsReadOnly(_str_PensideTests) || o.IsInvisible(_str_PensideTests) != c.IsInvisible(_str_PensideTests) || o.IsRequired(_str_PensideTests) != c._isRequired(o.m_isRequired, _str_PensideTests)) { m.Add(_str_PensideTests, o.ObjectIdent + _str_PensideTests, o.ObjectIdent2 + _str_PensideTests, o.ObjectIdent3 + _str_PensideTests, "Child", o.idfCase == null ? "" : o.idfCase.ToString(), o.IsReadOnly(_str_PensideTests), o.IsInvisible(_str_PensideTests), o.IsRequired(_str_PensideTests)); } } }, new field_info { _name = _str_AnimalList, _formname = _str_AnimalList, _type = "Child", _get_func = o => null, _set_func = (o, val) => { o.AnimalList.ForEach(c => c.SetValue("blnChecked", "false")); if (!string.IsNullOrEmpty(val)) val.Split(',').ToList().ForEach(i => o.AnimalList.First(c => (long)c.Key == Int64.Parse(i)).SetValue("blnChecked", "true")); }, _compare_func = (o, c, m) => { if (o.AnimalList.Count != c.AnimalList.Count || o.IsReadOnly(_str_AnimalList) != c.IsReadOnly(_str_AnimalList) || o.IsInvisible(_str_AnimalList) != c.IsInvisible(_str_AnimalList) || o.IsRequired(_str_AnimalList) != c._isRequired(o.m_isRequired, _str_AnimalList)) { m.Add(_str_AnimalList, o.ObjectIdent + _str_AnimalList, o.ObjectIdent2 + _str_AnimalList, o.ObjectIdent3 + _str_AnimalList, "Child", o.idfCase == null ? "" : o.idfCase.ToString(), o.IsReadOnly(_str_AnimalList), o.IsInvisible(_str_AnimalList), o.IsRequired(_str_AnimalList)); } } }, new field_info { _name = _str_Samples, _formname = _str_Samples, _type = "Child", _get_func = o => null, _set_func = (o, val) => { o.Samples.ForEach(c => c.SetValue("blnChecked", "false")); if (!string.IsNullOrEmpty(val)) val.Split(',').ToList().ForEach(i => o.Samples.First(c => (long)c.Key == Int64.Parse(i)).SetValue("blnChecked", "true")); }, _compare_func = (o, c, m) => { if (o.Samples.Count != c.Samples.Count || o.IsReadOnly(_str_Samples) != c.IsReadOnly(_str_Samples) || o.IsInvisible(_str_Samples) != c.IsInvisible(_str_Samples) || o.IsRequired(_str_Samples) != c._isRequired(o.m_isRequired, _str_Samples)) { m.Add(_str_Samples, o.ObjectIdent + _str_Samples, o.ObjectIdent2 + _str_Samples, o.ObjectIdent3 + _str_Samples, "Child", o.idfCase == null ? "" : o.idfCase.ToString(), o.IsReadOnly(_str_Samples), o.IsInvisible(_str_Samples), o.IsRequired(_str_Samples)); } } }, new field_info { _name = _str_Logs, _formname = _str_Logs, _type = "Child", _get_func = o => null, _set_func = (o, val) => { o.Logs.ForEach(c => c.SetValue("blnChecked", "false")); if (!string.IsNullOrEmpty(val)) val.Split(',').ToList().ForEach(i => o.Logs.First(c => (long)c.Key == Int64.Parse(i)).SetValue("blnChecked", "true")); }, _compare_func = (o, c, m) => { if (o.Logs.Count != c.Logs.Count || o.IsReadOnly(_str_Logs) != c.IsReadOnly(_str_Logs) || o.IsInvisible(_str_Logs) != c.IsInvisible(_str_Logs) || o.IsRequired(_str_Logs) != c._isRequired(o.m_isRequired, _str_Logs)) { m.Add(_str_Logs, o.ObjectIdent + _str_Logs, o.ObjectIdent2 + _str_Logs, o.ObjectIdent3 + _str_Logs, "Child", o.idfCase == null ? "" : o.idfCase.ToString(), o.IsReadOnly(_str_Logs), o.IsInvisible(_str_Logs), o.IsRequired(_str_Logs)); } } }, new field_info { _name = _str_FFPresenterControlMeasures, _formname = _str_FFPresenterControlMeasures, _type = "Relation", _get_func = o => null, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.FFPresenterControlMeasures != null) o.FFPresenterControlMeasures._compare(c.FFPresenterControlMeasures, m); } }, new field_info { _name = _str_Farm, _formname = _str_Farm, _type = "Relation", _get_func = o => null, _set_func = (o, val) => {}, _compare_func = (o, c, m) => { if (o.Farm != null) o.Farm._compare(c.Farm, m); } }, new field_info() }; #endregion private string _getType(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? "" : i._type; } private object _getValue(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? null : i._get_func(this); } private void _setValue(string name, string val) { var i = _field_infos.FirstOrDefault(n => n._name == name); if (i != null) i._set_func(this, val); } internal CompareModel _compare(IObject o, CompareModel ret) { if (ret == null) ret = new CompareModel(); if (o == null) return ret; VetCase obj = (VetCase)o; foreach (var i in _field_infos) if (i != null && i._compare_func != null) i._compare_func(this, obj, ret); return ret; } #endregion [LocalizedDisplayName(_str_FFPresenterControlMeasures)] [Relation(typeof(FFPresenterModel), eidss.model.Schema.FFPresenterModel._str_CurrentObservation, _str_idfObservation)] public FFPresenterModel FFPresenterControlMeasures { get { return _FFPresenterControlMeasures; } set { _FFPresenterControlMeasures = value; if (_FFPresenterControlMeasures != null) { _FFPresenterControlMeasures.m_ObjectName = _str_FFPresenterControlMeasures; _FFPresenterControlMeasures.Parent = this; } idfObservation = _FFPresenterControlMeasures == null ? new Int64?() : _FFPresenterControlMeasures.CurrentObservation; } } protected FFPresenterModel _FFPresenterControlMeasures; [LocalizedDisplayName(_str_Farm)] [Relation(typeof(FarmPanel), eidss.model.Schema.FarmPanel._str_idfFarm, _str_idfFarm)] public FarmPanel Farm { get { if (!_FarmLoaded) { _FarmLoaded = true; _getAccessor()._LoadFarm(this); if (_Farm != null) _Farm.Parent = this; } return _Farm; } set { if (!_FarmLoaded) { _FarmLoaded = true; } _Farm = value; if (_Farm != null) { _Farm.m_ObjectName = _str_Farm; _Farm.Parent = this; } idfFarm = _Farm == null ? new Int64() : _Farm.idfFarm; } } protected FarmPanel _Farm; private bool _FarmLoaded = false; [LocalizedDisplayName(_str_Vaccination)] [Relation(typeof(VaccinationListItem), "", _str_idfCase)] public EditableList<VaccinationListItem> Vaccination { get { return _Vaccination; } set { _Vaccination = value; } } protected EditableList<VaccinationListItem> _Vaccination = new EditableList<VaccinationListItem>(); [LocalizedDisplayName(_str_CaseTests)] [Relation(typeof(CaseTest), "", _str_idfCase)] public EditableList<CaseTest> CaseTests { get { return _CaseTests; } set { _CaseTests = value; } } protected EditableList<CaseTest> _CaseTests = new EditableList<CaseTest>(); [LocalizedDisplayName(_str_CaseTestValidations)] [Relation(typeof(CaseTestValidation), "", _str_idfCase)] public EditableList<CaseTestValidation> CaseTestValidations { get { return _CaseTestValidations; } set { _CaseTestValidations = value; } } protected EditableList<CaseTestValidation> _CaseTestValidations = new EditableList<CaseTestValidation>(); [LocalizedDisplayName(_str_PensideTests)] [Relation(typeof(PensideTest), "", _str_idfCase)] public EditableList<PensideTest> PensideTests { get { return _PensideTests; } set { _PensideTests = value; } } protected EditableList<PensideTest> _PensideTests = new EditableList<PensideTest>(); [LocalizedDisplayName(_str_AnimalList)] [Relation(typeof(AnimalListItem), eidss.model.Schema.AnimalListItem._str_idfCase, _str_idfCase)] public EditableList<AnimalListItem> AnimalList { get { return _AnimalList; } set { _AnimalList = value; } } protected EditableList<AnimalListItem> _AnimalList = new EditableList<AnimalListItem>(); [LocalizedDisplayName(_str_Samples)] [Relation(typeof(VetCaseSample), eidss.model.Schema.VetCaseSample._str_idfCase, _str_idfCase)] public EditableList<VetCaseSample> Samples { get { return _Samples; } set { _Samples = value; } } protected EditableList<VetCaseSample> _Samples = new EditableList<VetCaseSample>(); [LocalizedDisplayName(_str_Logs)] [Relation(typeof(VetCaseLog), eidss.model.Schema.VetCaseLog._str_idfVetCase, _str_idfCase)] public EditableList<VetCaseLog> Logs { get { return _Logs; } set { _Logs = value; } } protected EditableList<VetCaseLog> _Logs = new EditableList<VetCaseLog>(); [LocalizedDisplayName(_str_Site)] [Relation(typeof(SiteLookup), eidss.model.Schema.SiteLookup._str_idfsSite, _str_idfsSite)] public SiteLookup Site { get { return _Site == null ? null : ((long)_Site.Key == 0 ? null : _Site); } set { var oldVal = _Site; _Site = value == null ? null : ((long) value.Key == 0 ? null : value); if (_Site != oldVal) { if (idfsSite != (_Site == null ? new Int64() : (Int64)_Site.idfsSite)) idfsSite = _Site == null ? new Int64() : (Int64)_Site.idfsSite; OnPropertyChanged(_str_Site); } } } private SiteLookup _Site; public List<SiteLookup> SiteLookup { get { return _SiteLookup; } } private List<SiteLookup> _SiteLookup = new List<SiteLookup>(); [LocalizedDisplayName(_str_CaseReportType)] [Relation(typeof(BaseReference), eidss.model.Schema.BaseReference._str_idfsBaseReference, _str_idfsCaseReportType)] public BaseReference CaseReportType { get { return _CaseReportType == null ? null : ((long)_CaseReportType.Key == 0 ? null : _CaseReportType); } set { var oldVal = _CaseReportType; _CaseReportType = value == null ? null : ((long) value.Key == 0 ? null : value); if (_CaseReportType != oldVal) { if (idfsCaseReportType != (_CaseReportType == null ? new Int64?() : (Int64?)_CaseReportType.idfsBaseReference)) idfsCaseReportType = _CaseReportType == null ? new Int64?() : (Int64?)_CaseReportType.idfsBaseReference; OnPropertyChanged(_str_CaseReportType); } } } private BaseReference _CaseReportType; public BaseReferenceList CaseReportTypeLookup { get { return _CaseReportTypeLookup; } } private BaseReferenceList _CaseReportTypeLookup = new BaseReferenceList("rftCaseReportType"); [LocalizedDisplayName(_str_CaseType)] [Relation(typeof(BaseReference), eidss.model.Schema.BaseReference._str_idfsBaseReference, _str_idfsCaseType)] public BaseReference CaseType { get { return _CaseType == null ? null : ((long)_CaseType.Key == 0 ? null : _CaseType); } set { var oldVal = _CaseType; _CaseType = value == null ? null : ((long) value.Key == 0 ? null : value); if (_CaseType != oldVal) { if (idfsCaseType != (_CaseType == null ? new Int64() : (Int64)_CaseType.idfsBaseReference)) idfsCaseType = _CaseType == null ? new Int64() : (Int64)_CaseType.idfsBaseReference; OnPropertyChanged(_str_CaseType); } } } private BaseReference _CaseType; public BaseReferenceList CaseTypeLookup { get { return _CaseTypeLookup; } } private BaseReferenceList _CaseTypeLookup = new BaseReferenceList("rftCaseType"); [LocalizedDisplayName(_str_CaseClassification)] [Relation(typeof(BaseReference), eidss.model.Schema.BaseReference._str_idfsBaseReference, _str_idfsCaseClassification)] public BaseReference CaseClassification { get { return _CaseClassification == null ? null : ((long)_CaseClassification.Key == 0 ? null : _CaseClassification); } set { var oldVal = _CaseClassification; _CaseClassification = value == null ? null : ((long) value.Key == 0 ? null : value); if (_CaseClassification != oldVal) { if (idfsCaseClassification != (_CaseClassification == null ? new Int64?() : (Int64?)_CaseClassification.idfsBaseReference)) idfsCaseClassification = _CaseClassification == null ? new Int64?() : (Int64?)_CaseClassification.idfsBaseReference; OnPropertyChanged(_str_CaseClassification); } } } private BaseReference _CaseClassification; public BaseReferenceList CaseClassificationLookup { get { return _CaseClassificationLookup; } } private BaseReferenceList _CaseClassificationLookup = new BaseReferenceList("rftCaseClassification"); [LocalizedDisplayName(_str_CaseProgressStatus)] [Relation(typeof(BaseReference), eidss.model.Schema.BaseReference._str_idfsBaseReference, _str_idfsCaseProgressStatus)] public BaseReference CaseProgressStatus { get { return _CaseProgressStatus; } set { var oldVal = _CaseProgressStatus; _CaseProgressStatus = value; if (_CaseProgressStatus != oldVal) { if (idfsCaseProgressStatus != (_CaseProgressStatus == null ? new Int64?() : (Int64?)_CaseProgressStatus.idfsBaseReference)) idfsCaseProgressStatus = _CaseProgressStatus == null ? new Int64?() : (Int64?)_CaseProgressStatus.idfsBaseReference; OnPropertyChanged(_str_CaseProgressStatus); } } } private BaseReference _CaseProgressStatus; public BaseReferenceList CaseProgressStatusLookup { get { return _CaseProgressStatusLookup; } } private BaseReferenceList _CaseProgressStatusLookup = new BaseReferenceList("rftCaseProgressStatus"); [LocalizedDisplayName(_str_TestsConducted)] [Relation(typeof(BaseReference), eidss.model.Schema.BaseReference._str_idfsBaseReference, _str_idfsYNTestsConducted)] public BaseReference TestsConducted { get { return _TestsConducted == null ? null : ((long)_TestsConducted.Key == 0 ? null : _TestsConducted); } set { var oldVal = _TestsConducted; _TestsConducted = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TestsConducted != oldVal) { if (idfsYNTestsConducted != (_TestsConducted == null ? new Int64?() : (Int64?)_TestsConducted.idfsBaseReference)) idfsYNTestsConducted = _TestsConducted == null ? new Int64?() : (Int64?)_TestsConducted.idfsBaseReference; OnPropertyChanged(_str_TestsConducted); } } } private BaseReference _TestsConducted; public BaseReferenceList TestsConductedLookup { get { return _TestsConductedLookup; } } private BaseReferenceList _TestsConductedLookup = new BaseReferenceList("rftYesNoValue"); [LocalizedDisplayName(_str_TentativeDiagnosis)] [Relation(typeof(DiagnosisLookup), eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, _str_idfsTentativeDiagnosis)] public DiagnosisLookup TentativeDiagnosis { get { return _TentativeDiagnosis == null ? null : ((long)_TentativeDiagnosis.Key == 0 ? null : _TentativeDiagnosis); } set { var oldVal = _TentativeDiagnosis; _TentativeDiagnosis = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TentativeDiagnosis != oldVal) { if (idfsTentativeDiagnosis != (_TentativeDiagnosis == null ? new Int64?() : (Int64?)_TentativeDiagnosis.idfsDiagnosis)) idfsTentativeDiagnosis = _TentativeDiagnosis == null ? new Int64?() : (Int64?)_TentativeDiagnosis.idfsDiagnosis; OnPropertyChanged(_str_TentativeDiagnosis); } } } private DiagnosisLookup _TentativeDiagnosis; public List<DiagnosisLookup> TentativeDiagnosisLookup { get { return _TentativeDiagnosisLookup; } } private List<DiagnosisLookup> _TentativeDiagnosisLookup = new List<DiagnosisLookup>(); [LocalizedDisplayName(_str_TentativeDiagnosis1)] [Relation(typeof(DiagnosisLookup), eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, _str_idfsTentativeDiagnosis1)] public DiagnosisLookup TentativeDiagnosis1 { get { return _TentativeDiagnosis1 == null ? null : ((long)_TentativeDiagnosis1.Key == 0 ? null : _TentativeDiagnosis1); } set { var oldVal = _TentativeDiagnosis1; _TentativeDiagnosis1 = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TentativeDiagnosis1 != oldVal) { if (idfsTentativeDiagnosis1 != (_TentativeDiagnosis1 == null ? new Int64?() : (Int64?)_TentativeDiagnosis1.idfsDiagnosis)) idfsTentativeDiagnosis1 = _TentativeDiagnosis1 == null ? new Int64?() : (Int64?)_TentativeDiagnosis1.idfsDiagnosis; OnPropertyChanged(_str_TentativeDiagnosis1); } } } private DiagnosisLookup _TentativeDiagnosis1; public List<DiagnosisLookup> TentativeDiagnosis1Lookup { get { return _TentativeDiagnosis1Lookup; } } private List<DiagnosisLookup> _TentativeDiagnosis1Lookup = new List<DiagnosisLookup>(); [LocalizedDisplayName(_str_TentativeDiagnosis2)] [Relation(typeof(DiagnosisLookup), eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, _str_idfsTentativeDiagnosis2)] public DiagnosisLookup TentativeDiagnosis2 { get { return _TentativeDiagnosis2 == null ? null : ((long)_TentativeDiagnosis2.Key == 0 ? null : _TentativeDiagnosis2); } set { var oldVal = _TentativeDiagnosis2; _TentativeDiagnosis2 = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TentativeDiagnosis2 != oldVal) { if (idfsTentativeDiagnosis2 != (_TentativeDiagnosis2 == null ? new Int64?() : (Int64?)_TentativeDiagnosis2.idfsDiagnosis)) idfsTentativeDiagnosis2 = _TentativeDiagnosis2 == null ? new Int64?() : (Int64?)_TentativeDiagnosis2.idfsDiagnosis; OnPropertyChanged(_str_TentativeDiagnosis2); } } } private DiagnosisLookup _TentativeDiagnosis2; public List<DiagnosisLookup> TentativeDiagnosis2Lookup { get { return _TentativeDiagnosis2Lookup; } } private List<DiagnosisLookup> _TentativeDiagnosis2Lookup = new List<DiagnosisLookup>(); [LocalizedDisplayName(_str_FinalDiagnosis)] [Relation(typeof(DiagnosisLookup), eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, _str_idfsFinalDiagnosis)] public DiagnosisLookup FinalDiagnosis { get { return _FinalDiagnosis == null ? null : ((long)_FinalDiagnosis.Key == 0 ? null : _FinalDiagnosis); } set { var oldVal = _FinalDiagnosis; _FinalDiagnosis = value == null ? null : ((long) value.Key == 0 ? null : value); if (_FinalDiagnosis != oldVal) { if (idfsFinalDiagnosis != (_FinalDiagnosis == null ? new Int64?() : (Int64?)_FinalDiagnosis.idfsDiagnosis)) idfsFinalDiagnosis = _FinalDiagnosis == null ? new Int64?() : (Int64?)_FinalDiagnosis.idfsDiagnosis; OnPropertyChanged(_str_FinalDiagnosis); } } } private DiagnosisLookup _FinalDiagnosis; public List<DiagnosisLookup> FinalDiagnosisLookup { get { return _FinalDiagnosisLookup; } } private List<DiagnosisLookup> _FinalDiagnosisLookup = new List<DiagnosisLookup>(); [LocalizedDisplayName(_str_ShowDiagnosis)] [Relation(typeof(DiagnosisLookup), eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, _str_idfsShowDiagnosis)] public DiagnosisLookup ShowDiagnosis { get { return _ShowDiagnosis == null ? null : ((long)_ShowDiagnosis.Key == 0 ? null : _ShowDiagnosis); } set { var oldVal = _ShowDiagnosis; _ShowDiagnosis = value == null ? null : ((long) value.Key == 0 ? null : value); if (_ShowDiagnosis != oldVal) { if (idfsShowDiagnosis != (_ShowDiagnosis == null ? new Int64?() : (Int64?)_ShowDiagnosis.idfsDiagnosis)) idfsShowDiagnosis = _ShowDiagnosis == null ? new Int64?() : (Int64?)_ShowDiagnosis.idfsDiagnosis; OnPropertyChanged(_str_ShowDiagnosis); } } } private DiagnosisLookup _ShowDiagnosis; public List<DiagnosisLookup> ShowDiagnosisLookup { get { return _ShowDiagnosisLookup; } } private List<DiagnosisLookup> _ShowDiagnosisLookup = new List<DiagnosisLookup>(); [LocalizedDisplayName(_str_PersonInvestigatedBy)] [Relation(typeof(WiderPersonLookup), eidss.model.Schema.WiderPersonLookup._str_idfPerson, _str_idfPersonInvestigatedBy)] public WiderPersonLookup PersonInvestigatedBy { get { return _PersonInvestigatedBy == null ? null : ((long)_PersonInvestigatedBy.Key == 0 ? null : _PersonInvestigatedBy); } set { var oldVal = _PersonInvestigatedBy; _PersonInvestigatedBy = value == null ? null : ((long) value.Key == 0 ? null : value); if (_PersonInvestigatedBy != oldVal) { if (idfPersonInvestigatedBy != (_PersonInvestigatedBy == null ? new Int64?() : (Int64?)_PersonInvestigatedBy.idfPerson)) idfPersonInvestigatedBy = _PersonInvestigatedBy == null ? new Int64?() : (Int64?)_PersonInvestigatedBy.idfPerson; OnPropertyChanged(_str_PersonInvestigatedBy); } } } private WiderPersonLookup _PersonInvestigatedBy; public List<WiderPersonLookup> PersonInvestigatedByLookup { get { return _PersonInvestigatedByLookup; } } private List<WiderPersonLookup> _PersonInvestigatedByLookup = new List<WiderPersonLookup>(); private BvSelectList _getList(string name) { switch(name) { case _str_Site: return new BvSelectList(SiteLookup, eidss.model.Schema.SiteLookup._str_idfsSite, null, Site, _str_idfsSite); case _str_CaseReportType: return new BvSelectList(CaseReportTypeLookup, eidss.model.Schema.BaseReference._str_idfsBaseReference, null, CaseReportType, _str_idfsCaseReportType); case _str_CaseType: return new BvSelectList(CaseTypeLookup, eidss.model.Schema.BaseReference._str_idfsBaseReference, null, CaseType, _str_idfsCaseType); case _str_CaseClassification: return new BvSelectList(CaseClassificationLookup, eidss.model.Schema.BaseReference._str_idfsBaseReference, null, CaseClassification, _str_idfsCaseClassification); case _str_CaseProgressStatus: return new BvSelectList(CaseProgressStatusLookup, eidss.model.Schema.BaseReference._str_idfsBaseReference, null, CaseProgressStatus, _str_idfsCaseProgressStatus); case _str_TestsConducted: return new BvSelectList(TestsConductedLookup, eidss.model.Schema.BaseReference._str_idfsBaseReference, null, TestsConducted, _str_idfsYNTestsConducted); case _str_TentativeDiagnosis: return new BvSelectList(TentativeDiagnosisLookup, eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, null, TentativeDiagnosis, _str_idfsTentativeDiagnosis); case _str_TentativeDiagnosis1: return new BvSelectList(TentativeDiagnosis1Lookup, eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, null, TentativeDiagnosis1, _str_idfsTentativeDiagnosis1); case _str_TentativeDiagnosis2: return new BvSelectList(TentativeDiagnosis2Lookup, eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, null, TentativeDiagnosis2, _str_idfsTentativeDiagnosis2); case _str_FinalDiagnosis: return new BvSelectList(FinalDiagnosisLookup, eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, null, FinalDiagnosis, _str_idfsFinalDiagnosis); case _str_ShowDiagnosis: return new BvSelectList(ShowDiagnosisLookup, eidss.model.Schema.DiagnosisLookup._str_idfsDiagnosis, null, ShowDiagnosis, _str_idfsShowDiagnosis); case _str_PersonInvestigatedBy: return new BvSelectList(PersonInvestigatedByLookup, eidss.model.Schema.WiderPersonLookup._str_idfPerson, null, PersonInvestigatedBy, _str_idfPersonInvestigatedBy); case _str_Vaccination: return new BvSelectList(Vaccination, "", "", null, ""); case _str_CaseTests: return new BvSelectList(CaseTests, "", "", null, ""); case _str_CaseTestValidations: return new BvSelectList(CaseTestValidations, "", "", null, ""); case _str_PensideTests: return new BvSelectList(PensideTests, "", "", null, ""); case _str_AnimalList: return new BvSelectList(AnimalList, "", "", null, ""); case _str_Samples: return new BvSelectList(Samples, "", "", null, ""); case _str_Logs: return new BvSelectList(Logs, "", "", null, ""); } return null; } [XmlIgnore] [LocalizedDisplayName(_str_strDiagnosis)] public string strDiagnosis { get { return new Func<VetCase, string>(c => String.Format("{0}{1}{2}{3}", (c.FinalDiagnosis == null) ? "" : c.FinalDiagnosis.name, (c.TentativeDiagnosis2 == null) ? "" : ((c.FinalDiagnosis == null) ? "" : ", ") + c.TentativeDiagnosis2.name, (c.TentativeDiagnosis1 == null) ? "" : ((c.FinalDiagnosis == null && c.TentativeDiagnosis2 == null) ? "" : ", ") + c.TentativeDiagnosis1.name, (c.TentativeDiagnosis == null) ? "" : ((c.FinalDiagnosis == null && c.TentativeDiagnosis2 == null && c.TentativeDiagnosis1 == null) ? "" : ", ") + c.TentativeDiagnosis.name ))(this); } } [XmlIgnore] [LocalizedDisplayName(_str_DiagnosisAll)] public List<DiagnosisLookup> DiagnosisAll { get { return new Func<VetCase, List<DiagnosisLookup>>(c => new List<DiagnosisLookup>(new [] { c.FinalDiagnosis, c.TentativeDiagnosis2, c.TentativeDiagnosis1, c.TentativeDiagnosis } .Where(d => d != null).Distinct()))(this); } } [XmlIgnore] [LocalizedDisplayName(_str_strDiseaseNames)] public string strDiseaseNames { get { return new Func<VetCase, string>(c => c.DiagnosisAll.Aggregate("", (a,b) => (a == "" ? "" : a + ", ") + b.name + (String.IsNullOrEmpty(b.strOIECode) ? "" : "(" + b.strOIECode + ")")))(this); } } [XmlIgnore] [LocalizedDisplayName(_str_IsClosed)] public bool IsClosed { get { return new Func<VetCase, bool>(c => (c.idfsCaseProgressStatus == (long)CaseStatusEnum.Closed) && !c.IsDirty)(this); } } [XmlIgnore] [LocalizedDisplayName(_str_IsEnabledCaseProgressStatus)] public bool IsEnabledCaseProgressStatus { get { return new Func<VetCase, bool>(c => (c.idfsCaseProgressStatus == (long)CaseStatusEnum.InProgress) || (c.idfsCaseProgressStatus == (long)CaseStatusEnum.Closed && c.IsDirty) || (c.idfsCaseProgressStatus == (long)CaseStatusEnum.Closed && !c.IsDirty && c.GetPermissions().CanExecute("CanReopenClosedCase")))(this); } } [XmlIgnore] [LocalizedDisplayName(_str_idfsDiagnosis)] public long? idfsDiagnosis { get { return new Func<VetCase, long?>(c=> c.idfsFinalDiagnosis.HasValue ? c.idfsFinalDiagnosis : c.idfsTentativeDiagnosis2.HasValue ? c.idfsTentativeDiagnosis2 : c.idfsTentativeDiagnosis1.HasValue ? c.idfsTentativeDiagnosis1 : c.idfsTentativeDiagnosis.HasValue ? c.idfsTentativeDiagnosis : null)(this); } } [XmlIgnore] [LocalizedDisplayName(_str_strSiteCode)] public string strSiteCode { get { return new Func<VetCase, string>(c => c.Site == null ? "" : c.Site.strSiteName)(this); } } [XmlIgnore] [LocalizedDisplayName(_str_strIdfsDiagnosis)] public string strIdfsDiagnosis { get { return new Func<VetCase, string>(c=> c.idfsFinalDiagnosis.HasValue ? c.idfsFinalDiagnosis.ToString() : c.idfsTentativeDiagnosis.HasValue ? c.idfsTentativeDiagnosis.ToString() : null)(this); } } [XmlIgnore] [LocalizedDisplayName(_str_strReadOnlyEnteredDate)] public string strReadOnlyEnteredDate { get { return new Func<VetCase, string>(c => c.datEnteredDate == null ? (string)null : c.datEnteredDate.Value.ToString())(this); } } [XmlIgnore] [LocalizedDisplayName(_str_buttonSelectFarm)] public string buttonSelectFarm { get { return new Func<VetCase, string>(c=> "")(this); } } [XmlIgnore] [LocalizedDisplayName(_str_buttonCoordinatesPicker)] public string buttonCoordinatesPicker { get { return new Func<VetCase, string>(c => "")(this); } } [XmlIgnore] [LocalizedDisplayName(_str_blnEnableTestsConductedCalc)] public bool blnEnableTestsConductedCalc { get { return new Func<VetCase, bool>(c => c.CaseTests == null || c.CaseTests.Where(i => !i.IsMarkedToDelete && i.idfsTestStatus == (long)TestStatus.Finalized).Count() == 0)(this); } } protected CacheScope m_CS; protected Accessor _getAccessor() { return Accessor.Instance(m_CS); } private IObjectPermissions m_permissions = null; internal IObjectPermissions _permissions { get { return m_permissions; } set { m_permissions = value; } } internal string m_ObjectName = "VetCase"; #region Parent and Clone supporting [XmlIgnore] public IObject Parent { get { return m_Parent; } set { m_Parent = value; /*OnPropertyChanged(_str_Parent);*/ } } private IObject m_Parent; internal void _setParent() { if (_FFPresenterControlMeasures != null) { _FFPresenterControlMeasures.Parent = this; } if (_Farm != null) { _Farm.Parent = this; } Vaccination.ForEach(c => { c.Parent = this; }); CaseTests.ForEach(c => { c.Parent = this; }); CaseTestValidations.ForEach(c => { c.Parent = this; }); PensideTests.ForEach(c => { c.Parent = this; }); AnimalList.ForEach(c => { c.Parent = this; }); Samples.ForEach(c => { c.Parent = this; }); Logs.ForEach(c => { c.Parent = this; }); } partial void Cloned(); partial void ClonedWithSetup(); public override object Clone() { var ret = base.Clone() as VetCase; ret.Cloned(); ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret._setParent(); if (this.IsDirty && !ret.IsDirty) ret.SetChange(); else if (!this.IsDirty && ret.IsDirty) ret.RejectChanges(); return ret; } public IObject CloneWithSetup(DbManagerProxy manager, bool bRestricted = false) { var ret = base.Clone() as VetCase; ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret.m_IsNew = this.IsNew; ret.m_ObjectName = this.m_ObjectName; if (_FFPresenterControlMeasures != null) ret.FFPresenterControlMeasures = _FFPresenterControlMeasures.CloneWithSetup(manager, bRestricted) as FFPresenterModel; if (_Farm != null) ret.Farm = _Farm.CloneWithSetup(manager, bRestricted) as FarmPanel; if (_Vaccination != null && _Vaccination.Count > 0) { ret.Vaccination.Clear(); _Vaccination.ForEach(c => ret.Vaccination.Add(c.CloneWithSetup(manager, bRestricted))); } if (_CaseTests != null && _CaseTests.Count > 0) { ret.CaseTests.Clear(); _CaseTests.ForEach(c => ret.CaseTests.Add(c.CloneWithSetup(manager, bRestricted))); } if (_CaseTestValidations != null && _CaseTestValidations.Count > 0) { ret.CaseTestValidations.Clear(); _CaseTestValidations.ForEach(c => ret.CaseTestValidations.Add(c.CloneWithSetup(manager, bRestricted))); } if (_PensideTests != null && _PensideTests.Count > 0) { ret.PensideTests.Clear(); _PensideTests.ForEach(c => ret.PensideTests.Add(c.CloneWithSetup(manager, bRestricted))); } if (_AnimalList != null && _AnimalList.Count > 0) { ret.AnimalList.Clear(); _AnimalList.ForEach(c => ret.AnimalList.Add(c.CloneWithSetup(manager, bRestricted))); } if (_Samples != null && _Samples.Count > 0) { ret.Samples.Clear(); _Samples.ForEach(c => ret.Samples.Add(c.CloneWithSetup(manager, bRestricted))); } if (_Logs != null && _Logs.Count > 0) { ret.Logs.Clear(); _Logs.ForEach(c => ret.Logs.Add(c.CloneWithSetup(manager, bRestricted))); } Accessor.Instance(null)._SetupLoad(manager, ret, true); ret.ClonedWithSetup(); ret.DeepAcceptChanges(); ret._setParent(); ret._permissions = _permissions; return ret; } public VetCase CloneWithSetup() { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { return CloneWithSetup(manager) as VetCase; } } #endregion #region IObject implementation public object Key { get { return idfCase; } } public string KeyName { get { return "idfCase"; } } public string ToStringProp { get { return ToString(); } } private bool m_IsNew; public bool IsNew { get { return m_IsNew; } } [XmlIgnore] [LocalizedDisplayName("HasChanges")] public bool HasChanges { get { return IsDirty || (_FFPresenterControlMeasures != null && _FFPresenterControlMeasures.HasChanges) || (_Farm != null && _Farm.HasChanges) || Vaccination.IsDirty || Vaccination.Count(c => c.IsMarkedToDelete || c.HasChanges) > 0 || CaseTests.IsDirty || CaseTests.Count(c => c.IsMarkedToDelete || c.HasChanges) > 0 || CaseTestValidations.IsDirty || CaseTestValidations.Count(c => c.IsMarkedToDelete || c.HasChanges) > 0 || PensideTests.IsDirty || PensideTests.Count(c => c.IsMarkedToDelete || c.HasChanges) > 0 || AnimalList.IsDirty || AnimalList.Count(c => c.IsMarkedToDelete || c.HasChanges) > 0 || Samples.IsDirty || Samples.Count(c => c.IsMarkedToDelete || c.HasChanges) > 0 || Logs.IsDirty || Logs.Count(c => c.IsMarkedToDelete || c.HasChanges) > 0 ; } } public new void RejectChanges() { var _prev_idfsSite_Site = idfsSite; var _prev_idfsCaseReportType_CaseReportType = idfsCaseReportType; var _prev_idfsCaseType_CaseType = idfsCaseType; var _prev_idfsCaseClassification_CaseClassification = idfsCaseClassification; var _prev_idfsCaseProgressStatus_CaseProgressStatus = idfsCaseProgressStatus; var _prev_idfsYNTestsConducted_TestsConducted = idfsYNTestsConducted; var _prev_idfsTentativeDiagnosis_TentativeDiagnosis = idfsTentativeDiagnosis; var _prev_idfsTentativeDiagnosis1_TentativeDiagnosis1 = idfsTentativeDiagnosis1; var _prev_idfsTentativeDiagnosis2_TentativeDiagnosis2 = idfsTentativeDiagnosis2; var _prev_idfsFinalDiagnosis_FinalDiagnosis = idfsFinalDiagnosis; var _prev_idfsShowDiagnosis_ShowDiagnosis = idfsShowDiagnosis; var _prev_idfPersonInvestigatedBy_PersonInvestigatedBy = idfPersonInvestigatedBy; base.RejectChanges(); if (_prev_idfsSite_Site != idfsSite) { _Site = _SiteLookup.FirstOrDefault(c => c.idfsSite == idfsSite); } if (_prev_idfsCaseReportType_CaseReportType != idfsCaseReportType) { _CaseReportType = _CaseReportTypeLookup.FirstOrDefault(c => c.idfsBaseReference == idfsCaseReportType); } if (_prev_idfsCaseType_CaseType != idfsCaseType) { _CaseType = _CaseTypeLookup.FirstOrDefault(c => c.idfsBaseReference == idfsCaseType); } if (_prev_idfsCaseClassification_CaseClassification != idfsCaseClassification) { _CaseClassification = _CaseClassificationLookup.FirstOrDefault(c => c.idfsBaseReference == idfsCaseClassification); } if (_prev_idfsCaseProgressStatus_CaseProgressStatus != idfsCaseProgressStatus) { _CaseProgressStatus = _CaseProgressStatusLookup.FirstOrDefault(c => c.idfsBaseReference == idfsCaseProgressStatus); } if (_prev_idfsYNTestsConducted_TestsConducted != idfsYNTestsConducted) { _TestsConducted = _TestsConductedLookup.FirstOrDefault(c => c.idfsBaseReference == idfsYNTestsConducted); } if (_prev_idfsTentativeDiagnosis_TentativeDiagnosis != idfsTentativeDiagnosis) { _TentativeDiagnosis = _TentativeDiagnosisLookup.FirstOrDefault(c => c.idfsDiagnosis == idfsTentativeDiagnosis); } if (_prev_idfsTentativeDiagnosis1_TentativeDiagnosis1 != idfsTentativeDiagnosis1) { _TentativeDiagnosis1 = _TentativeDiagnosis1Lookup.FirstOrDefault(c => c.idfsDiagnosis == idfsTentativeDiagnosis1); } if (_prev_idfsTentativeDiagnosis2_TentativeDiagnosis2 != idfsTentativeDiagnosis2) { _TentativeDiagnosis2 = _TentativeDiagnosis2Lookup.FirstOrDefault(c => c.idfsDiagnosis == idfsTentativeDiagnosis2); } if (_prev_idfsFinalDiagnosis_FinalDiagnosis != idfsFinalDiagnosis) { _FinalDiagnosis = _FinalDiagnosisLookup.FirstOrDefault(c => c.idfsDiagnosis == idfsFinalDiagnosis); } if (_prev_idfsShowDiagnosis_ShowDiagnosis != idfsShowDiagnosis) { _ShowDiagnosis = _ShowDiagnosisLookup.FirstOrDefault(c => c.idfsDiagnosis == idfsShowDiagnosis); } if (_prev_idfPersonInvestigatedBy_PersonInvestigatedBy != idfPersonInvestigatedBy) { _PersonInvestigatedBy = _PersonInvestigatedByLookup.FirstOrDefault(c => c.idfPerson == idfPersonInvestigatedBy); } } public void DeepRejectChanges() { RejectChanges(); if (FFPresenterControlMeasures != null) FFPresenterControlMeasures.DeepRejectChanges(); if (Farm != null) Farm.DeepRejectChanges(); Vaccination.DeepRejectChanges(); CaseTests.DeepRejectChanges(); CaseTestValidations.DeepRejectChanges(); PensideTests.DeepRejectChanges(); AnimalList.DeepRejectChanges(); Samples.DeepRejectChanges(); Logs.DeepRejectChanges(); } public void DeepAcceptChanges() { AcceptChanges(); if (_FFPresenterControlMeasures != null) _FFPresenterControlMeasures.DeepAcceptChanges(); if (_Farm != null) _Farm.DeepAcceptChanges(); Vaccination.DeepAcceptChanges(); CaseTests.DeepAcceptChanges(); CaseTestValidations.DeepAcceptChanges(); PensideTests.DeepAcceptChanges(); AnimalList.DeepAcceptChanges(); Samples.DeepAcceptChanges(); Logs.DeepAcceptChanges(); } private bool m_bForceDirty; public override void AcceptChanges() { m_bForceDirty = false; base.AcceptChanges(); } [XmlIgnore] [LocalizedDisplayName("IsDirty")] public override bool IsDirty { get { return m_bForceDirty || base.IsDirty; } } public void SetChange() { m_bForceDirty = true; } public void DeepSetChange() { SetChange(); if (_FFPresenterControlMeasures != null) _FFPresenterControlMeasures.SetChange(); if (_Farm != null) _Farm.SetChange(); Vaccination.ForEach(c => c.SetChange()); CaseTests.ForEach(c => c.SetChange()); CaseTestValidations.ForEach(c => c.SetChange()); PensideTests.ForEach(c => c.SetChange()); AnimalList.ForEach(c => c.SetChange()); Samples.ForEach(c => c.SetChange()); Logs.ForEach(c => c.SetChange()); } public bool MarkToDelete() { return _Delete(false); } public string ObjectName { get { return m_ObjectName; } } public string ObjectIdent { get { return ObjectName + "_" + Key.ToString() + "_"; } } public string ObjectIdent2 { get { return ObjectIdent; } } public string ObjectIdent3 { get { return ObjectIdent; } } public IObjectAccessor GetAccessor() { return _getAccessor(); } public IObjectPermissions GetPermissions() { return _permissions; } private IObjectEnvironment _environment; public IObjectEnvironment Environment { get { return _environment; } set { _environment = value; } } public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } } public bool IsReadOnly(string name) { return _isReadOnly(name); } public bool IsInvisible(string name) { return _isInvisible(name); } public bool IsRequired(string name) { return _isRequired(m_isRequired, name); } public bool IsHiddenPersonalData(string name) { return _isHiddenPersonalData(name); } public string GetType(string name) { return _getType(name); } public object GetValue(string name) { return _getValue(name); } public void SetValue(string name, string val) { _setValue(name, val); } public CompareModel Compare(IObject o) { return _compare(o, null); } public BvSelectList GetList(string name) { return _getList(name); } public event ValidationEvent Validation; public event ValidationEvent ValidationEnd; public event AfterPostEvent AfterPost; public Dictionary<string, string> GetFieldTags(string name) { return null; } #endregion private bool IsRIRPropChanged(string fld, VetCase c) { return IsReadOnly(fld) != c.IsReadOnly(fld) || IsInvisible(fld) != c.IsInvisible(fld) || IsRequired(fld) != c._isRequired(m_isRequired, fld); } public VetCase() { m_permissions = new Permissions(this); } partial void Changed(string fieldName); partial void Created(DbManagerProxy manager); partial void Loaded(DbManagerProxy manager); partial void Deleted(); partial void ParsedFormCollection(NameValueCollection form); private int? m_HACode; public int? _HACode { get { return m_HACode; } set { m_HACode = value; } } private bool m_IsForcedToDelete; [LocalizedDisplayName("IsForcedToDelete")] public bool IsForcedToDelete { get { return m_IsForcedToDelete; } } private bool m_IsMarkedToDelete; [LocalizedDisplayName("IsMarkedToDelete")] public bool IsMarkedToDelete { get { return m_IsMarkedToDelete; } } public void _SetupMainHandler() { PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(VetCase_PropertyChanged); } public void _RevokeMainHandler() { PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(VetCase_PropertyChanged); } private void VetCase_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { (sender as VetCase).Changed(e.PropertyName); if (e.PropertyName == _str_idfsFinalDiagnosis) OnPropertyChanged(_str_strDiagnosis); if (e.PropertyName == _str_idfsTentativeDiagnosis2) OnPropertyChanged(_str_strDiagnosis); if (e.PropertyName == _str_idfsTentativeDiagnosis1) OnPropertyChanged(_str_strDiagnosis); if (e.PropertyName == _str_idfsTentativeDiagnosis) OnPropertyChanged(_str_strDiagnosis); if (e.PropertyName == _str_idfsFinalDiagnosis) OnPropertyChanged(_str_DiagnosisAll); if (e.PropertyName == _str_idfsTentativeDiagnosis2) OnPropertyChanged(_str_DiagnosisAll); if (e.PropertyName == _str_idfsTentativeDiagnosis1) OnPropertyChanged(_str_DiagnosisAll); if (e.PropertyName == _str_idfsTentativeDiagnosis) OnPropertyChanged(_str_DiagnosisAll); if (e.PropertyName == _str_DiagnosisAll) OnPropertyChanged(_str_strDiseaseNames); if (e.PropertyName == _str_idfsCaseProgressStatus) OnPropertyChanged(_str_IsClosed); if (e.PropertyName == _str_idfsCaseProgressStatus) OnPropertyChanged(_str_IsEnabledCaseProgressStatus); if (e.PropertyName == _str_idfsFinalDiagnosis) OnPropertyChanged(_str_idfsDiagnosis); if (e.PropertyName == _str_idfsTentativeDiagnosis2) OnPropertyChanged(_str_idfsDiagnosis); if (e.PropertyName == _str_idfsTentativeDiagnosis1) OnPropertyChanged(_str_idfsDiagnosis); if (e.PropertyName == _str_idfsTentativeDiagnosis) OnPropertyChanged(_str_idfsDiagnosis); if (e.PropertyName == _str_idfsSite) OnPropertyChanged(_str_strSiteCode); if (e.PropertyName == _str_idfsFinalDiagnosis) OnPropertyChanged(_str_strIdfsDiagnosis); if (e.PropertyName == _str_idfsTentativeDiagnosis) OnPropertyChanged(_str_strIdfsDiagnosis); if (e.PropertyName == _str_datEnteredDate) OnPropertyChanged(_str_strReadOnlyEnteredDate); if (e.PropertyName == _str_Farm) OnPropertyChanged(_str_buttonSelectFarm); if (e.PropertyName == _str_Farm) OnPropertyChanged(_str_buttonCoordinatesPicker); } public bool ForceToDelete() { return _Delete(true); } internal bool _Delete(bool isForceDelete) { if (!_ValidateOnDelete()) return false; _DeletingExtenders(); m_IsMarkedToDelete = true; m_IsForcedToDelete = m_IsForcedToDelete ? m_IsForcedToDelete : isForceDelete; OnPropertyChanged("IsMarkedToDelete"); _DeletedExtenders(); Deleted(); return true; } private bool _ValidateOnDelete(bool bReport = true) { return Accessor.Instance(null).ValidateCanDelete(this); } private void _DeletingExtenders() { VetCase obj = this; } private void _DeletedExtenders() { VetCase obj = this; } public bool OnValidation(ValidationModelException ex) { if (Validation != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk); Validation(this, args); return args.Continue; } return false; } public bool OnValidationEnd(ValidationModelException ex) { if (ValidationEnd != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk); ValidationEnd(this, args); return args.Continue; } return false; } public void OnAfterPost() { if (AfterPost != null) { AfterPost(this, EventArgs.Empty); } } public FormSize FormSize { get { return FormSize.Undefined; } } private bool _isInvisible(string name) { return false; } private static string[] readonly_names1 = "idfsCaseProgressStatus,CaseProgressStatus".Split(new char[] { ',' }); private static string[] readonly_names2 = "strOutbreakID".Split(new char[] { ',' }); private static string[] readonly_names3 = "idfOutbreak".Split(new char[] { ',' }); private static string[] readonly_names4 = "strReadOnlyLocalIdentifier,strReadOnlyEnteredDate".Split(new char[] { ',' }); private static string[] readonly_names5 = "strSiteCode,strMonitoringSessionID,idfParentMonitoringSession".Split(new char[] { ',' }); private static string[] readonly_names6 = "idfsCaseType,CaseType,datEnteredDate,strCaseID,strDiseaseNames,strDiagnosis,idfPersonEnteredBy,idfsSite,strPersonEnteredByName,strTentativeDiagnosisOIECode,strTentativeDiagnosis1OIECode,strTentativeDiagnosis2OIECode,strFinalDiagnosisOIECode".Split(new char[] { ',' }); private static string[] readonly_names7 = "strInvestigatedByOffice,strReportedByOffice,strPersonInvestigatedBy,strPersonReportedBy".Split(new char[] { ',' }); private static string[] readonly_names8 = "PersonInvestigatedBy,idfPersonInvestigatedBy".Split(new char[] { ',' }); private static string[] readonly_names9 = "TestsConducted,idfsYNTestsConducted".Split(new char[] { ',' }); private static string[] readonly_names10 = "CaseTests,CaseTestValidations".Split(new char[] { ',' }); private static string[] readonly_names11 = "idfsCaseReportType,CaseReportType".Split(new char[] { ',' }); private static string[] readonly_names12 = "buttonSelectFarm,buttonCoordinatesPicker".Split(new char[] { ',' }); private static string[] readonly_names13 = "datTentativeDiagnosisDate".Split(new char[] { ',' }); private static string[] readonly_names14 = "datTentativeDiagnosis1Date".Split(new char[] { ',' }); private static string[] readonly_names15 = "datTentativeDiagnosis2Date".Split(new char[] { ',' }); private static string[] readonly_names16 = "datFinalDiagnosisDate".Split(new char[] { ',' }); private bool _isReadOnly(string name) { if (readonly_names1.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.ReadOnly || !c.IsEnabledCaseProgressStatus)(this); if (readonly_names2.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => true)(this); if (readonly_names3.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly)(this); if (readonly_names4.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => true)(this); if (readonly_names5.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => true)(this); if (readonly_names6.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => true)(this); if (readonly_names7.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => true)(this); if (readonly_names8.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly || c.idfInvestigatedByOffice == null)(this); if (readonly_names9.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly || (c.blnEnableTestsConducted != null && !c.blnEnableTestsConducted.Value) || !c.blnEnableTestsConductedCalc)(this); if (readonly_names10.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly)(this); if (readonly_names11.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly || c.idfParentMonitoringSession.HasValue)(this); if (readonly_names12.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly)(this); if (readonly_names13.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly || !c.idfsTentativeDiagnosis.HasValue)(this); if (readonly_names14.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly || !c.idfsTentativeDiagnosis1.HasValue)(this); if (readonly_names15.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly || !c.idfsTentativeDiagnosis2.HasValue)(this); if (readonly_names16.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VetCase, bool>(c => c.IsClosed || c.ReadOnly || !c.idfsFinalDiagnosis.HasValue)(this); return ReadOnly || new Func<VetCase, bool>(c => c.ReadOnly || c.IsClosed)(this); } private bool m_readOnly; private bool _readOnly { get { return m_readOnly; } set { m_readOnly = value; if (_FFPresenterControlMeasures != null) _FFPresenterControlMeasures.ReadOnly |= value; if (_Farm != null) _Farm.ReadOnly |= value; foreach(var o in _Vaccination) o.ReadOnly |= value; foreach(var o in _CaseTests) o.ReadOnly |= value; foreach(var o in _CaseTestValidations) o.ReadOnly |= value; foreach(var o in _PensideTests) o.ReadOnly |= value; foreach(var o in _AnimalList) o.ReadOnly |= value; foreach(var o in _Samples) o.ReadOnly |= value; foreach(var o in _Logs) o.ReadOnly |= value; } } internal Dictionary<string, Func<VetCase, bool>> m_isRequired; private bool _isRequired(Dictionary<string, Func<VetCase, bool>> isRequiredDict, string name) { if (isRequiredDict != null && isRequiredDict.ContainsKey(name)) return isRequiredDict[name](this); return false; } public void AddRequired(string name, Func<VetCase, bool> func) { if (m_isRequired == null) m_isRequired = new Dictionary<string, Func<VetCase, bool>>(); if (!m_isRequired.ContainsKey(name)) m_isRequired.Add(name, func); } internal Dictionary<string, Func<VetCase, bool>> m_isHiddenPersonalData; private bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData != null && m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name](this); return false; } public void AddHiddenPersonalData(string name, Func<VetCase, bool> func) { if (m_isHiddenPersonalData == null) m_isHiddenPersonalData = new Dictionary<string, Func<VetCase, bool>>(); if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, func); } #region IDisposable Members private bool bIsDisposed; ~VetCase() { Dispose(); } public void Dispose() { if (!bIsDisposed) { bIsDisposed = true; if (_FFPresenterControlMeasures != null) FFPresenterControlMeasures.Dispose(); if (_Farm != null) Farm.Dispose(); Vaccination.ForEach(c => c.Dispose()); CaseTests.ForEach(c => c.Dispose()); CaseTestValidations.ForEach(c => c.Dispose()); PensideTests.ForEach(c => c.Dispose()); AnimalList.ForEach(c => c.Dispose()); Samples.ForEach(c => c.Dispose()); Logs.ForEach(c => c.Dispose()); LookupManager.RemoveObject("SiteLookup", this); LookupManager.RemoveObject("rftCaseReportType", this); LookupManager.RemoveObject("rftCaseType", this); LookupManager.RemoveObject("rftCaseClassification", this); LookupManager.RemoveObject("rftCaseProgressStatus", this); LookupManager.RemoveObject("rftYesNoValue", this); LookupManager.RemoveObject("DiagnosisLookup", this); LookupManager.RemoveObject("DiagnosisLookup", this); LookupManager.RemoveObject("DiagnosisLookup", this); LookupManager.RemoveObject("DiagnosisLookup", this); LookupManager.RemoveObject("DiagnosisLookup", this); LookupManager.RemoveObject("WiderPersonLookup", this); } } #endregion #region ILookupUsage Members public void ReloadLookupItem(DbManagerProxy manager, string lookup_object) { if (lookup_object == "SiteLookup") _getAccessor().LoadLookup_Site(manager, this); if (lookup_object == "rftCaseReportType") _getAccessor().LoadLookup_CaseReportType(manager, this); if (lookup_object == "rftCaseType") _getAccessor().LoadLookup_CaseType(manager, this); if (lookup_object == "rftCaseClassification") _getAccessor().LoadLookup_CaseClassification(manager, this); if (lookup_object == "rftCaseProgressStatus") _getAccessor().LoadLookup_CaseProgressStatus(manager, this); if (lookup_object == "rftYesNoValue") _getAccessor().LoadLookup_TestsConducted(manager, this); if (lookup_object == "DiagnosisLookup") _getAccessor().LoadLookup_TentativeDiagnosis(manager, this); if (lookup_object == "DiagnosisLookup") _getAccessor().LoadLookup_TentativeDiagnosis1(manager, this); if (lookup_object == "DiagnosisLookup") _getAccessor().LoadLookup_TentativeDiagnosis2(manager, this); if (lookup_object == "DiagnosisLookup") _getAccessor().LoadLookup_FinalDiagnosis(manager, this); if (lookup_object == "DiagnosisLookup") _getAccessor().LoadLookup_ShowDiagnosis(manager, this); if (lookup_object == "WiderPersonLookup") _getAccessor().LoadLookup_PersonInvestigatedBy(manager, this); } #endregion public void ParseFormCollection(NameValueCollection form, bool bParseLookups = true, bool bParseRelations = true) { if (bParseLookups) { _field_infos.Where(i => i._type == "Lookup").ToList().ForEach(a => { if (form[ObjectIdent + a._formname] != null) a._set_func(this, form[ObjectIdent + a._formname]);} ); } _field_infos.Where(i => i._type != "Lookup" && i._type != "Child" && i._type != "Relation" && i._type != null) .ToList().ForEach(a => { if (form.AllKeys.Contains(ObjectIdent + a._formname)) a._set_func(this, form[ObjectIdent + a._formname]);} ); if (bParseRelations) { if (_FFPresenterControlMeasures != null) _FFPresenterControlMeasures.ParseFormCollection(form, bParseLookups, bParseRelations); if (_Farm != null) _Farm.ParseFormCollection(form, bParseLookups, bParseRelations); if (_Vaccination != null) _Vaccination.ForEach(c => c.ParseFormCollection(form, bParseLookups, bParseRelations)); if (_CaseTests != null) _CaseTests.ForEach(c => c.ParseFormCollection(form, bParseLookups, bParseRelations)); if (_CaseTestValidations != null) _CaseTestValidations.ForEach(c => c.ParseFormCollection(form, bParseLookups, bParseRelations)); if (_PensideTests != null) _PensideTests.ForEach(c => c.ParseFormCollection(form, bParseLookups, bParseRelations)); if (_AnimalList != null) _AnimalList.ForEach(c => c.ParseFormCollection(form, bParseLookups, bParseRelations)); if (_Samples != null) _Samples.ForEach(c => c.ParseFormCollection(form, bParseLookups, bParseRelations)); if (_Logs != null) _Logs.ForEach(c => c.ParseFormCollection(form, bParseLookups, bParseRelations)); } ParsedFormCollection(form); } #region Accessor public abstract partial class Accessor : DataAccessor<VetCase> , IObjectAccessor , IObjectMeta , IObjectValidator , IObjectPermissions , IObjectCreator , IObjectCreator<VetCase> , IObjectSelectDetail , IObjectSelectDetail<VetCase> , IObjectPost , IObjectDelete { #region IObjectAccessor public string KeyName { get { return "idfCase"; } } #endregion private delegate void on_action(VetCase obj); private static Accessor g_Instance = CreateInstance<Accessor>(); private CacheScope m_CS; public static Accessor Instance(CacheScope cs) { if (cs == null) return g_Instance; lock(cs) { object acc = cs.Get(typeof (Accessor)); if (acc != null) { return acc as Accessor; } Accessor ret = CreateInstance<Accessor>(); ret.m_CS = cs; cs.Add(typeof(Accessor), ret); return ret; } } private FFPresenterModel.Accessor FFPresenterControlMeasuresAccessor { get { return eidss.model.Schema.FFPresenterModel.Accessor.Instance(m_CS); } } private FarmPanel.Accessor FarmAccessor { get { return eidss.model.Schema.FarmPanel.Accessor.Instance(m_CS); } } private VaccinationListItem.Accessor VaccinationAccessor { get { return eidss.model.Schema.VaccinationListItem.Accessor.Instance(m_CS); } } private CaseTest.Accessor CaseTestsAccessor { get { return eidss.model.Schema.CaseTest.Accessor.Instance(m_CS); } } private CaseTestValidation.Accessor CaseTestValidationsAccessor { get { return eidss.model.Schema.CaseTestValidation.Accessor.Instance(m_CS); } } private PensideTest.Accessor PensideTestsAccessor { get { return eidss.model.Schema.PensideTest.Accessor.Instance(m_CS); } } private AnimalListItem.Accessor AnimalListAccessor { get { return eidss.model.Schema.AnimalListItem.Accessor.Instance(m_CS); } } private VetCaseSample.Accessor SamplesAccessor { get { return eidss.model.Schema.VetCaseSample.Accessor.Instance(m_CS); } } private VetCaseLog.Accessor LogsAccessor { get { return eidss.model.Schema.VetCaseLog.Accessor.Instance(m_CS); } } private SiteLookup.Accessor SiteAccessor { get { return eidss.model.Schema.SiteLookup.Accessor.Instance(m_CS); } } private BaseReference.Accessor CaseReportTypeAccessor { get { return eidss.model.Schema.BaseReference.Accessor.Instance(m_CS); } } private BaseReference.Accessor CaseTypeAccessor { get { return eidss.model.Schema.BaseReference.Accessor.Instance(m_CS); } } private BaseReference.Accessor CaseClassificationAccessor { get { return eidss.model.Schema.BaseReference.Accessor.Instance(m_CS); } } private BaseReference.Accessor CaseProgressStatusAccessor { get { return eidss.model.Schema.BaseReference.Accessor.Instance(m_CS); } } private BaseReference.Accessor TestsConductedAccessor { get { return eidss.model.Schema.BaseReference.Accessor.Instance(m_CS); } } private DiagnosisLookup.Accessor TentativeDiagnosisAccessor { get { return eidss.model.Schema.DiagnosisLookup.Accessor.Instance(m_CS); } } private DiagnosisLookup.Accessor TentativeDiagnosis1Accessor { get { return eidss.model.Schema.DiagnosisLookup.Accessor.Instance(m_CS); } } private DiagnosisLookup.Accessor TentativeDiagnosis2Accessor { get { return eidss.model.Schema.DiagnosisLookup.Accessor.Instance(m_CS); } } private DiagnosisLookup.Accessor FinalDiagnosisAccessor { get { return eidss.model.Schema.DiagnosisLookup.Accessor.Instance(m_CS); } } private DiagnosisLookup.Accessor ShowDiagnosisAccessor { get { return eidss.model.Schema.DiagnosisLookup.Accessor.Instance(m_CS); } } private WiderPersonLookup.Accessor PersonInvestigatedByAccessor { get { return eidss.model.Schema.WiderPersonLookup.Accessor.Instance(m_CS); } } public virtual IObject SelectDetail(DbManagerProxy manager, object ident, int? HACode = null) { if (ident == null) { return CreateNew(manager, null, HACode); } else { return _SelectByKey(manager , (Int64?)ident , HACode , null, null ); } } public virtual VetCase SelectDetailT(DbManagerProxy manager, object ident, int? HACode = null) { if (ident == null) { return CreateNewT(manager, null, HACode); } else { return _SelectByKey(manager , (Int64?)ident , HACode , null, null ); } } public virtual VetCase SelectByKey(DbManagerProxy manager , Int64? idfCase , int? HACode = null ) { return _SelectByKey(manager , idfCase , HACode , null, null ); } private VetCase _SelectByKey(DbManagerProxy manager , Int64? idfCase , int? HACode , on_action loading, on_action loaded ) { MapResultSet[] sets = new MapResultSet[1]; List<VetCase> objs = new List<VetCase>(); sets[0] = new MapResultSet(typeof(VetCase), objs); try { manager .SetSpCommand("spVetCase_SelectDetail" , manager.Parameter("@idfCase", idfCase) , manager.Parameter("@LangID", ModelUserContext.CurrentLanguage) ) .ExecuteResultSet(sets); if (objs.Count == 0) return null; VetCase obj = objs[0]; obj.m_CS = m_CS; obj._HACode = HACode; if (loading != null) loading(obj); _SetupLoad(manager, obj); //obj._setParent(); if (loaded != null) loaded(obj); obj.Loaded(manager); return obj; } catch(DataException e) { throw DbModelException.Create(e); } } private void _SetupAddChildHandlerVaccination(VetCase obj) { obj.Vaccination.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach(var o in e.NewItems) { _SetupChildHandlers(obj, o); } } }; } private void _SetupAddChildHandlerCaseTests(VetCase obj) { obj.CaseTests.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach(var o in e.NewItems) { _SetupChildHandlers(obj, o); } } }; } private void _SetupAddChildHandlerCaseTestValidations(VetCase obj) { obj.CaseTestValidations.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach(var o in e.NewItems) { _SetupChildHandlers(obj, o); } } }; } private void _SetupAddChildHandlerPensideTests(VetCase obj) { obj.PensideTests.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach(var o in e.NewItems) { _SetupChildHandlers(obj, o); } } }; } private void _SetupAddChildHandlerAnimalList(VetCase obj) { obj.AnimalList.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach(var o in e.NewItems) { _SetupChildHandlers(obj, o); } } }; } private void _SetupAddChildHandlerSamples(VetCase obj) { obj.Samples.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach(var o in e.NewItems) { _SetupChildHandlers(obj, o); } } }; } private void _SetupAddChildHandlerLogs(VetCase obj) { obj.Logs.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach(var o in e.NewItems) { _SetupChildHandlers(obj, o); } } }; } internal void _LoadFFPresenterControlMeasures(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadFFPresenterControlMeasures(manager, obj); } } internal void _LoadFFPresenterControlMeasures(DbManagerProxy manager, VetCase obj) { if (obj.FFPresenterControlMeasures == null && obj.idfObservation != null && obj.idfObservation != 0) { obj.FFPresenterControlMeasures = FFPresenterControlMeasuresAccessor.SelectByKey(manager , obj.idfObservation.Value ); if (obj.FFPresenterControlMeasures != null) { obj.FFPresenterControlMeasures.m_ObjectName = _str_FFPresenterControlMeasures; } } } internal void _LoadFarm(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadFarm(manager, obj); } } internal void _LoadFarm(DbManagerProxy manager, VetCase obj) { if (obj.Farm == null && obj.idfFarm != 0) { obj.Farm = FarmAccessor.SelectByKey(manager , obj.idfFarm , obj._HACode ); if (obj.Farm != null) { obj.Farm.m_ObjectName = _str_Farm; } } } internal void _LoadVaccination(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadVaccination(manager, obj); } } internal void _LoadVaccination(DbManagerProxy manager, VetCase obj) { obj.Vaccination.Clear(); obj.Vaccination.AddRange(VaccinationAccessor.SelectDetailList(manager , obj.idfCase , obj._HACode )); obj.Vaccination.ForEach(c => c.m_ObjectName = _str_Vaccination); obj.Vaccination.AcceptChanges(); } internal void _LoadCaseTests(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadCaseTests(manager, obj); } } internal void _LoadCaseTests(DbManagerProxy manager, VetCase obj) { obj.CaseTests.Clear(); obj.CaseTests.AddRange(CaseTestsAccessor.SelectDetailList(manager , obj.idfCase )); obj.CaseTests.ForEach(c => c.m_ObjectName = _str_CaseTests); obj.CaseTests.AcceptChanges(); } internal void _LoadCaseTestValidations(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadCaseTestValidations(manager, obj); } } internal void _LoadCaseTestValidations(DbManagerProxy manager, VetCase obj) { obj.CaseTestValidations.Clear(); obj.CaseTestValidations.AddRange(CaseTestValidationsAccessor.SelectDetailList(manager , obj.idfCase )); obj.CaseTestValidations.ForEach(c => c.m_ObjectName = _str_CaseTestValidations); obj.CaseTestValidations.AcceptChanges(); } internal void _LoadPensideTests(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadPensideTests(manager, obj); } } internal void _LoadPensideTests(DbManagerProxy manager, VetCase obj) { obj.PensideTests.Clear(); obj.PensideTests.AddRange(PensideTestsAccessor.SelectDetailList(manager , obj.idfCase )); obj.PensideTests.ForEach(c => c.m_ObjectName = _str_PensideTests); obj.PensideTests.AcceptChanges(); } internal void _LoadAnimalList(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadAnimalList(manager, obj); } } internal void _LoadAnimalList(DbManagerProxy manager, VetCase obj) { obj.AnimalList.Clear(); obj.AnimalList.AddRange(AnimalListAccessor.SelectDetailList(manager , obj.idfCase , obj._HACode )); obj.AnimalList.ForEach(c => c.m_ObjectName = _str_AnimalList); obj.AnimalList.AcceptChanges(); } internal void _LoadSamples(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadSamples(manager, obj); } } internal void _LoadSamples(DbManagerProxy manager, VetCase obj) { obj.Samples.Clear(); obj.Samples.AddRange(SamplesAccessor.SelectDetailList(manager , obj.idfCase )); obj.Samples.ForEach(c => c.m_ObjectName = _str_Samples); obj.Samples.AcceptChanges(); } internal void _LoadLogs(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { _LoadLogs(manager, obj); } } internal void _LoadLogs(DbManagerProxy manager, VetCase obj) { obj.Logs.Clear(); obj.Logs.AddRange(LogsAccessor.SelectDetailList(manager , obj.idfCase )); obj.Logs.ForEach(c => c.m_ObjectName = _str_Logs); obj.Logs.AcceptChanges(); } internal void _SetupLoad(DbManagerProxy manager, VetCase obj, bool bCloning = false) { if (obj == null) return; // loading extenters - begin obj._HACode = new Func<VetCase, int?>(c => (c.idfsCaseType == (long)CaseTypeEnum.Livestock ? 32 : 64))(obj); obj.Farm = new Func<VetCase, FarmPanel>(c=> c.Farm ?? FarmAccessor.CreateByCase(manager, c, c))(obj); obj.Farm.Case = new Func<VetCase, WeakReference>(c => new WeakReference(c))(obj); obj.Farm.FarmTree.ForEach(t => { t.Case = new Func<VetCase, WeakReference>(c => c.Farm.Case)(obj); } ); obj.idfFarm = new Func<VetCase, long>(c => c.Farm.idfFarm)(obj); // loading extenters - end if (!bCloning) { _LoadFFPresenterControlMeasures(manager, obj); _LoadVaccination(manager, obj); _LoadCaseTests(manager, obj); _LoadCaseTestValidations(manager, obj); _LoadPensideTests(manager, obj); _LoadAnimalList(manager, obj); _LoadSamples(manager, obj); _LoadLogs(manager, obj); } _LoadLookups(manager, obj); obj._setParent(); // loaded extenters - begin obj.TestsConducted = new Func<VetCase, BaseReference>(c => (c.blnEnableTestsConducted == null || c.blnEnableTestsConducted.Value || c.TestsConductedLookup == null || c.blnEnableTestsConductedCalc) ? c.TestsConducted : c.TestsConductedLookup.Where(i => i.idfsBaseReference == (long)YesNoUnknownValuesEnum.Yes).SingleOrDefault())(obj); obj.Samples.ForEach(t => { t._HACode = new Func<VetCase, int?>(c => c._HACode)(obj); } ); obj.CaseTests.ForEach(t => { t.idfTesting = new Func<VetCase, long>(c => { (t.GetAccessor() as CaseTest.Accessor).LoadLookup_TestNameRef(manager, t); return t.idfTesting; })(obj); } ); obj.PensideTests.ForEach(t => { t._HACode = new Func<VetCase, int?>(c => c._HACode)(obj); } ); obj.PensideTests.ForEach(t => { t.strDummy = new Func<VetCase, string>(c => "")(obj); } ); if (obj.idfsFormTemplate.HasValue) { obj.FFPresenterControlMeasures.SetProperties(obj.idfsFormTemplate.Value, obj.idfCase); obj.FFPresenterControlMeasures.ReadOnly = obj.IsClosed; } else { if (obj._HACode.Value == (int)eidss.model.Enums.HACode.Livestock) { if (obj.idfObservation == null) obj.idfObservation = (new GetNewIDExtender<VetCase>()).GetScalar(manager, obj); obj.FFPresenterControlMeasures = FFPresenterModel.Accessor.Instance(null).SelectByKey(manager, obj.idfObservation); obj.FFPresenterControlMeasures.SetProperties(EidssSiteContext.Instance.CountryID, null, FFTypeEnum.LivestockControlMeasures, obj.idfObservation.Value, obj.idfCase); if (obj.FFPresenterControlMeasures.CurrentTemplate != null) obj.idfsFormTemplate = obj.FFPresenterControlMeasures.CurrentTemplate.idfsFormTemplate; } } // loaded extenters - end _SetupHandlers(obj); _SetupChildHandlers(obj, null); _SetupAddChildHandlerVaccination(obj); _SetupAddChildHandlerCaseTests(obj); _SetupAddChildHandlerCaseTestValidations(obj); _SetupAddChildHandlerPensideTests(obj); _SetupAddChildHandlerAnimalList(obj); _SetupAddChildHandlerSamples(obj); _SetupAddChildHandlerLogs(obj); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); obj._SetupMainHandler(); obj.AcceptChanges(); } internal void _SetPermitions(IObjectPermissions permissions, VetCase obj) { if (obj != null) { obj._permissions = permissions; if (obj._permissions != null) { FFPresenterControlMeasuresAccessor._SetPermitions(obj._permissions, obj.FFPresenterControlMeasures); FarmAccessor._SetPermitions(obj._permissions, obj.Farm); obj.Vaccination.ForEach(c => VaccinationAccessor._SetPermitions(obj._permissions, c)); obj.CaseTests.ForEach(c => CaseTestsAccessor._SetPermitions(obj._permissions, c)); obj.CaseTestValidations.ForEach(c => CaseTestValidationsAccessor._SetPermitions(obj._permissions, c)); obj.PensideTests.ForEach(c => PensideTestsAccessor._SetPermitions(obj._permissions, c)); obj.AnimalList.ForEach(c => AnimalListAccessor._SetPermitions(obj._permissions, c)); obj.Samples.ForEach(c => SamplesAccessor._SetPermitions(obj._permissions, c)); obj.Logs.ForEach(c => LogsAccessor._SetPermitions(obj._permissions, c)); } } } private VetCase _CreateNew(DbManagerProxy manager, IObject Parent, int? HACode, on_action creating, on_action created, bool isFake = false) { try { VetCase obj = VetCase.CreateInstance(); obj.m_CS = m_CS; obj.m_IsNew = true; obj.Parent = Parent; obj._HACode = HACode; if (creating != null) creating(obj); // creating extenters - begin obj.idfsCaseType = new Func<VetCase, long>(c => (HACode == (int)eidss.model.Enums.HACode.Livestock ? (long)CaseTypeEnum.Livestock : (long)CaseTypeEnum.Avian))(obj); obj.idfCase = (new GetNewIDExtender<VetCase>()).GetScalar(manager, obj, isFake); obj.strCaseID = new Func<VetCase, string>(c => "(new)")(obj); obj.idfObservation = (new GetNewIDExtender<VetCase>()).GetScalar(manager, obj, isFake); obj.idfsSite = (new GetSiteIDExtender<VetCase>()).GetScalar(manager, obj, isFake); obj.datEnteredDate = new Func<VetCase, DateTime>(c => DateTime.Now)(obj); obj.Farm = new Func<VetCase, FarmPanel>(c => FarmAccessor.CreateByCase(manager, c, c))(obj); obj.idfFarm = new Func<VetCase, long>(c => c.Farm.idfFarm)(obj); obj.Farm._HACode = obj.Farm.intHACode = obj._HACode; if (EidssUserContext.Instance != null) { if (EidssUserContext.User != null) { obj.strPersonEnteredByName = EidssUserContext.User.FullName; if (EidssUserContext.User.EmployeeID != null) { long em; if (long.TryParse(EidssUserContext.User.EmployeeID.ToString(), out em)) obj.idfPersonEnteredBy = em; } } if (HACode.Value == (int)eidss.model.Enums.HACode.Livestock) { obj.FFPresenterControlMeasures = FFPresenterModel.Accessor.Instance(null).SelectByKey(manager, obj.idfObservation); obj.FFPresenterControlMeasures.SetProperties(EidssSiteContext.Instance.CountryID, null, FFTypeEnum.LivestockControlMeasures, obj.idfObservation.Value, obj.idfCase); if (obj.FFPresenterControlMeasures.CurrentTemplate != null) { obj.idfsFormTemplate = obj.FFPresenterControlMeasures.CurrentTemplate.idfsFormTemplate; } } } // creating extenters - end _LoadLookups(manager, obj); _SetupHandlers(obj); _SetupChildHandlers(obj, null); _SetupAddChildHandlerVaccination(obj); _SetupAddChildHandlerCaseTests(obj); _SetupAddChildHandlerCaseTestValidations(obj); _SetupAddChildHandlerPensideTests(obj); _SetupAddChildHandlerAnimalList(obj); _SetupAddChildHandlerSamples(obj); _SetupAddChildHandlerLogs(obj); obj._SetupMainHandler(); obj._setParent(); // created extenters - begin obj.CaseProgressStatus = (new SelectLookupExtender<BaseReference>()).Select(obj.CaseProgressStatusLookup, c => c.idfsBaseReference == (long)CaseStatusEnum.InProgress); // created extenters - end if (created != null) created(obj); obj.Created(manager); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); return obj; } catch(DataException e) { throw DbModelException.Create(e); } } public VetCase CreateNewT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public IObject CreateNew(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public VetCase CreateFakeT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public IObject CreateFake(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public VetCase CreateWithParamsT(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } public IObject CreateWithParams(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } public ActResult VetInvestigationReport(DbManagerProxy manager, VetCase obj, List<object> pars) { if (pars.Count != 2) throw new ParamsCountException(); if (pars[0] != null && !(pars[0] is long)) throw new TypeMismatchException("id", typeof(long)); if (pars[1] != null && !(pars[1] is long)) throw new TypeMismatchException("diagnosisId", typeof(long)); return VetInvestigationReport(manager, obj , (long)pars[0] , (long)pars[1] ); } public ActResult VetInvestigationReport(DbManagerProxy manager, VetCase obj , long id , long diagnosisId ) { if (obj != null && !obj.GetPermissions().CanExecute("VetInvestigationReport")) throw new PermissionException("VetCase", "VetInvestigationReport"); return true; } private void _SetupChildHandlers(VetCase obj, object newobj) { foreach(var o in obj.CaseTestValidations.Where(c => !c.IsMarkedToDelete)) { if (newobj == null || newobj == o) { var item = o; o._RevokeMainHandler(); o.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "datInterpretationDate") { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { item.LockNotifyChanges(); item.CancelMemberLastChanges("datInterpretationDate"); obj.OnValidationEnd(ex); item.UnlockNotifyChanges(); } } }; o._SetupMainHandler(); } } foreach(var o in obj.CaseTestValidations.Where(c => !c.IsMarkedToDelete)) { if (newobj == null || newobj == o) { var item = o; o._RevokeMainHandler(); o.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "datValidationDate") { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { item.LockNotifyChanges(); item.CancelMemberLastChanges("datValidationDate"); obj.OnValidationEnd(ex); item.UnlockNotifyChanges(); } } }; o._SetupMainHandler(); } } foreach(var o in obj.Samples.Where(c => !c.IsMarkedToDelete)) { if (newobj == null || newobj == o) { var item = o; o._RevokeMainHandler(); o.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "datFieldCollectionDate") { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { item.LockNotifyChanges(); item.CancelMemberLastChanges("datFieldCollectionDate"); obj.OnValidationEnd(ex); item.UnlockNotifyChanges(); } } }; o._SetupMainHandler(); } } foreach(var o in obj.CaseTests.Where(c => !c.IsMarkedToDelete)) { if (newobj == null || newobj == o) { var item = o; o._RevokeMainHandler(); o.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "datConcludedDate") { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { item.LockNotifyChanges(); item.CancelMemberLastChanges("datConcludedDate"); obj.OnValidationEnd(ex); item.UnlockNotifyChanges(); } } }; o._SetupMainHandler(); } } } private void _SetupHandlers(VetCase obj) { obj.CaseTestValidations.ListChanged += delegate(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { if (obj.CaseTestValidations.Count > e.NewIndex) obj.CaseTestValidations.RemoveAt(e.NewIndex); } } }; obj.CaseTestValidations.ListChanged += delegate(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { if (obj.CaseTestValidations.Count > e.NewIndex) obj.CaseTestValidations.RemoveAt(e.NewIndex); } } }; obj.Samples.ListChanged += delegate(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { if (obj.Samples.Count > e.NewIndex) obj.Samples.RemoveAt(e.NewIndex); } } }; obj.CaseTests.ListChanged += delegate(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { if (obj.CaseTests.Count > e.NewIndex) obj.CaseTests.RemoveAt(e.NewIndex); } } }; obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == _str_datInvestigationDate) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datInvestigationDate); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } if (e.PropertyName == _str_datReportDate) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datReportDate); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } if (e.PropertyName == _str_datInvestigationDate) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datInvestigationDate); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } if (e.PropertyName == _str_datAssignedDate) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datAssignedDate); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } if (e.PropertyName == _str_datTentativeDiagnosisDate) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datTentativeDiagnosisDate); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } if (e.PropertyName == _str_datTentativeDiagnosis1Date) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datTentativeDiagnosis1Date); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } if (e.PropertyName == _str_datTentativeDiagnosis2Date) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datTentativeDiagnosis2Date); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } if (e.PropertyName == _str_datFinalDiagnosisDate) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datFinalDiagnosisDate); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } }; obj.CaseTests.ListChanged += delegate(object sender, ListChangedEventArgs e) { obj.TestsConducted = new Func<VetCase, BaseReference>(c => (c.CaseTests.Count(i => !i.IsMarkedToDelete) == 0) ? c.TestsConducted : c.TestsConductedLookup.Where(i => i.idfsBaseReference == (long)YesNoUnknownValuesEnum.Yes).SingleOrDefault())(obj); }; obj.AnimalList.ListChanged += delegate(object sender, ListChangedEventArgs e) { obj._HACode = new Func<VetCase, int?>(c => { if (e.ListChangedType == ListChangedType.ItemAdded) { var a = obj.AnimalList[e.NewIndex]; var sp = obj.Farm.FarmTree.FirstOrDefault(s => s.idfParty == a.idfSpecies); if (sp != null) a.CopyMainProperties(sp); } return c._HACode; })(obj); }; obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == _str_idfOutbreak) { try { CheckOutbreak(obj); } catch(ValidationModelException ex) { if (!obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_idfOutbreak); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } else if (ex.ShouldAsk) { obj.LockNotifyChanges(); new Action<VetCase>(c => c.ChangeOutbreakDiagnosis())(obj); obj.UnlockNotifyChanges(); } } } if (e.PropertyName == _str_idfsTentativeDiagnosis) { obj.datTentativeDiagnosisDate = new Func<VetCase, DateTime?>(c => c.idfsTentativeDiagnosis.HasValue ? (c.datTentativeDiagnosisDate.HasValue ? c.datTentativeDiagnosisDate : DateTime.Today) : null)(obj); } if (e.PropertyName == _str_idfsTentativeDiagnosis1) { obj.datTentativeDiagnosis1Date = new Func<VetCase, DateTime?>(c => c.idfsTentativeDiagnosis1.HasValue ? (c.datTentativeDiagnosis1Date.HasValue ? c.datTentativeDiagnosis1Date : DateTime.Today) : null)(obj); } if (e.PropertyName == _str_idfsTentativeDiagnosis2) { obj.datTentativeDiagnosis2Date = new Func<VetCase, DateTime?>(c => c.idfsTentativeDiagnosis2.HasValue ? (c.datTentativeDiagnosis2Date.HasValue ? c.datTentativeDiagnosis2Date : DateTime.Today) : null)(obj); } if (e.PropertyName == _str_idfsFinalDiagnosis) { obj.datFinalDiagnosisDate = new Func<VetCase, DateTime?>(c => c.idfsFinalDiagnosis.HasValue ? (c.datFinalDiagnosisDate.HasValue ? c.datFinalDiagnosisDate : DateTime.Today) : null)(obj); } if (e.PropertyName == _str_idfInvestigatedByOffice) { obj.PersonInvestigatedBy = (new SetScalarHandler()).Handler(obj, obj.idfInvestigatedByOffice, obj.idfInvestigatedByOffice_Previous, obj.PersonInvestigatedBy, (o, fld, prev_fld) => null); } if (e.PropertyName == _str_idfsTentativeDiagnosis) { obj.strTentativeDiagnosisOIECode = (obj.TentativeDiagnosis == null) ? "" : obj.TentativeDiagnosis.strOIECode; } if (e.PropertyName == _str_idfsTentativeDiagnosis1) { obj.strTentativeDiagnosis1OIECode = (obj.TentativeDiagnosis1 == null) ? "" : obj.TentativeDiagnosis1.strOIECode; } if (e.PropertyName == _str_idfsTentativeDiagnosis2) { obj.strTentativeDiagnosis2OIECode = (obj.TentativeDiagnosis2 == null) ? "" : obj.TentativeDiagnosis2.strOIECode; } if (e.PropertyName == _str_idfsFinalDiagnosis) { obj.strFinalDiagnosisOIECode = (obj.FinalDiagnosis == null) ? "" : obj.FinalDiagnosis.strOIECode; } if (e.PropertyName == _str_idfsDiagnosis) { if (obj.idfsDiagnosis.HasValue) { obj.SetNewFFTemplatesValues(); } } if (e.PropertyName == _str_idfInvestigatedByOffice) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) LoadLookup_PersonInvestigatedBy(manager, obj); } }; } public void LoadLookup_Site(DbManagerProxy manager, VetCase obj) { obj.SiteLookup.Clear(); obj.SiteLookup.Add(SiteAccessor.CreateNewT(manager, null)); obj.SiteLookup.AddRange(SiteAccessor.SelectLookupList(manager ) .Where(c => (c.intRowStatus == 0) || (c.idfsSite == obj.idfsSite)) .ToList()); if (obj.idfsSite != 0) { obj.Site = obj.SiteLookup .SingleOrDefault(c => c.idfsSite == obj.idfsSite); } LookupManager.AddObject("SiteLookup", obj, SiteAccessor.GetType(), "SelectLookupList"); } public void LoadLookup_CaseReportType(DbManagerProxy manager, VetCase obj) { obj.CaseReportTypeLookup.Clear(); obj.CaseReportTypeLookup.Add(CaseReportTypeAccessor.CreateNewT(manager, null)); obj.CaseReportTypeLookup.AddRange(CaseReportTypeAccessor.rftCaseReportType_SelectList(manager ) .Where(c => c.idfsBaseReference != (long)eidss.model.Enums.CaseReportType.Both) .Where(c => (c.intRowStatus == 0) || (c.idfsBaseReference == obj.idfsCaseReportType)) .ToList()); if (obj.idfsCaseReportType != null && obj.idfsCaseReportType != 0) { obj.CaseReportType = obj.CaseReportTypeLookup .SingleOrDefault(c => c.idfsBaseReference == obj.idfsCaseReportType); } LookupManager.AddObject("rftCaseReportType", obj, CaseReportTypeAccessor.GetType(), "rftCaseReportType_SelectList" , "SelectLookupList"); } public void LoadLookup_CaseType(DbManagerProxy manager, VetCase obj) { obj.CaseTypeLookup.Clear(); obj.CaseTypeLookup.Add(CaseTypeAccessor.CreateNewT(manager, null)); obj.CaseTypeLookup.AddRange(CaseTypeAccessor.rftCaseType_SelectList(manager ) .Where(c => (c.intRowStatus == 0) || (c.idfsBaseReference == obj.idfsCaseType)) .ToList()); if (obj.idfsCaseType != 0) { obj.CaseType = obj.CaseTypeLookup .SingleOrDefault(c => c.idfsBaseReference == obj.idfsCaseType); } LookupManager.AddObject("rftCaseType", obj, CaseTypeAccessor.GetType(), "rftCaseType_SelectList" , "SelectLookupList"); } public void LoadLookup_CaseClassification(DbManagerProxy manager, VetCase obj) { obj.CaseClassificationLookup.Clear(); obj.CaseClassificationLookup.Add(CaseClassificationAccessor.CreateNewT(manager, null)); obj.CaseClassificationLookup.AddRange(CaseClassificationAccessor.rftCaseClassification_SelectList(manager ) .Where(c => ((c.intHACode & (int)obj._HACode) != 0)) .Where(c => (c.intRowStatus == 0) || (c.idfsBaseReference == obj.idfsCaseClassification)) .ToList()); if (obj.idfsCaseClassification != null && obj.idfsCaseClassification != 0) { obj.CaseClassification = obj.CaseClassificationLookup .SingleOrDefault(c => c.idfsBaseReference == obj.idfsCaseClassification); } LookupManager.AddObject("rftCaseClassification", obj, CaseClassificationAccessor.GetType(), "rftCaseClassification_SelectList" , "SelectLookupList"); } public void LoadLookup_CaseProgressStatus(DbManagerProxy manager, VetCase obj) { obj.CaseProgressStatusLookup.Clear(); obj.CaseProgressStatusLookup.AddRange(CaseProgressStatusAccessor.rftCaseProgressStatus_SelectList(manager ) .Where(c => (c.intRowStatus == 0) || (c.idfsBaseReference == obj.idfsCaseProgressStatus)) .ToList()); if (obj.idfsCaseProgressStatus != null && obj.idfsCaseProgressStatus != 0) { obj.CaseProgressStatus = obj.CaseProgressStatusLookup .SingleOrDefault(c => c.idfsBaseReference == obj.idfsCaseProgressStatus); } LookupManager.AddObject("rftCaseProgressStatus", obj, CaseProgressStatusAccessor.GetType(), "rftCaseProgressStatus_SelectList" , "SelectLookupList"); } public void LoadLookup_TestsConducted(DbManagerProxy manager, VetCase obj) { obj.TestsConductedLookup.Clear(); obj.TestsConductedLookup.Add(TestsConductedAccessor.CreateNewT(manager, null)); obj.TestsConductedLookup.AddRange(TestsConductedAccessor.rftYesNoValue_SelectList(manager ) .Where(c => (c.intRowStatus == 0) || (c.idfsBaseReference == obj.idfsYNTestsConducted)) .ToList()); if (obj.idfsYNTestsConducted != null && obj.idfsYNTestsConducted != 0) { obj.TestsConducted = obj.TestsConductedLookup .SingleOrDefault(c => c.idfsBaseReference == obj.idfsYNTestsConducted); } LookupManager.AddObject("rftYesNoValue", obj, TestsConductedAccessor.GetType(), "rftYesNoValue_SelectList" , "SelectLookupList"); } public void LoadLookup_TentativeDiagnosis(DbManagerProxy manager, VetCase obj) { obj.TentativeDiagnosisLookup.Clear(); obj.TentativeDiagnosisLookup.Add(TentativeDiagnosisAccessor.CreateNewT(manager, null)); obj.TentativeDiagnosisLookup.AddRange(TentativeDiagnosisAccessor.SelectLookupList(manager ) .Where(c => ((c.intHACode & (int)obj._HACode) != 0) || c.idfsDiagnosis == obj.idfsTentativeDiagnosis) .Where(c => (c.idfsUsingType == (long)DiagnosisUsingTypeEnum.StandardCase) || c.idfsDiagnosis == obj.idfsTentativeDiagnosis) .Where(c => (c.intRowStatus == 0) || (c.idfsDiagnosis == obj.idfsTentativeDiagnosis)) .ToList()); if (obj.idfsTentativeDiagnosis != null && obj.idfsTentativeDiagnosis != 0) { obj.TentativeDiagnosis = obj.TentativeDiagnosisLookup .SingleOrDefault(c => c.idfsDiagnosis == obj.idfsTentativeDiagnosis); } LookupManager.AddObject("DiagnosisLookup", obj, TentativeDiagnosisAccessor.GetType(), "SelectLookupList"); } public void LoadLookup_TentativeDiagnosis1(DbManagerProxy manager, VetCase obj) { obj.TentativeDiagnosis1Lookup.Clear(); obj.TentativeDiagnosis1Lookup.Add(TentativeDiagnosis1Accessor.CreateNewT(manager, null)); obj.TentativeDiagnosis1Lookup.AddRange(TentativeDiagnosis1Accessor.SelectLookupList(manager ) .Where(c => ((c.intHACode & (int)obj._HACode) != 0) || c.idfsDiagnosis == obj.idfsTentativeDiagnosis1) .Where(c => (c.idfsUsingType == (long)DiagnosisUsingTypeEnum.StandardCase) || c.idfsDiagnosis == obj.idfsTentativeDiagnosis1) .Where(c => (c.intRowStatus == 0) || (c.idfsDiagnosis == obj.idfsTentativeDiagnosis1)) .ToList()); if (obj.idfsTentativeDiagnosis1 != null && obj.idfsTentativeDiagnosis1 != 0) { obj.TentativeDiagnosis1 = obj.TentativeDiagnosis1Lookup .SingleOrDefault(c => c.idfsDiagnosis == obj.idfsTentativeDiagnosis1); } LookupManager.AddObject("DiagnosisLookup", obj, TentativeDiagnosis1Accessor.GetType(), "SelectLookupList"); } public void LoadLookup_TentativeDiagnosis2(DbManagerProxy manager, VetCase obj) { obj.TentativeDiagnosis2Lookup.Clear(); obj.TentativeDiagnosis2Lookup.Add(TentativeDiagnosis2Accessor.CreateNewT(manager, null)); obj.TentativeDiagnosis2Lookup.AddRange(TentativeDiagnosis2Accessor.SelectLookupList(manager ) .Where(c => ((c.intHACode & (int)obj._HACode) != 0) || c.idfsDiagnosis == obj.idfsTentativeDiagnosis2) .Where(c => (c.idfsUsingType == (long)DiagnosisUsingTypeEnum.StandardCase) || c.idfsDiagnosis == obj.idfsTentativeDiagnosis2) .Where(c => (c.intRowStatus == 0) || (c.idfsDiagnosis == obj.idfsTentativeDiagnosis2)) .ToList()); if (obj.idfsTentativeDiagnosis2 != null && obj.idfsTentativeDiagnosis2 != 0) { obj.TentativeDiagnosis2 = obj.TentativeDiagnosis2Lookup .SingleOrDefault(c => c.idfsDiagnosis == obj.idfsTentativeDiagnosis2); } LookupManager.AddObject("DiagnosisLookup", obj, TentativeDiagnosis2Accessor.GetType(), "SelectLookupList"); } public void LoadLookup_FinalDiagnosis(DbManagerProxy manager, VetCase obj) { obj.FinalDiagnosisLookup.Clear(); obj.FinalDiagnosisLookup.Add(FinalDiagnosisAccessor.CreateNewT(manager, null)); obj.FinalDiagnosisLookup.AddRange(FinalDiagnosisAccessor.SelectLookupList(manager ) .Where(c => ((c.intHACode & (int)obj._HACode) != 0) || c.idfsDiagnosis == obj.idfsFinalDiagnosis) .Where(c => (c.idfsUsingType == (long)DiagnosisUsingTypeEnum.StandardCase) || c.idfsDiagnosis == obj.idfsFinalDiagnosis) .Where(c => (c.intRowStatus == 0) || (c.idfsDiagnosis == obj.idfsFinalDiagnosis)) .ToList()); if (obj.idfsFinalDiagnosis != null && obj.idfsFinalDiagnosis != 0) { obj.FinalDiagnosis = obj.FinalDiagnosisLookup .SingleOrDefault(c => c.idfsDiagnosis == obj.idfsFinalDiagnosis); } LookupManager.AddObject("DiagnosisLookup", obj, FinalDiagnosisAccessor.GetType(), "SelectLookupList"); } public void LoadLookup_ShowDiagnosis(DbManagerProxy manager, VetCase obj) { obj.ShowDiagnosisLookup.Clear(); obj.ShowDiagnosisLookup.Add(ShowDiagnosisAccessor.CreateNewT(manager, null)); obj.ShowDiagnosisLookup.AddRange(ShowDiagnosisAccessor.SelectLookupList(manager ) .Where(c => ((c.intHACode & (int)obj._HACode) != 0) || c.idfsDiagnosis == obj.idfsShowDiagnosis) .Where(c => (c.idfsUsingType == (long)DiagnosisUsingTypeEnum.StandardCase) || c.idfsDiagnosis == obj.idfsShowDiagnosis) .Where(c => (c.intRowStatus == 0) || (c.idfsDiagnosis == obj.idfsShowDiagnosis)) .ToList()); if (obj.idfsShowDiagnosis != null && obj.idfsShowDiagnosis != 0) { obj.ShowDiagnosis = obj.ShowDiagnosisLookup .SingleOrDefault(c => c.idfsDiagnosis == obj.idfsShowDiagnosis); } LookupManager.AddObject("DiagnosisLookup", obj, ShowDiagnosisAccessor.GetType(), "SelectLookupList"); } public void LoadLookup_PersonInvestigatedBy(DbManagerProxy manager, VetCase obj) { obj.PersonInvestigatedByLookup.Clear(); obj.PersonInvestigatedByLookup.Add(PersonInvestigatedByAccessor.CreateNewT(manager, null)); obj.PersonInvestigatedByLookup.AddRange(PersonInvestigatedByAccessor.SelectLookupList(manager , new Func<VetCase, long>(c => c.idfInvestigatedByOffice ?? 0)(obj) , null , false , null ) .Where(c => (c.intRowStatus == 0) || (c.idfPerson == obj.idfPersonInvestigatedBy)) .ToList()); if (obj.idfPersonInvestigatedBy != null && obj.idfPersonInvestigatedBy != 0) { obj.PersonInvestigatedBy = obj.PersonInvestigatedByLookup .SingleOrDefault(c => c.idfPerson == obj.idfPersonInvestigatedBy); } LookupManager.AddObject("WiderPersonLookup", obj, PersonInvestigatedByAccessor.GetType(), "SelectLookupList"); } private void _LoadLookups(DbManagerProxy manager, VetCase obj) { LoadLookup_Site(manager, obj); LoadLookup_CaseReportType(manager, obj); LoadLookup_CaseType(manager, obj); LoadLookup_CaseClassification(manager, obj); LoadLookup_CaseProgressStatus(manager, obj); LoadLookup_TestsConducted(manager, obj); LoadLookup_TentativeDiagnosis(manager, obj); LoadLookup_TentativeDiagnosis1(manager, obj); LoadLookup_TentativeDiagnosis2(manager, obj); LoadLookup_FinalDiagnosis(manager, obj); LoadLookup_ShowDiagnosis(manager, obj); LoadLookup_PersonInvestigatedBy(manager, obj); } [SprocName("spVetCase_CanDelete")] protected abstract void _canDelete(DbManagerProxy manager, Int64? ID, out Boolean Result ); [SprocName("spVetCase_Delete")] protected abstract void _postDelete(DbManagerProxy manager , Int64? ID ); protected void _postDeletePredicate(DbManagerProxy manager , Int64? ID ) { _postDelete(manager, ID); } public bool DeleteObject(DbManagerProxy manager, object ident) { IObject obj = SelectDetail(manager, ident); if (!obj.MarkToDelete()) return false; return Post(manager, obj); } [SprocName("spVetCase_Post")] protected abstract void _post(DbManagerProxy manager, [Direction.InputOutput()] VetCase obj); protected void _postPredicate(DbManagerProxy manager, [Direction.InputOutput()] VetCase obj) { _post(manager, obj); } public bool Post(DbManagerProxy manager, IObject obj, bool bChildObject = false) { bool bTransactionStarted = false; bool bSuccess; try { VetCase bo = obj as VetCase; if (!bo.IsNew && bo.IsMarkedToDelete) // delete { if (!bo.GetPermissions().CanDelete) throw new PermissionException("VetCase", "Delete"); } else if (bo.IsNew && !bo.IsMarkedToDelete) // insert { if (!bo.GetPermissions().CanInsert) throw new PermissionException("VetCase", "Insert"); } else if (!bo.IsMarkedToDelete) // update { if (!bo.GetPermissions().CanUpdate) throw new PermissionException("VetCase", "Update"); } long mainObject = bo.idfCase; if (!bo.IsNew && bo.IsMarkedToDelete) // delete { } else if (bo.IsNew && !bo.IsMarkedToDelete) // insert { manager.SetEventParams(false, new object[] { EventType.VetCaseCreatedLocal, mainObject, "" }); } else if (!bo.IsMarkedToDelete) // update { if ( bo.idfsFinalDiagnosis != bo.idfsFinalDiagnosis_Original || bo.idfsTentativeDiagnosis2 != bo.idfsTentativeDiagnosis2_Original || bo.idfsTentativeDiagnosis1 != bo.idfsTentativeDiagnosis1_Original || bo.idfsTentativeDiagnosis != bo.idfsTentativeDiagnosis_Original ) manager.SetEventParams(false, new object[] { EventType.VetCaseDiagnosisChangedLocal, mainObject, "" }); if ( bo.idfsCaseClassification != bo.idfsCaseClassification_Original ) manager.SetEventParams(false, new object[] { EventType.VetCaseClassificationChangedLocal, mainObject, "" }); if (new Func<VetCase, bool>(c => c.idfsCaseProgressStatus == (long)CaseStatusEnum.InProgress && c.idfsCaseProgressStatus_Original == (long)CaseStatusEnum.Closed)(bo)) manager.SetEventParams(false, new object[] { EventType.ClosedVetCaseReopenedLocal, mainObject, "" }); if (new Func<VetCase, bool>(c => c.PensideTests.Count(i => i.IsNew && !i.IsMarkedToDelete) > 0)(bo)) manager.SetEventParams(false, new object[] { EventType.VetCaseFieldTestResultRegistrationLocal, mainObject, "" }); if (new Func<VetCase, bool>(c => c.CaseTests.Count(i => i.IsNew && !i.IsMarkedToDelete) > 0)(bo)) manager.SetEventParams(false, new object[] { EventType.VetCaseTestResultRegistrationLocal, mainObject, "" }); } if (!manager.IsTransactionStarted) { eidss.model.Enums.AuditEventType auditEventType = eidss.model.Enums.AuditEventType.daeFreeDataUpdate; if (!bo.IsNew && bo.IsMarkedToDelete) // delete { auditEventType = eidss.model.Enums.AuditEventType.daeDelete; } else if (bo.IsNew && !bo.IsMarkedToDelete) // insert { auditEventType = eidss.model.Enums.AuditEventType.daeCreate; } else if (!bo.IsMarkedToDelete) // update { auditEventType = eidss.model.Enums.AuditEventType.daeEdit; } eidss.model.Enums.EIDSSAuditObject objectType = eidss.model.Enums.EIDSSAuditObject.daoVetCase; eidss.model.Enums.AuditTable auditTable = eidss.model.Enums.AuditTable.tlbVetCase; manager.AuditParams = new object[] { auditEventType, objectType, auditTable, mainObject }; bTransactionStarted = true; manager.BeginTransaction(); } bSuccess = _PostNonTransaction(manager, obj as VetCase, bChildObject); if (bTransactionStarted) { if (bSuccess) { obj.DeepAcceptChanges(); manager.CommitTransaction(); } else { manager.RollbackTransaction(); } } if (bSuccess && bo.IsNew && !bo.IsMarkedToDelete) // insert { bo.m_IsNew = false; } if (bSuccess && bTransactionStarted) { bo.OnAfterPost(); } } catch(Exception e) { if (bTransactionStarted) { manager.RollbackTransaction(); } if (e is DataException) { throw DbModelException.Create(e as DataException); } else throw; } return bSuccess; } private bool _PostNonTransaction(DbManagerProxy manager, VetCase obj, bool bChildObject) { bool bHasChanges = obj.HasChanges; if (!obj.IsNew && obj.IsMarkedToDelete) // delete { if (obj.FFPresenterControlMeasures != null) { obj.FFPresenterControlMeasures.MarkToDelete(); if (!FFPresenterControlMeasuresAccessor.Post(manager, obj.FFPresenterControlMeasures, true)) return false; } if (obj.Logs != null) { foreach (var i in obj.Logs) { i.MarkToDelete(); if (!LogsAccessor.Post(manager, i, true)) return false; } } if (obj.CaseTests != null) { foreach (var i in obj.CaseTests) { i.MarkToDelete(); if (!CaseTestsAccessor.Post(manager, i, true)) return false; } } if (!ValidateCanDelete(manager, obj)) return false; _postDeletePredicate(manager , obj.idfCase ); } else if (!obj.IsMarkedToDelete) // insert/update { if (!bChildObject) if (!Validate(manager, obj, true, true, true)) return false; // posting extenters - begin obj.datModificationForArchiveDate = new Func<VetCase, DateTime?>(c => c.HasChanges ? DateTime.Now : c.datModificationForArchiveDate)(obj); obj.strCaseID = new Func<VetCase, DbManagerProxy, string>((c,m) => c.strCaseID != "(new)" ? c.strCaseID : m.SetSpCommand("dbo.spGetNextNumber", (long)NumberingObjectEnum.VetCase, DBNull.Value, DBNull.Value) .ExecuteScalar<string>(ScalarSourceType.OutputParameter, "NextNumberValue"))(obj, manager); obj.idfsShowDiagnosis = new Func<VetCase, long?>(c=>c.idfsDiagnosis)(obj); // posting extenters - end if (obj.IsNew) { if (obj.Farm != null) // forced load potential lazy subobject for new object if (!FarmAccessor.Post(manager, obj.Farm, true)) return false; } else { if (obj._Farm != null) // do not load lazy subobject for existing object if (!FarmAccessor.Post(manager, obj.Farm, true)) return false; } if (!obj.IsMarkedToDelete && bHasChanges) _postPredicate(manager, obj); if (obj.IsNew) { if (obj.Vaccination != null) // forced load potential lazy subobject for new object { foreach (var i in obj.Vaccination) if (!VaccinationAccessor.Post(manager, i, true)) return false; obj.Vaccination.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj.Vaccination.Remove(c)); obj.Vaccination.AcceptChanges(); } } else { if (obj._Vaccination != null) // do not load lazy subobject for existing object { foreach (var i in obj._Vaccination) if (!VaccinationAccessor.Post(manager, i, true)) return false; obj._Vaccination.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj._Vaccination.Remove(c)); obj._Vaccination.AcceptChanges(); } } if (obj.IsNew) { if (obj.AnimalList != null) // forced load potential lazy subobject for new object { foreach (var i in obj.AnimalList) if (!AnimalListAccessor.Post(manager, i, true)) return false; obj.AnimalList.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj.AnimalList.Remove(c)); obj.AnimalList.AcceptChanges(); } } else { if (obj._AnimalList != null) // do not load lazy subobject for existing object { foreach (var i in obj._AnimalList) if (!AnimalListAccessor.Post(manager, i, true)) return false; obj._AnimalList.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj._AnimalList.Remove(c)); obj._AnimalList.AcceptChanges(); } } if (obj.IsNew) { if (obj.Samples != null) // forced load potential lazy subobject for new object { foreach (var i in obj.Samples) if (!SamplesAccessor.Post(manager, i, true)) return false; obj.Samples.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj.Samples.Remove(c)); obj.Samples.AcceptChanges(); } } else { if (obj._Samples != null) // do not load lazy subobject for existing object { foreach (var i in obj._Samples) if (!SamplesAccessor.Post(manager, i, true)) return false; obj._Samples.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj._Samples.Remove(c)); obj._Samples.AcceptChanges(); } } if (obj.IsNew) { if (obj.CaseTests != null) // forced load potential lazy subobject for new object { foreach (var i in obj.CaseTests) if (!CaseTestsAccessor.Post(manager, i, true)) return false; obj.CaseTests.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj.CaseTests.Remove(c)); obj.CaseTests.AcceptChanges(); } } else { if (obj._CaseTests != null) // do not load lazy subobject for existing object { foreach (var i in obj._CaseTests) if (!CaseTestsAccessor.Post(manager, i, true)) return false; obj._CaseTests.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj._CaseTests.Remove(c)); obj._CaseTests.AcceptChanges(); } } if (obj.IsNew) { if (obj.PensideTests != null) // forced load potential lazy subobject for new object { foreach (var i in obj.PensideTests) if (!PensideTestsAccessor.Post(manager, i, true)) return false; obj.PensideTests.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj.PensideTests.Remove(c)); obj.PensideTests.AcceptChanges(); } } else { if (obj._PensideTests != null) // do not load lazy subobject for existing object { foreach (var i in obj._PensideTests) if (!PensideTestsAccessor.Post(manager, i, true)) return false; obj._PensideTests.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj._PensideTests.Remove(c)); obj._PensideTests.AcceptChanges(); } } if (obj.IsNew) { if (obj.CaseTestValidations != null) // forced load potential lazy subobject for new object { foreach (var i in obj.CaseTestValidations) if (!CaseTestValidationsAccessor.Post(manager, i, true)) return false; obj.CaseTestValidations.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj.CaseTestValidations.Remove(c)); obj.CaseTestValidations.AcceptChanges(); } } else { if (obj._CaseTestValidations != null) // do not load lazy subobject for existing object { foreach (var i in obj._CaseTestValidations) if (!CaseTestValidationsAccessor.Post(manager, i, true)) return false; obj._CaseTestValidations.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj._CaseTestValidations.Remove(c)); obj._CaseTestValidations.AcceptChanges(); } } if (obj.IsNew) { if (obj.Logs != null) // forced load potential lazy subobject for new object { foreach (var i in obj.Logs) if (!LogsAccessor.Post(manager, i, true)) return false; obj.Logs.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj.Logs.Remove(c)); obj.Logs.AcceptChanges(); } } else { if (obj._Logs != null) // do not load lazy subobject for existing object { foreach (var i in obj._Logs) if (!LogsAccessor.Post(manager, i, true)) return false; obj._Logs.Where(c => c.IsMarkedToDelete).ToList().ForEach(c => obj._Logs.Remove(c)); obj._Logs.AcceptChanges(); } } if (obj.IsNew) { if (obj.FFPresenterControlMeasures != null) // forced load potential lazy subobject for new object if (!FFPresenterControlMeasuresAccessor.Post(manager, obj.FFPresenterControlMeasures, true)) return false; } else { if (obj._FFPresenterControlMeasures != null) // do not load lazy subobject for existing object if (!FFPresenterControlMeasuresAccessor.Post(manager, obj.FFPresenterControlMeasures, true)) return false; } // posted extenters - begin if (obj.AnimalList.Count() > 0) { obj.AnimalList.ForEach(animal => animal.CopyMainProperties(obj.Farm.FarmTree.Single(species=>species.idfParty == animal.idfSpecies))); } // posted extenters - end } //obj.AcceptChanges(); obj.OnPropertyChanged(_str_IsClosed); obj.OnPropertyChanged(_str_IsEnabledCaseProgressStatus); return true; } public bool ValidateCanDelete(VetCase obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { return ValidateCanDelete(manager, obj); } } public bool ValidateCanDelete(DbManagerProxy manager, VetCase obj) { try { if (!obj.IsForcedToDelete) { bool result = false; _canDelete(manager , obj.idfCase , out result ); if (!result) { throw new ValidationModelException("msgCantDelete", "_on_delete", "_on_delete", null, null, false, obj); } } } catch(ValidationModelException ex) { if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } else obj.m_IsForcedToDelete = true; } return true; } protected ValidationModelException ChainsValidate(VetCase obj) { try { new ChainsValidatorDateTime<VetCase>(obj, "datInvestigationDate", c => true, obj.datInvestigationDate, obj.GetType(), false, listdatInvestigationDate => { listdatInvestigationDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "CurrentDate", c => true, DateTime.Now, null, false, listCurrentDate => { })); }).Process(); new ChainsValidatorDateTime<VetCase>(obj, "datReportDate", c => true, obj.datReportDate, obj.GetType(), false, listdatReportDate => { listdatReportDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "datInvestigationDate", c => true, obj.datInvestigationDate, obj.GetType(), false, listdatInvestigationDate => { obj.CaseTestValidations.Where(c => !c.IsMarkedToDelete).ToList().ForEach(j =>listdatInvestigationDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "datInterpretationDate", c => true, j.datInterpretationDate, j.GetType(), false, listdatInterpretationDate => { listdatInterpretationDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "CurrentDate", c => true, DateTime.Now, null, false, listCurrentDate => { })); }))); obj.CaseTestValidations.Where(c => !c.IsMarkedToDelete).ToList().ForEach(j =>listdatInvestigationDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "datValidationDate", c => true, j.datValidationDate, j.GetType(), false, listdatValidationDate => { listdatValidationDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "CurrentDate", c => true, DateTime.Now, null, false, listCurrentDate => { })); }))); })); listdatReportDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "datAssignedDate", c => true, obj.datAssignedDate, obj.GetType(), false, listdatAssignedDate => { listdatAssignedDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "datTentativeDiagnosisDate", c => true, obj.datTentativeDiagnosisDate, obj.GetType(), false, listdatTentativeDiagnosisDate => { listdatTentativeDiagnosisDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "datTentativeDiagnosis1Date", c => true, obj.datTentativeDiagnosis1Date, obj.GetType(), false, listdatTentativeDiagnosis1Date => { listdatTentativeDiagnosis1Date.Add( new ChainsValidatorDateTime<VetCase>(obj, "datTentativeDiagnosis2Date", c => true, obj.datTentativeDiagnosis2Date, obj.GetType(), false, listdatTentativeDiagnosis2Date => { listdatTentativeDiagnosis2Date.Add( new ChainsValidatorDateTime<VetCase>(obj, "CurrentDate", c => true, DateTime.Now, null, false, listCurrentDate => { })); })); })); })); })); obj.Samples.Where(c => !c.IsMarkedToDelete).ToList().ForEach(j =>listdatReportDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "datFieldCollectionDate", c => true, j.datFieldCollectionDate, j.GetType(), false, listdatFieldCollectionDate => { listdatFieldCollectionDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "CurrentDate", c => true, DateTime.Now, null, false, listCurrentDate => { })); }))); }).Process(); new ChainsValidatorDateTime<VetCase>(obj, "datFinalDiagnosisDate", c => true, obj.datFinalDiagnosisDate, obj.GetType(), false, listdatFinalDiagnosisDate => { listdatFinalDiagnosisDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "CurrentDate", c => true, DateTime.Now, null, false, listCurrentDate => { })); }).Process(); obj.CaseTests.Where(c => !c.IsMarkedToDelete).ToList().ForEach(j => new ChainsValidatorDateTime<VetCase>(obj, "datConcludedDate", c => true, j.datConcludedDate, j.GetType(), false, listdatConcludedDate => { listdatConcludedDate.Add( new ChainsValidatorDateTime<VetCase>(obj, "CurrentDate", c => true, DateTime.Now, null, false, listCurrentDate => { })); }).Process()); } catch(ValidationModelException ex) { return ex; } return null; } protected bool ChainsValidate(VetCase obj, bool bRethrowException) { ValidationModelException ex = ChainsValidate(obj); if (ex != null) { if (bRethrowException) throw ex; if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } } return true; } public bool Validate(DbManagerProxy manager, IObject obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { return Validate(manager, obj as VetCase, bPostValidation, bChangeValidation, bDeepValidation, bRethrowException); } public bool Validate(DbManagerProxy manager, VetCase obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { if (!ChainsValidate(obj, bRethrowException)) return false; try { if (bPostValidation) { (new RequiredValidator( "Farm.Address.idfsCountry", "Farm.Address.Country","", false )).Validate(c => true, obj, obj.Farm.Address.idfsCountry); (new RequiredValidator( "Farm.Address.idfsRegion", "Farm.Address.Region","", false )).Validate(c => true, obj, obj.Farm.Address.idfsRegion); (new RequiredValidator( "Farm.Address.idfsRayon", "Farm.Address.Rayon","", false )).Validate(c => true, obj, obj.Farm.Address.idfsRayon); (new RequiredValidator( "idfsCaseReportType", "CaseReportType","", false )).Validate(c => true, obj, obj.idfsCaseReportType); (new RequiredValidator( "idfsCaseProgressStatus", "CaseProgressStatus","", false )).Validate(c => true, obj, obj.idfsCaseProgressStatus); (new CustomMandatoryFieldValidator("CaseClassification", "CaseClassification", "idfsCaseClassification", false )).Validate(obj, obj.CaseClassification, CustomMandatoryField.VetCase_CaseClassification, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("Farm.Address.Settlement", "Farm.Address.Settlement", "", false )).Validate(obj, obj.Farm.Address.Settlement, CustomMandatoryField.VetCase_Farm_Address_Settlement, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("TentativeDiagnosis", "TentativeDiagnosis", "", false )).Validate(obj, obj.TentativeDiagnosis, CustomMandatoryField.VetCase_TentativeDiagnosis, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("TentativeDiagnosis1", "TentativeDiagnosis1", "", false )).Validate(obj, obj.TentativeDiagnosis1, CustomMandatoryField.VetCase_Tentative1Diagnosis, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("TentativeDiagnosis2", "TentativeDiagnosis2", "", false )).Validate(obj, obj.TentativeDiagnosis2, CustomMandatoryField.VetCase_Tentative2Diagnosis, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("FinalDiagnosis", "FinalDiagnosis", "", false )).Validate(obj, obj.FinalDiagnosis, CustomMandatoryField.VetCase_FinalDiagnosis, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("datTentativeDiagnosisDate", "datTentativeDiagnosisDate", "", false )).Validate(obj, obj.datTentativeDiagnosisDate, CustomMandatoryField.VetCase_TentativeDiagnosisDate, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("datTentativeDiagnosis1Date", "datTentativeDiagnosis1Date", "", false )).Validate(obj, obj.datTentativeDiagnosis1Date, CustomMandatoryField.VetCase_TentativeDiagnosis1Date, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("datTentativeDiagnosis2Date", "datTentativeDiagnosis2Date", "", false )).Validate(obj, obj.datTentativeDiagnosis2Date, CustomMandatoryField.VetCase_TentativeDiagnosis2Date, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("datFinalDiagnosisDate", "datFinalDiagnosisDate", "", false )).Validate(obj, obj.datFinalDiagnosisDate, CustomMandatoryField.VetCase_FinalDiagnosisDate, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("Farm.strOwnerLastName", "Farm.strOwnerLastName", "", false )).Validate(obj, obj.Farm.strOwnerLastName, CustomMandatoryField.VetCase_Farm_FarmOwnerLastName, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("Farm.strOwnerFirstName", "Farm.strOwnerFirstName", "", false )).Validate(obj, obj.Farm.strOwnerFirstName, CustomMandatoryField.VetCase_Farm_FarmOwnerFirstName, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("Farm.strNationalName", "Farm.strNationalName", "", false )).Validate(obj, obj.Farm.strNationalName, CustomMandatoryField.VetCase_Farm_FarmName, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("idfReportedByOffice", "idfReportedByOffice", "", false )).Validate(obj, obj.idfReportedByOffice, CustomMandatoryField.VetCase_ReportedByOffice, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); (new CustomMandatoryFieldValidator("idfPersonReportedBy", "idfPersonReportedBy", "", false )).Validate(obj, obj.idfPersonReportedBy, CustomMandatoryField.VetCase_PersonReportedBy, c => !eidss.model.Core.EidssUserContext.SmartphoneContext); CustomValidations(obj); } if (bChangeValidation) { CheckOutbreak(obj); } if (bDeepValidation) { if (obj.Farm != null) FarmAccessor.Validate(manager, obj.Farm, bPostValidation, bChangeValidation, bDeepValidation, true); if (obj.Vaccination != null) foreach (var i in obj.Vaccination.Where(c => !c.IsMarkedToDelete && c.HasChanges)) VaccinationAccessor.Validate(manager, i, bPostValidation, bChangeValidation, bDeepValidation, true); if (obj.AnimalList != null) foreach (var i in obj.AnimalList.Where(c => !c.IsMarkedToDelete && c.HasChanges)) AnimalListAccessor.Validate(manager, i, bPostValidation, bChangeValidation, bDeepValidation, true); if (obj.Samples != null) foreach (var i in obj.Samples.Where(c => !c.IsMarkedToDelete && c.HasChanges)) SamplesAccessor.Validate(manager, i, bPostValidation, bChangeValidation, bDeepValidation, true); if (obj.CaseTests != null) foreach (var i in obj.CaseTests.Where(c => !c.IsMarkedToDelete && c.HasChanges)) CaseTestsAccessor.Validate(manager, i, bPostValidation, bChangeValidation, bDeepValidation, true); if (obj.PensideTests != null) foreach (var i in obj.PensideTests.Where(c => !c.IsMarkedToDelete && c.HasChanges)) PensideTestsAccessor.Validate(manager, i, bPostValidation, bChangeValidation, bDeepValidation, true); if (obj.CaseTestValidations != null) foreach (var i in obj.CaseTestValidations.Where(c => !c.IsMarkedToDelete && c.HasChanges)) CaseTestValidationsAccessor.Validate(manager, i, bPostValidation, bChangeValidation, bDeepValidation, true); if (obj.Logs != null) foreach (var i in obj.Logs.Where(c => !c.IsMarkedToDelete && c.HasChanges)) LogsAccessor.Validate(manager, i, bPostValidation, bChangeValidation, bDeepValidation, true); if (obj.FFPresenterControlMeasures != null) FFPresenterControlMeasuresAccessor.Validate(manager, obj.FFPresenterControlMeasures, bPostValidation, bChangeValidation, bDeepValidation, true); } } catch(ValidationModelException ex) { if (bRethrowException) throw; if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } } return true; } #region IObjectPermissions public bool CanSelect { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("VetCase.Select"); } } public bool CanUpdate { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("VetCase.Update"); } } public bool CanDelete { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("VetCase.Delete"); } } public bool CanInsert { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("VetCase.Insert"); } } public bool CanExecute(string permission) { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo(permission.Contains(".") ? permission : permission + ".Execute"); } public bool IsReadOnlyForEdit { get { return !CanUpdate; } } #endregion private void _SetupRequired(VetCase obj) { obj .Farm .Address .AddRequired("Country", c => true); obj .Farm .Address .AddRequired("Region", c => true); obj .Farm .Address .AddRequired("Rayon", c => true); obj .AddRequired("CaseReportType", c => true); obj .AddRequired("CaseReportType", c => true); obj .AddRequired("CaseProgressStatus", c => true); obj .AddRequired("CaseProgressStatus", c => true); if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_CaseClassification) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("CaseClassification", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_Farm_Address_Settlement) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .Farm .Address .AddRequired("Settlement", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_TentativeDiagnosis) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("TentativeDiagnosis", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_Tentative1Diagnosis) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("TentativeDiagnosis1", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_Tentative2Diagnosis) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("TentativeDiagnosis2", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_FinalDiagnosis) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("FinalDiagnosis", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_TentativeDiagnosisDate) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("datTentativeDiagnosisDate", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_TentativeDiagnosis1Date) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("datTentativeDiagnosis1Date", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_TentativeDiagnosis2Date) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("datTentativeDiagnosis2Date", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_FinalDiagnosisDate) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("datFinalDiagnosisDate", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_Farm_FarmOwnerLastName) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .Farm .AddRequired("strOwnerLastName", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_Farm_FarmOwnerFirstName) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .Farm .AddRequired("strOwnerFirstName", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_Farm_FarmName) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .Farm .AddRequired("strNationalName", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_ReportedByOffice) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("idfReportedByOffice", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } if (EidssSiteContext.Instance.CustomMandatoryFields.Contains(CustomMandatoryField.VetCase_PersonReportedBy) && new Func<VetCase, bool>(c => !eidss.model.Core.EidssUserContext.SmartphoneContext)(obj)) { obj .AddRequired("idfPersonReportedBy", c => !eidss.model.Core.EidssUserContext.SmartphoneContext); } } private void _SetupPersonalDataRestrictions(VetCase obj) { if (EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)) { obj .AddHiddenPersonalData("Vet_Farm", c=>true); obj .Farm .AddHiddenPersonalData("strOwnerLastName", c=>true); obj .Farm .AddHiddenPersonalData("strOwnerFirstName", c=>true); obj .Farm .AddHiddenPersonalData("strOwnerMiddleName", c=>true); obj .Farm .AddHiddenPersonalData("strFarmCode", c=>true); obj .Farm .AddHiddenPersonalData("strNationalName", c=>true); obj .Farm .Address .AddHiddenPersonalData("Settlement", c=>true); obj .Farm .Address .AddHiddenPersonalData("idfsSettlement", c=>true); obj .Farm .Address .AddHiddenPersonalData("PostCode", c=>true); obj .Farm .Address .AddHiddenPersonalData("Street", c=>true); obj .Farm .Address .AddHiddenPersonalData("strPostCode", c=>true); obj .Farm .Address .AddHiddenPersonalData("strStreetName", c=>true); obj .Farm .Address .AddHiddenPersonalData("strApartment", c=>true); obj .Farm .Address .AddHiddenPersonalData("strHouse", c=>true); obj .Farm .Address .AddHiddenPersonalData("strBuilding", c=>true); obj .Farm .AddHiddenPersonalData("strFax", c=>true); obj .Farm .AddHiddenPersonalData("strEmail", c=>true); obj .Farm .AddHiddenPersonalData("strContactPhone", c=>true); } if (EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)) { obj .AddHiddenPersonalData("Vet_Farm", c=>true); obj .Farm .AddHiddenPersonalData("strOwnerLastName", c=>true); obj .Farm .AddHiddenPersonalData("strOwnerFirstName", c=>true); obj .Farm .AddHiddenPersonalData("strOwnerMiddleName", c=>true); obj .Farm .AddHiddenPersonalData("strFarmCode", c=>true); obj .Farm .AddHiddenPersonalData("strNationalName", c=>true); obj .Farm .Address .AddHiddenPersonalData("PostCode", c=>true); obj .Farm .Address .AddHiddenPersonalData("Street", c=>true); obj .Farm .Address .AddHiddenPersonalData("strPostCode", c=>true); obj .Farm .Address .AddHiddenPersonalData("strStreetName", c=>true); obj .Farm .Address .AddHiddenPersonalData("strApartment", c=>true); obj .Farm .Address .AddHiddenPersonalData("strHouse", c=>true); obj .Farm .Address .AddHiddenPersonalData("strBuilding", c=>true); obj .Farm .AddHiddenPersonalData("strFax", c=>true); obj .Farm .AddHiddenPersonalData("strEmail", c=>true); obj .Farm .AddHiddenPersonalData("strContactPhone", c=>true); } if (EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Coordinates)) { obj .Farm .Address .AddHiddenPersonalData("dblLatitude", c=>true); obj .Farm .Address .AddHiddenPersonalData("dblLongitude", c=>true); } } #region IObjectMeta public int? MaxSize(string name) { return Meta.Sizes.ContainsKey(name) ? (int?)Meta.Sizes[name] : null; } public bool RequiredByField(string name, IObject obj) { return Meta.RequiredByField.ContainsKey(name) ? Meta.RequiredByField[name](obj as VetCase) : false; } public bool RequiredByProperty(string name, IObject obj) { return Meta.RequiredByProperty.ContainsKey(name) ? Meta.RequiredByProperty[name](obj as VetCase) : false; } public List<SearchPanelMetaItem> SearchPanelMeta { get { return Meta.SearchPanelMeta; } } public List<GridMetaItem> GridMeta { get { return Meta.GridMeta; } } public List<ActionMetaItem> Actions { get { return Meta.Actions; } } public string DetailPanel { get { return "VetCaseDetail"; } } public string HelpIdWin { get { return ""; } } public string HelpIdWeb { get { return "web_vetcaselivestockdetailform"; } } public string HelpIdHh { get { return ""; } } #endregion } #region IObjectPermissions internal class Permissions : IObjectPermissions { private VetCase m_obj; internal Permissions(VetCase obj) { m_obj = obj; } public bool CanSelect { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("VetCase.Select"); } } public bool CanUpdate { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("VetCase.Update"); } } public bool CanDelete { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("VetCase.Delete"); } } public bool CanInsert { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("VetCase.Insert"); } } public bool CanExecute(string permission) { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo(permission.Contains(".") ? permission : permission + ".Execute"); } public bool IsReadOnlyForEdit { get { return !(CanUpdate || (CanInsert && m_obj.IsNew)); } } } #endregion #region Meta public static class Meta { public static string spSelect = "spVetCase_SelectDetail"; public static string spCount = ""; public static string spPost = "spVetCase_Post"; public static string spInsert = ""; public static string spUpdate = ""; public static string spDelete = "spVetCase_Delete"; public static string spCanDelete = "spVetCase_CanDelete"; public static Dictionary<string, int> Sizes = new Dictionary<string, int>(); public static Dictionary<string, Func<VetCase, bool>> RequiredByField = new Dictionary<string, Func<VetCase, bool>>(); public static Dictionary<string, Func<VetCase, bool>> RequiredByProperty = new Dictionary<string, Func<VetCase, bool>>(); public static List<SearchPanelMetaItem> SearchPanelMeta = new List<SearchPanelMetaItem>(); public static List<GridMetaItem> GridMeta = new List<GridMetaItem>(); public static List<ActionMetaItem> Actions = new List<ActionMetaItem>(); private static Dictionary<string, List<Func<bool>>> m_isHiddenPersonalData = new Dictionary<string, List<Func<bool>>>(); internal static bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name].Aggregate(false, (s,c) => s | c()); return false; } private static void AddHiddenPersonalData(string name, Func<bool> func) { if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, new List<Func<bool>>()); m_isHiddenPersonalData[name].Add(func); } static Meta() { Sizes.Add(_str_strOutbreakID, 200); Sizes.Add(_str_strMonitoringSessionID, 50); Sizes.Add(_str_strCaseID, 200); Sizes.Add(_str_strInvestigatedByOffice, 2000); Sizes.Add(_str_strPersonInvestigatedBy, 602); Sizes.Add(_str_strPersonEnteredByName, 602); Sizes.Add(_str_strReportedByOffice, 2000); Sizes.Add(_str_strPersonReportedBy, 602); Sizes.Add(_str_strSampleNotes, 1000); Sizes.Add(_str_strTestNotes, 1000); Sizes.Add(_str_strSummaryNotes, 1000); Sizes.Add(_str_strClinicalNotes, 1000); Sizes.Add(_str_strFieldAccessionID, 200); Sizes.Add(_str_strFinalDiagnosisOIECode, 200); Sizes.Add(_str_strTentativeDiagnosisOIECode, 200); Sizes.Add(_str_strTentativeDiagnosis1OIECode, 200); Sizes.Add(_str_strTentativeDiagnosis2OIECode, 200); if (!RequiredByField.ContainsKey("Farm.Address.idfsCountry")) RequiredByField.Add("Farm.Address.idfsCountry", c => true); if (!RequiredByProperty.ContainsKey("Farm.Address.Country")) RequiredByProperty.Add("Farm.Address.Country", c => true); if (!RequiredByField.ContainsKey("Farm.Address.idfsRegion")) RequiredByField.Add("Farm.Address.idfsRegion", c => true); if (!RequiredByProperty.ContainsKey("Farm.Address.Region")) RequiredByProperty.Add("Farm.Address.Region", c => true); if (!RequiredByField.ContainsKey("Farm.Address.idfsRayon")) RequiredByField.Add("Farm.Address.idfsRayon", c => true); if (!RequiredByProperty.ContainsKey("Farm.Address.Rayon")) RequiredByProperty.Add("Farm.Address.Rayon", c => true); if (!RequiredByField.ContainsKey("idfsCaseReportType")) RequiredByField.Add("idfsCaseReportType", c => true); if (!RequiredByProperty.ContainsKey("CaseReportType")) RequiredByProperty.Add("CaseReportType", c => true); if (!RequiredByField.ContainsKey("idfsCaseProgressStatus")) RequiredByField.Add("idfsCaseProgressStatus", c => true); if (!RequiredByProperty.ContainsKey("CaseProgressStatus")) RequiredByProperty.Add("CaseProgressStatus", c => true); Actions.Add(new ActionMetaItem( "VetInvestigationReport", ActionTypes.Action, true, "", "", (manager, c, pars) => Accessor.Instance(null).VetInvestigationReport(manager, (VetCase)c, pars), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"titleVetCaseInvestigationReport", "Report", /*from BvMessages*/"", /*from BvMessages*/"", "", /*from BvMessages*/"", ActionsAlignment.Left, ActionsPanelType.Main, ActionsAppType.All ), true, null, null, null, null, null, false, false, null, false, new ActionMetaItem[] { } )); Actions.Add(new ActionMetaItem( "Save", ActionTypes.Save, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(ObjectAccessor.PostInterface<VetCase>().Post(manager, (VetCase)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strSave_Id", "Save", /*from BvMessages*/"tooltipSave_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipSave_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Ok", ActionTypes.Ok, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(ObjectAccessor.PostInterface<VetCase>().Post(manager, (VetCase)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipOK_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipOK_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Cancel", ActionTypes.Cancel, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strCancel_Id", "", /*from BvMessages*/"tooltipCancel_Id", /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipCancel_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Delete", ActionTypes.Delete, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(((VetCase)c).MarkToDelete() && ObjectAccessor.PostInterface<VetCase>().Post(manager, (VetCase)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strDelete_Id", "Delete_Remove", /*from BvMessages*/"tooltipDelete_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipDelete_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, (o, p, r) => r && !o.IsNew && !o.HasChanges, null, null, false )); _SetupPersonalDataRestrictions(); } private static void _SetupPersonalDataRestrictions() { AddHiddenPersonalData("Vet_Farm", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.strOwnerLastName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.strOwnerFirstName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.strOwnerMiddleName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.strFarmCode", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.strNationalName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.Settlement", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.idfsSettlement", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.PostCode", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.Street", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.strPostCode", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.strStreetName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.strApartment", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.strHouse", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.Address.strBuilding", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.strFax", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.strEmail", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Farm.strContactPhone", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Settlement)); AddHiddenPersonalData("Vet_Farm", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.strOwnerLastName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.strOwnerFirstName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.strOwnerMiddleName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.strFarmCode", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.strNationalName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.Address.PostCode", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.Address.Street", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.Address.strPostCode", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.Address.strStreetName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.Address.strApartment", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.Address.strHouse", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.Address.strBuilding", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.strFax", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.strEmail", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.strContactPhone", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Details)); AddHiddenPersonalData("Farm.Address.dblLatitude", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Coordinates)); AddHiddenPersonalData("Farm.Address.dblLongitude", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Vet_Farm_Coordinates)); } } #endregion #endregion } }
13,028
https://github.com/mmather11/ModTek/blob/master/ModTek/ModTek.cs
Github Open Source
Open Source
Unlicense, LicenseRef-scancode-public-domain
2,018
ModTek
mmather11
C#
Code
1,466
4,888
using BattleTech; using BattleTechModLoader; using Harmony; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using BattleTech.Data; using UnityEngine.Assertions; namespace ModTek { using static Logger; [UsedImplicitly] public static class ModTek { [UsedImplicitly] public static string ModDirectory { get; private set; } [UsedImplicitly] public static string StreamingAssetsDirectory { get; private set; } private const string MOD_JSON_NAME = "mod.json"; private static bool hasLoadedMods = false; private static List<string> modLoadOrder; private static Dictionary<Int32, string> JsonHashToId { get; } = new Dictionary<int, string>(); private static Dictionary<string, List<string>> JsonMerges { get; } = new Dictionary<string, List<string>>(); private static Dictionary<string, List<ModDef.ManifestEntry>> ModManifest { get; } = new Dictionary<string, List<ModDef.ManifestEntry>>(); // ran by BTML [UsedImplicitly] public static void Init() { var manifestDirectory = Path.GetDirectoryName(VersionManifestUtilities.MANIFEST_FILEPATH); Assert.IsNotNull(manifestDirectory, nameof(manifestDirectory) + " != null"); ModDirectory = Path.GetFullPath( Path.Combine(manifestDirectory, Path.Combine(Path.Combine(Path.Combine( "..", ".."), ".."), "Mods"))); StreamingAssetsDirectory = Path.GetFullPath(Path.Combine(manifestDirectory, "..")); LogPath = Path.Combine(ModDirectory, "ModTek.log"); // create log file, overwritting if it's already there using (var logWriter = File.CreateText(LogPath)) logWriter.WriteLine($"ModTek v{Assembly.GetExecutingAssembly().GetName().Version} -- {DateTime.Now}"); // init harmony and patch the stuff that comes with ModTek (contained in Patches.cs) var harmony = HarmonyInstance.Create("io.github.mpstark.ModTek"); harmony.PatchAll(Assembly.GetExecutingAssembly()); } [UsedImplicitly] public static void LoadMod(ModDef modDef) { var potentialAdditions = new List<ModDef.ManifestEntry>(); LogWithDate($"Loading {modDef.Name}"); // load out of the manifest if (modDef.LoadImplicitManifest && modDef.Manifest.All(x => Path.GetFullPath(Path.Combine(modDef.Directory, x.Path)) != Path.GetFullPath(Path.Combine(modDef.Directory, "StreamingAssets")))) modDef.Manifest.Add(new ModDef.ManifestEntry("StreamingAssets", true)); foreach (var entry in modDef.Manifest) { var entryPath = Path.Combine(modDef.Directory, entry.Path); if (string.IsNullOrEmpty(entry.Path) && (string.IsNullOrEmpty(entry.Type) || entry.Path == "StreamingAssets")) { Log($"\t{modDef.Name} has a manifest entry that is missing its path! Aborting load."); return; } if (Directory.Exists(entryPath)) { // path is a directory, add all the files there var files = Directory.GetFiles(entryPath, "*", SearchOption.AllDirectories); foreach (var filePath in files) { var childModDef = new ModDef.ManifestEntry(entry, filePath, InferIDFromFileAndType(filePath, entry.Type)); potentialAdditions.Add(childModDef); } } else if (File.Exists(entryPath)) { // path is a file, add the single entry entry.Id = entry.Id ?? InferIDFromFileAndType(entryPath, entry.Type); entry.Path = entryPath; potentialAdditions.Add(entry); } else { // wasn't a file and wasn't a path, must not exist // TODO: what to do with manifest entries that aren't implicit that are missing? //Log($"\t{modDef.Name} has a manifest entry {entryPath}, but it's missing! Aborting load."); //return; } } // load mod dll if (modDef.DLL != null) { var dllPath = Path.Combine(modDef.Directory, modDef.DLL); string typeName = null; var methodName = "Init"; if (!File.Exists(dllPath)) { Log($"\t{modDef.Name} has a DLL specified ({dllPath}), but it's missing! Aborting load."); return; } if (modDef.DLLEntryPoint != null) { var pos = modDef.DLLEntryPoint.LastIndexOf('.'); if (pos == -1) { methodName = modDef.DLLEntryPoint; } else { typeName = modDef.DLLEntryPoint.Substring(0, pos); methodName = modDef.DLLEntryPoint.Substring(pos + 1); } } Log($"\tUsing BTML to load dll {Path.GetFileName(dllPath)} with entry path {typeName ?? "NoNameSpecified"}.{methodName}"); BTModLoader.LoadDLL(dllPath, methodName, typeName, new object[] { modDef.Directory, modDef.Settings.ToString(Formatting.None) }); } // actually add the additions, since we successfully got through loading the other stuff if (potentialAdditions.Count > 0) { foreach (var addition in potentialAdditions) { Log($"\tNew Entry: {addition.Path.Replace(ModDirectory, "")}"); } ModManifest[modDef.Name] = potentialAdditions; } } internal static void LoadMods() { if (hasLoadedMods) return; // find all sub-directories that have a mod.json file var modDirectories = Directory.GetDirectories(ModDirectory) .Where(x => File.Exists(Path.Combine(x, MOD_JSON_NAME))).ToArray(); if (modDirectories.Length == 0) Log("No ModTek-compatable mods found."); // create ModDef objects for each mod.json file var modDefs = new Dictionary<string, ModDef>(); foreach (var modDirectory in modDirectories) { var modDefPath = Path.Combine(modDirectory, MOD_JSON_NAME); try { var modDef = ModDefFromPath(modDefPath); if (!modDef.Enabled) { LogWithDate($"Will not load {modDef.Name} because it's disabled."); continue; } if (modDefs.ContainsKey(modDef.Name)) { LogWithDate($"Already loaded a mod named {modDef.Name}. Skipping load from {modDef.Directory}."); continue; } modDefs.Add(modDef.Name, modDef); } catch (Exception e) { Log($"Caught exception while parsing {MOD_JSON_NAME} at path {modDefPath}"); Log($"\t{e.Message}"); //continue; } } // TODO: be able to read load order from a JSON PropagateConflictsForward(modDefs); modLoadOrder = GetLoadOrder(modDefs, out var willNotLoad); // lists guarentee order foreach (var modName in modLoadOrder) { var modDef = modDefs[modName]; try { LoadMod(modDef); } catch (Exception e) { LogWithDate($"Exception caught while trying to load {modDef.Name}"); Log($"{e.Message}"); } } foreach (var modDef in willNotLoad) { LogWithDate($"Will not load {modDef}. It's lacking a dependancy or a conflict loaded before it."); } Log(""); Log("----------"); Log(""); hasLoadedMods = true; } private static void PropagateConflictsForward(Dictionary<string, ModDef> modDefs) { // conflicts are a unidirectional edge, so make them one in ModDefs foreach (var modDefKvp in modDefs) { var modDef = modDefKvp.Value; if (modDef.ConflictsWith.Count == 0) continue; foreach (var conflict in modDef.ConflictsWith) { modDefs[conflict].ConflictsWith.Add(modDef.Name); } } } private static List<string> GetLoadOrder(Dictionary<string, ModDef> modDefs, out List<string> unloaded) { var loadOrder = new List<string>(); var loaded = new HashSet<string>(); unloaded = modDefs.Keys.OrderByDescending(x => x).ToList(); int removedThisPass; do { removedThisPass = 0; for (var i = unloaded.Count - 1; i >= 0; i--) { var modDef = modDefs[unloaded[i]]; if (modDef.DependsOn.Count != 0 && modDef.DependsOn.Intersect(loaded).Count() != modDef.DependsOn.Count || modDef.ConflictsWith.Count != 0 && modDef.ConflictsWith.Intersect(loaded).Any()) continue; unloaded.RemoveAt(i); loadOrder.Add(modDef.Name); loaded.Add(modDef.Name); removedThisPass++; } } while (removedThisPass > 0 && unloaded.Count > 0); return loadOrder; } private static ModDef ModDefFromPath(string path) { var modDef = JsonConvert.DeserializeObject<ModDef>(File.ReadAllText(path)); modDef.Directory = Path.GetDirectoryName(path); return modDef; } // ReSharper disable once UnusedParameter.Local private static string InferIDFromJObject(JObject jObj, string type = null) { // go through the different kinds of id storage in JSONS // TODO: make this specific to the type, remove Resharper disable once above string[] jPaths = { "Description.Id", "id", "Id", "ID", "identifier", "Identifier" }; foreach (var jPath in jPaths) { var id = (string) jObj.SelectToken(jPath); if (id != null) return id; } return null; } private static string InferIDFromFileAndType(string path, string type) { var ext = Path.GetExtension(path); if (ext == null || ext.ToLower() != ".json" || !File.Exists(path)) return Path.GetFileNameWithoutExtension(path); try { var jObj = JObject.Parse(File.ReadAllText(path)); var id = InferIDFromJObject(jObj, type); if (id != null) return id; } catch (Exception e) { Log($"\tException occurred while parsing type {type} json at {path}"); Log($"\t\t{e.Message}"); } // fall back to using the path return Path.GetFileNameWithoutExtension(path); } internal static string FixMissingCommas(string json) { var rgx = new Regex(@"(\]|\}|""|[A-Za-z0-9])\s*\n\s*(\[|\{|"")", RegexOptions.Singleline); return rgx.Replace(json, "$1,\n$2"); } internal static void TryMergeIntoInterceptedJson(string jsonIn, ref string jsonOut) { var jsonHash = jsonIn.GetHashCode(); var jsonCopy = jsonOut; if (!JsonHashToId.ContainsKey(jsonHash)) return; var id = JsonHashToId[jsonHash]; if (!JsonMerges.ContainsKey(id)) return; LogWithDate($"Merging json into ID: {id}"); JObject ontoJObj; try { ontoJObj = JObject.Parse(jsonCopy); } catch (Exception e) { try { Log("\tParent JSON has an JSON parse error, attempting to fix missing commas with regex"); jsonCopy = FixMissingCommas(jsonCopy); ontoJObj = JObject.Parse(jsonCopy); } catch (Exception e2) { Log("\tParent JSON has an error preventing merges that couldn't be fixed with missing comma regex"); Log($"\t\t Exception before regex: {e.Message}"); Log($"\t\t Exception after regex: {e2.Message}"); return; } Log("\tFixed missing commas in parent JSON."); } foreach (var jsonMerge in JsonMerges[id]) { try { var inJObj = JObject.Parse(jsonMerge); ontoJObj.Merge(inJObj, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace }); } catch (Exception e) { Log($"\tError merging particular JSON merge onto {id}, skipping just this single merge"); Log($"\t\t{e.Message}"); } } jsonOut = ontoJObj.ToString(); } internal static void TryAddToVersionManifest(VersionManifest manifest) { if (!hasLoadedMods) LoadMods(); var breakMyGame = File.Exists(Path.Combine(ModDirectory, "break.my.game")); LogWithDate("Adding in mod manifests!"); if (breakMyGame) { var mddPath = Path.Combine(Path.Combine(StreamingAssetsDirectory, "MDD"), "MetadataDatabase.db"); var mddBackupPath = mddPath + ".orig"; Log($"\tBreak my game mode enabled! All new modded content (doesn't currently support merges) will be added to the DB."); if (!File.Exists(mddBackupPath)) { Log($"\t\tBacking up metadata database to {Path.GetFileName(mddBackupPath)}"); File.Copy(mddPath, mddBackupPath); } } foreach (var modName in modLoadOrder) { if (!ModManifest.ContainsKey(modName)) continue; Log($"\t{modName}:"); foreach (var modEntry in ModManifest[modName]) { var existingEntry = manifest.Find(x => x.Id == modEntry.Id); VersionManifestAddendum addendum = null; if (!string.IsNullOrEmpty(modEntry.AddToAddendum)) { addendum = manifest.GetAddendumByName(modEntry.AddToAddendum); // create the addendum if it doesn't exist if (addendum == null) { Log($"\t\tCreated addendum {modEntry.AddToAddendum}:"); addendum = new VersionManifestAddendum(modEntry.AddToAddendum); manifest.ApplyAddendum(addendum); } } if (modEntry.Type == null) { // null type means that we have to find existing entry with the same rel path to fill in the entry // TODO: + 16 is a little bizzare looking, it's the length of the substring + 1 because we want to get rid of it and the \ var relPath = modEntry.Path.Substring(modEntry.Path.LastIndexOf("StreamingAssets", StringComparison.Ordinal) + 16); var fakeStreamingAssetsPath = Path.Combine(StreamingAssetsDirectory, relPath); existingEntry = manifest.Find(x => Path.GetFullPath(x.FilePath) == Path.GetFullPath(fakeStreamingAssetsPath)); if (existingEntry == null) continue; modEntry.Id = existingEntry.Id; modEntry.Type = existingEntry.Type; } if (Path.GetExtension(modEntry.Path).ToLower() == ".json" && modEntry.ShouldMergeJSON && existingEntry != null) { // read the manifest pointed entry and hash the contents JsonHashToId[File.ReadAllText(existingEntry.FilePath).GetHashCode()] = modEntry.Id; // The manifest already contains this information, so we need to queue it to be merged var partialJson = File.ReadAllText(modEntry.Path); if (!JsonMerges.ContainsKey(modEntry.Id)) JsonMerges.Add(modEntry.Id, new List<string>()); if (JsonMerges[modEntry.Id].Contains(partialJson)) { Log($"\t\tAlready added {modEntry.Id} to JsonMerges"); continue; } Log($"\t\tAdding {modEntry.Id} to JsonMerges"); JsonMerges[modEntry.Id].Add(partialJson); continue; } if (breakMyGame && Path.GetExtension(modEntry.Path).ToLower() == ".json") { var type = (BattleTechResourceType) Enum.Parse(typeof(BattleTechResourceType), modEntry.Type); using (var metadataDatabase = new MetadataDatabase()) { VersionManifestHotReload.InstantiateResourceAndUpdateMDDB(type, modEntry.Path, metadataDatabase); Log($"\t\tAdding to MDDB! {type} {modEntry.Path}"); } } if (!string.IsNullOrEmpty(modEntry.AddToAddendum)) { Log($"\t\tAddOrUpdate {modEntry.Type} {modEntry.Id} to addendum {addendum.Name}"); addendum.AddOrUpdate(modEntry.Id, modEntry.Path, modEntry.Type, DateTime.Now, modEntry.AssetBundleName, modEntry.AssetBundlePersistent); continue; } // This is a new definition or a replacement that doesn't get merged, so add or update the manifest Log($"\t\tAddOrUpdate {modEntry.Type} {modEntry.Id}"); manifest.AddOrUpdate(modEntry.Id, modEntry.Path, modEntry.Type, DateTime.Now, modEntry.AssetBundleName, modEntry.AssetBundlePersistent); } } Log(""); } } }
2,884
https://github.com/rajeshyogeshwar/exchange_calendars/blob/master/tests/test_xbse_calendar.py
Github Open Source
Open Source
Apache-2.0
null
exchange_calendars
rajeshyogeshwar
Python
Code
327
1,033
import pytest from exchange_calendars.exchange_calendar_xbse import XBSEExchangeCalendar from .test_exchange_calendar import ExchangeCalendarTestBaseNew class TestXBSECalendar(ExchangeCalendarTestBaseNew): @pytest.fixture(scope="class") def calendar_cls(self): yield XBSEExchangeCalendar @pytest.fixture def max_session_hours(self): # XBSE is open from 10:00 to 5:20PM on its longest trading day yield 7 + (3 / 4) @pytest.fixture def regular_holidays_sample(self): yield [ "2021-01-01", # New Year's Day "2021-04-30", # Orthodox Good Friday "2021-06-01", # Children's day "2021-06-21", # Orthodox Pentecost "2021-11-30", # St. Adnrew's Day "2021-12-01", # National Day "2020-01-01", # New Year's Day "2020-01-02", # New Year's Day "2020-01-24", # Romanian Principalities Unification Day "2020-04-17", # Good Friday "2020-04-20", # Orthodox Easter "2020-05-01", # Labour Day "2020-06-01", # Children's Day "2020-06-08", # Orthodox Pentecost "2020-11-30", # St. Adnrew's day "2020-12-01", # National Day "2020-12-25", # Christmans "2019-01-01", # New Year's Day "2019-01-02", # New Year's Day "2019-01-24", # Romanian Principalities Unification Day "2019-04-26", # Good Friday "2019-04-29", # Orthodox Easter "2019-05-01", # Labour Day "2019-06-17", # Orthodox Pentecost "2019-08-15", # Assumption of Virgin Mary "2019-12-25", # Christmans "2019-12-26", # Christmans ] @pytest.fixture def adhoc_holidays_sample(self): yield [ # Athens Stock Exchange observes Orthodox (or Eastern) Easter, # as well as Western Easter. All holidays that are tethered to # Easter (i.e. Whit Monday, Good Friday, etc.), are relative to # Orthodox Easter. Following checks that Orthodox Easter and # related holidays are correct. # # Some Orthodox Good Friday dates "2002-05-03", "2005-04-29", "2008-04-25", "2009-04-17", "2016-04-29", "2017-04-14", # Some Orthodox Pentecost dates "2002-06-24", "2005-06-20", "2006-06-12", "2008-06-16", "2013-06-24", "2016-06-20", ] @pytest.fixture def non_holidays_sample(self): yield [ # Holidays that fall on a weekend are not made up. Ensure surrounding # days are not holidays. # Second New Years Day on Saturday, Jan 2st "2021-01-04", # Christmas 25th, 26th both holidays, fall Saturday Sunday "2021-12-24", "2021-12-27", # Labour Day on Saturday + Good Friday on Friday + Orthodox Easter on Monday "2021-04-29", "2021-05-04", # Children's Day on Saturday "2019-05-31", "2019-06-03", # Assumption of Virgin Mary on Sunday "2021-08-13", "2021-08-16", # Assumption of Virgin Mary on Saturday "2020-08-14", "2020-08-17", ]
7,315
https://github.com/rcanasv/astrolibc/blob/master/src/structure.h
Github Open Source
Open Source
MIT
null
astrolibc
rcanasv
C
Code
237
681
/* * \file structure.h * \brief header file containing stuff related to structures in simulations * e.g. Haloes, Subhaloes, Galaxies, Streams, etc ... * */ #ifndef STRUCTURE_H #define STRUCTURE_H #include "base.h" #include "particle.h" #include "typedef.h" #include "format.h" #include "stf.h" void Structure_correct_periodicity (Structure * strct, Simulation * sim); void Structure_sort_by_radius (Structure * strct); void Structure_calculate_centre_of_mass (Structure * strct); void Structure_calculate_surface_density (Structure * strct, double * rotation, double ledge, double redge, int nbins, double ** bins, double ** Sigma); void Structure_calculate_spherical_density (Structure * strct, double ledge, double redge, int nbins, double deltar, double ** bins, double ** Rho); void Structure_calculate_j_r (Structure * strct, double radius); void Structure_calculate_sigma_v_r (Structure * strct, double radius); void Structure_calculate_sfr (Structure * strct); void Structure_calculate_fmass_radius (Catalog * ctlg, Simulation * sim, int * strct_to_get, double fraction); void Structure_calculate_disp_tensor_pos (Catalog * ctlg, Simulation * sim, int * strct_to_get); void Structure_calculate_disp_tensor_vel (Catalog * ctlg, Simulation * sim, int * strct_to_get); void Structure_rotate_position_x (Structure * strct, double angle); void Structure_rotate_position_y (Structure * strct, double angle); void Structure_rotate_position_z (Structure * strct, double angle); void Structure_rotate_velocity_x (Structure * strct, double angle); void Structure_rotate_velocity_y (Structure * strct, double angle); void Structure_rotate_velocity_z (Structure * strct, double angle); void Structure_get_particle_radius (Structure * strct); void Structure_get_particle_properties (Catalog * ctlg, Simulation * sim, int * strct_to_get); void Structure_shift_to_centre_of_mass (Structure * strct); int Structure_mass_compare (const void * a, const void * b); int Structure_dummyd_compare (const void * a, const void * b); #endif /* STRUCTURE_H */
30,717
https://github.com/gugang/element/blob/master/packages/tabs/src/tabs.vue
Github Open Source
Open Source
MIT
null
element
gugang
Vue
Code
274
998
<script> import ElTab from './tab'; module.exports = { name: 'el-tabs', components: { ElTab }, props: { type: String, tabPosition: String, activeName: String, closable: false, tabWidth: 0 }, data() { return { tabs: [], children: null, activeTab: null, currentName: 0, barStyle: '' }; }, watch: { activeName: { handler(val) { var fisrtKey = this.$children[0] && this.$children[0].key || '1'; this.currentName = val || fisrtKey; } }, 'currentName'() { this.calcBarStyle(); } }, methods: { handleTabRemove(tab, ev) { ev.stopPropagation(); tab.$destroy(true); var index = this.tabs.indexOf(tab); if (index !== -1) { this.tabs.splice(index, 1); } if (tab.key === this.currentName) { let deleteIndex = this.$children.indexOf(tab); let nextChild = this.$children[deleteIndex + 1]; let prevChild = this.$children[deleteIndex - 1]; this.currentName = nextChild ? nextChild.key : prevChild ? prevChild.key : '-1'; } this.$emit('tab-remove', tab.key); }, handleTabClick(tab, event) { this.currentName = tab.key; this.$emit('tab-click', tab.key, event); }, calcBarStyle(firstRendering) { if (this.type || !this.$refs.tabs) return {}; var style = {}; var offset = 0; var tabWidth = 0; this.tabs.every((tab, index) => { let $el = this.$refs.tabs[index].$el; if (tab.key !== this.currentName) { offset += $el.clientWidth; return true; } else { tabWidth = $el.clientWidth; return false; } }); style.width = tabWidth + 'px'; style.transform = `translateX(${offset}px)`; if (!firstRendering) { style.transition = 'transform .3s cubic-bezier(.645,.045,.355,1), -webkit-transform .3s cubic-bezier(.645,.045,.355,1)'; } this.barStyle = style; } }, mounted() { if (!this.currentName) { var fisrtKey = this.$children[0] && this.$children[0].key || '1'; this.currentName = this.activeName || fisrtKey; } this.$children.forEach(tab => this.tabs.push(tab)); this.$nextTick(() => this.calcBarStyle(true)); } }; </script> <template> <div class="el-tabs" :class="[type ? 'el-tabs--' + type : '']"> <div class="el-tabs__header"> <el-tab v-for="tab in tabs" ref="tabs" :tab="tab" :closable="closable" @remove="handleTabRemove" @click.native="handleTabClick(tab, $event)"> </el-tab> <div class="el-tabs__active-bar" :style="barStyle" v-if="!this.type && tabs.length > 0"> </div> </div> <div class="el-tabs__content"> <slot></slot> </div> </div> </template>
28,854
https://github.com/jeremiedecock/pyai/blob/master/ailib/optimize/minimizers/saes.py
Github Open Source
Open Source
MIT
2,019
pyai
jeremiedecock
Python
Code
845
2,376
# -*- coding: utf-8 -*- # Copyright (c) 2013,2014,2015,2016,2017 Jeremie DECOCK (http://www.jdhp.org) # 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. __all__ = ['SAES'] import math import numpy as np import pandas as pd try: import matplotlib import matplotlib.pyplot as plt from matplotlib import cm from matplotlib import colors except Exception as e: print(e) from .optimizer import Optimizer class SAES(Optimizer): """SAES optimizer. ($\mu$/1+$\lambda$)-$\sigma$-Self-Adaptation-ES Init pop $\forall$ gen $\quad$ $\forall$ child $\quad\quad$ 1. select $\rho$ parents $\quad\quad$ 2. recombination of selected parents (if $\rho > 1$) $\quad\quad$ 3. mutation of $\sigma$ (individual strategy) : $\sigma \leftarrow \sigma ~ e^{\tau \mathcal{N}(0,1)}$ $\quad\quad$ 4. mutation of $\boldsymbol{x}$ (objective param) : $\boldsymbol{x} \leftarrow \boldsymbol{x} + \sigma ~ \mathcal{N}(0,1)$ $\quad\quad$ 5. eval $f(\boldsymbol{x})$ $\quad$ Select next gen individuals See: * http://www.scholarpedia.org/article/Evolution_strategies * Notebook "ai_optimization_saes_en.ipynb" on jdhp.org Parameters ---------- mu : int The number of parents. lambda_ : int The number of offspring. sigma_init : float The initial global mutation strength sigma. sigma_min : float The stop criterion: the optimization is stopped when `sigma` is smaller than `sigma_min`. sigma_init : int The number of times the (noisy) objective functions should be called at each evaluation (taking the average value of these calls). """ def minimize(self, objective_function, init_pop_mean, init_pop_std, num_gen=50, mu=3, lmb=6, rho=1, tau=None, selection_operator='+', isotropic_mutation=True, plot=False): """TODO Parameters ---------- x_init : ndarray The initial parent vector (a 1D numpy array). Returns ------- ndarray The optimal point found (a 1D numpy array). """ assert selection_operator in (',', '+') # Number of dimension of the solution space d = objective_function.ndim # Self-adaptation learning rate if tau is None: tau = 1./math.sqrt(2.*d) # Set indices alias ############################ all_indices = slice(None, None) parent_indices = slice(0, mu) children_indices = slice(mu, None) sigma_col = 0 x_cols = slice(1, -1) y_col = -1 sigma_col_label = "sigma" y_col_label = "y" # Init the population ########################## # "pop" array layout: # - the first mu lines contain parents # - the next lambda lines contain children # - the first column contains the individual's strategy (sigma) # - the last column contains the individual's assess (f(x)) # - the other columns contain the individual value (x) pop = pd.DataFrame(np.full([mu+lmb, d+2], np.nan), columns=[sigma_col_label] + ["x" + str(d) for d in range(d)] + [y_col_label]) pop.iloc[parent_indices, sigma_col] = 1. # init the parents strategy to 1.0 #pop.iloc[parent_indices, x_cols] = np.random.normal(init_pop_mean, # init_pop_std, # size=[mu, d]) # init the parents value pop.iloc[parent_indices, x_cols] = np.random.uniform(low=-10., high=10., size=[mu, d]) # init the parents value pop.iloc[parent_indices, y_col] = objective_function(pop.iloc[parent_indices, x_cols].values.T) # evaluate parents #print("Initial population:\n", pop, "\n") # Plot ############################################# if plot: cmap = cm.gnuplot2 # magma fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(20, 6)) ax3.set_xlabel('gen') ax3.set_ylabel('y') for gen in range(num_gen): # Parent selection ############################# if rho == 1: # Each child is made from one randomly selected parent selected_parent_indices = np.random.randint(mu, size=lmb) elif rho == mu: # Recombine all parents for each child raise NotImplemented() # TODO elif 1 < rho < mu: # Recombine rho randomly selected parents for each child raise NotImplemented() # TODO else: raise ValueError() #print("Parent selection") #display(selected_parent_indices) # Recombination ################################ if rho == 1: # Each child is made from one randomly selected parent pop.iloc[children_indices] = pop.iloc[selected_parent_indices].values elif rho == mu: # Recombine all parents for each child raise NotImplemented() # TODO elif 1 < rho < mu: # Recombine rho randomly selected parents for each child raise NotImplemented() # TODO else: raise ValueError() pop.iloc[children_indices, y_col] = np.nan #print("Recombination") #display(pop) # Mutate children's sigma ###################### pop.iloc[children_indices, sigma_col] *= np.exp(tau * np.random.normal(size=lmb)) #print("Mutated children's sigma") #display(pop) # Mutate children's value ###################### sigma_array = np.tile(pop.iloc[children_indices, sigma_col], [d,1]).T # TODO: <- CHECK THIS !!! random_array = np.random.normal(size=[lmb,d]) pop.iloc[children_indices, x_cols] += sigma_array * random_array #print("Mutated children's value") #display(pop) # Evaluate children ############################ pop.iloc[children_indices, y_col] = objective_function(pop.iloc[children_indices, x_cols].values.T) #print("Evaluate children") #display(pop) if plot: color_str = matplotlib.colors.rgb2hex(cmap(float(gen) / num_gen)) pop.plot.scatter(x="x0", y="x1", c=color_str, ax=ax1) pop.plot.scatter(x="sigma", y="y", c=color_str, loglog=True, ax=ax2) ax3.semilogy(np.full(shape=pop.y.shape, fill_value=gen), pop.y, '.', color=color_str) # Select the best individuals ################## if selection_operator == ',': pop.iloc[parent_indices] = np.nan pop = pop.sort_values(by=[y_col_label], na_position='last').reset_index(drop=True) pop.iloc[children_indices] = np.nan #print("Selected individuals for the next generation") #display(pop) if plot: plt.show() return pop.iloc[0, x_cols].values
27,400
https://github.com/aqiu95/cellsociety/blob/master/src/UI/GraphManager.java
Github Open Source
Open Source
MIT
null
cellsociety
aqiu95
Java
Code
165
624
package UI; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.stage.Stage; import java.util.ArrayList; /** * This class manages the graphing of the UI. * * @author Allen Qiu (asq3) */ public class GraphManager { private static final int WINDOW_HEIGHT = 300; private static final int WINDOW_WIDTH = 1000; private ArrayList<XYChart.Series> mySeries = new ArrayList<>(); private int time = 0; private Stage myStage; private boolean stageVisible = false; GraphManager(int numSeries, String[] colors) { NumberAxis xAxis = new NumberAxis(); xAxis.setLabel("Steps"); NumberAxis yAxis = new NumberAxis(); yAxis.setLabel("Population"); LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis); lineChart.setCreateSymbols(false); lineChart.setLegendVisible(false); for(int i=0;i<numSeries;i++){ mySeries.add(new XYChart.Series()); } Scene scene = new Scene(lineChart, WINDOW_WIDTH, WINDOW_HEIGHT); for(int i=0;i<mySeries.size();i++){ XYChart.Series myCurrentSeries = mySeries.get(i); lineChart.getData().add(myCurrentSeries); myCurrentSeries.getNode().lookup(".chart-series-line").setStyle("-fx-stroke: #" + colors[i] + ";"); } myStage = new Stage(); myStage.setTitle("CA Simulator"); myStage.setX(0); myStage.setY(0); myStage.setScene(scene); } public void updateGraph(int[] values){ for(int i=0;i<mySeries.size();i++){ mySeries.get(i).getData().add(new XYChart.Data(time, values[i])); } time++; } public void toggleChart(){ if(stageVisible){ stageVisible = false; myStage.hide(); } else { stageVisible = true; myStage.show(); } } public void closeChart(){ myStage.close(); } }
38,958
https://github.com/Gintasp/university-advisor/blob/master/Models/JSON/FacultyDataModel.cs
Github Open Source
Open Source
MIT
null
university-advisor
Gintasp
C#
Code
18
41
namespace Advisor.Models.JSON { public class FacultyDataModel : BasicModel { public int UniversityId { get; set; } } }
29,440
https://github.com/zhuyifan1996/arctic-captions/blob/master/vgg_net.py
Github Open Source
Open Source
BSD-3-Clause
2,016
arctic-captions
zhuyifan1996
Python
Code
543
1,899
# VGG-16, 16-layer model from the paper: # "Very Deep Convolutional Networks for Large-Scale Image Recognition" # Original source: https://gist.github.com/ksimonyan/211839e770f7b538e2d8 # License: see http://www.robots.ox.ac.uk/~vgg/research/very_deep/ # Download pretrained weights from: # https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/vgg16.pkl import numpy as np import matplotlib.pyplot as plt import lasagne from lasagne.layers import InputLayer from lasagne.layers import DenseLayer from lasagne.layers import NonlinearityLayer from lasagne.layers import DropoutLayer from lasagne.layers import Pool2DLayer as PoolLayer from lasagne.layers import Conv2DLayer as ConvLayer from lasagne.nonlinearities import softmax from lasagne.utils import floatX def build_model(): net = {} net['input'] = InputLayer((None, 3, 224, 224)) net['conv1_1'] = ConvLayer( net['input'], 64, 3, pad=1 ) net['conv1_2'] = ConvLayer( net['conv1_1'], 64, 3, pad=1 ) net['pool1'] = PoolLayer(net['conv1_2'], 2) net['conv2_1'] = ConvLayer( net['pool1'], 128, 3, pad=1 ) net['conv2_2'] = ConvLayer( net['conv2_1'], 128, 3, pad=1 ) net['pool2'] = PoolLayer(net['conv2_2'], 2) net['conv3_1'] = ConvLayer( net['pool2'], 256, 3, pad=1 ) net['conv3_2'] = ConvLayer( net['conv3_1'], 256, 3, pad=1 ) net['conv3_3'] = ConvLayer( net['conv3_2'], 256, 3, pad=1 ) net['pool3'] = PoolLayer(net['conv3_3'], 2) net['conv4_1'] = ConvLayer( net['pool3'], 512, 3, pad=1 ) net['conv4_2'] = ConvLayer( net['conv4_1'], 512, 3, pad=1 ) net['conv4_3'] = ConvLayer( net['conv4_2'], 512, 3, pad=1 ) net['pool4'] = PoolLayer(net['conv4_3'], 2) net['conv5_1'] = ConvLayer( net['pool4'], 512, 3, pad=1 ) net['conv5_2'] = ConvLayer( net['conv5_1'], 512, 3, pad=1 ) net['conv5_3'] = ConvLayer( net['conv5_2'], 512, 3, pad=1 ) net['pool5'] = PoolLayer(net['conv5_3'], 2) net['fc6'] = DenseLayer(net['pool5'], num_units=4096) net['fc6_dropout'] = DropoutLayer(net['fc6'], p=0.5) net['fc7'] = DenseLayer(net['fc6_dropout'], num_units=4096) net['fc7_dropout'] = DropoutLayer(net['fc7'], p=0.5) net['fc8'] = DenseLayer( net['fc7_dropout'], num_units=1000, nonlinearity=None) net['prob'] = NonlinearityLayer(net['fc8'], softmax) output_layer = net['prob'] return net, net['prob'] # the whole net and the output layer def load_param(output_layer, pickle_file): """ load the model and parameters from specified pickle_file into the lasagne layers, with output layer set to [output_layer] """ import pickle model = pickle.load(open(pickle_file)) CLASSES = model['synset words'] # MEAN_IMAGE = model['mean value'] # right now do not subtract mean image during testing lasagne.layers.set_all_param_values(output_layer, model['param values']) def prepare_image(im): import io import skimage.transform # Resize so smallest dim = 256, preserving aspect ratio h, w, _ = im.shape if h < w: im = skimage.transform.resize(im, (256, w*256/h), preserve_range=True) else: im = skimage.transform.resize(im, (h*256/w, 256), preserve_range=True) # Central crop to 224x224 h, w, _ = im.shape im = im[h//2-112:h//2+112, w//2-112:w//2+112] rawim = np.copy(im).astype('uint8') # Shuffle axes to c01 im = np.swapaxes(np.swapaxes(im, 1, 2), 0, 1) # Convert to BGR im = im[::-1, :, :] # WARNING: DID NOT subtract mean during testing # im = im - MEAN_IMAGE return rawim, floatX(im[np.newaxis]) def extract_feature(img, layer): """ run the pretrained network on the image and extract the output from [layer]. [args]: img -- np array representing the test image layer -- lasagne layer object specifying which layer to extract from """ rawim, im = prepare_image(img) feature = np.array(lasagne.layers.get_output(layer, im, deterministic=True).eval()) assert feature.shape == (1, 512, 14, 14) return feature if __name__ == "__main__": from scipy import misc import os from six.moves import cPickle DATAPATH = os.getcwd()+os.sep+"data"+os.sep # set up the pretrained VGG Net 16 net, output_layer = build_model() load_param(output_layer, DATAPATH+"vgg16.pkl") for f in os.listdir(DATAPATH+"Flicker8k_Dataset"): if f.endswith(".jpg"): img = misc.imread(DATAPATH+"Flicker8k_Dataset"+os.sep+f) feat = extract_feature(img, net["conv5_3"]) with open(DATAPATH+"Flicker8k_features"+os.sep+f.replace('.jpg','.pkl'), 'w+') as out: cPickle.dump(feat, out, protocol=cPickle.HIGHEST_PROTOCOL) else: continue # rawimd, im = prep_image(img) # prob = np.array(lasagne.layers.get_output(output_layer, im, deterministic=True).eval()) # top5 = np.argsort(prob[0])[-1:-6:-1] # plt.figure() # plt.imshow(rawimd.astype('uint8')) # plt.axis('off') # for n, label in enumerate(top5): # plt.text(250, 70 + n * 20, '{}. {}'.format(n+1, CLASSES[label]), fontsize=14)
9,237
https://github.com/cloudfoundry/bosh-agent/blob/master/platform/net/mac_address_detector.go
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, Apache-2.0
2,023
bosh-agent
cloudfoundry
Go
Code
388
1,223
package net import ( "encoding/json" gonet "net" "path" "strings" bosherr "github.com/cloudfoundry/bosh-utils/errors" boshsys "github.com/cloudfoundry/bosh-utils/system" ) //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . MACAddressDetector type MACAddressDetector interface { DetectMacAddresses() (map[string]string, error) } const ( ifaliasPrefix = "bosh-interface" ) type linuxMacAddressDetector struct { fs boshsys.FileSystem } type windowsMacAddressDetector struct { interfacesFunction func() ([]gonet.Interface, error) runner boshsys.CmdRunner } type netAdapter struct { Name string MacAddress string } func NewLinuxMacAddressDetector(fs boshsys.FileSystem) MACAddressDetector { return linuxMacAddressDetector{ fs: fs, } } func NewWindowsMacAddressDetector(runner boshsys.CmdRunner, interfacesFunction func() ([]gonet.Interface, error)) MACAddressDetector { return windowsMacAddressDetector{ interfacesFunction: interfacesFunction, runner: runner, } } func (d linuxMacAddressDetector) DetectMacAddresses() (map[string]string, error) { addresses := map[string]string{} filePaths, err := d.fs.Glob("/sys/class/net/*") if err != nil { return addresses, bosherr.WrapError(err, "Getting file list from /sys/class/net") } var macAddress string var ifalias string for _, filePath := range filePaths { isPhysicalDevice := d.fs.FileExists(path.Join(filePath, "device")) // For third-party networking plugin case that the physical interface is used as bridge // interface and a virtual interface is created to replace it, the virtual interface needs // to be included in the detected result. // The virtual interface has an ifalias that has the prefix "bosh-interface" hasBoshPrefix := false ifalias, err = d.fs.ReadFileString(path.Join(filePath, "ifalias")) if err == nil { hasBoshPrefix = strings.HasPrefix(ifalias, ifaliasPrefix) } if isPhysicalDevice || hasBoshPrefix { macAddress, err = d.fs.ReadFileString(path.Join(filePath, "address")) if err != nil { return addresses, bosherr.WrapError(err, "Reading mac address from file") } macAddress = strings.Trim(macAddress, "\n") interfaceName := path.Base(filePath) addresses[macAddress] = interfaceName } } return addresses, nil } func (d windowsMacAddressDetector) DetectMacAddresses() (map[string]string, error) { ifs, err := d.interfacesFunction() if err != nil { return nil, bosherr.WrapError(err, "Detecting Mac Addresses") } macs := make(map[string]string, len(ifs)) var netAdapters []netAdapter stdout, stderr, _, err := d.runner.RunCommand("powershell", "-Command", "Get-NetAdapter | Select MacAddress,Name | ConvertTo-Json") if err != nil { return nil, bosherr.WrapErrorf(err, "Getting visible adapters: %s", stderr) } err = json.Unmarshal([]byte(stdout), &netAdapters) if err != nil { var singularNetAdapter netAdapter err = json.Unmarshal([]byte(stdout), &singularNetAdapter) if err != nil { return nil, bosherr.WrapError(err, "Parsing Get-NetAdapter output") } netAdapters = append(netAdapters, singularNetAdapter) } for _, f := range ifs { if adapterVisible(netAdapters, f.HardwareAddr.String(), f.Name) { macs[f.HardwareAddr.String()] = f.Name } } return macs, nil } func adapterVisible(netAdapters []netAdapter, macAddress string, adapterName string) bool { for _, adapter := range netAdapters { adapterMac, _ := gonet.ParseMAC(adapter.MacAddress) if adapter.Name == adapterName && adapterMac.String() == macAddress { return true } } return false }
17,252
https://github.com/vashistaarav1611/Arcade/blob/master/puzzle/source/Drawer.js
Github Open Source
Open Source
MIT
2,022
Arcade
vashistaarav1611
JavaScript
Code
430
1,315
/** * Drawer Manager */ class Drawer { /** * The Drawer constructor * @param {Metrics} metrics * @param {Instance} instance */ constructor(metrics, instance) { this.instance = instance; this.list = new List(instance.getDrawerPieces()); this.element = document.querySelector(".drawer"); this.grid = document.querySelector(".grid"); this.button = document.querySelector(".drawer button"); this.onlyBorders = false; const optimalSize = 210; const minAmount = Math.floor(optimalSize / metrics.fullSize); const minSize = minAmount * metrics.fullSize; const maxSize = (minAmount + 1) * metrics.fullSize; const cols = Math.abs(minSize - optimalSize) < Math.abs(maxSize - optimalSize) ? minAmount : minAmount + 1; const finalSize = (cols * metrics.fullSize) + (cols - 1) * 8; this.element.style.display = "block"; this.element.style.width = Utils.toPX(finalSize); this.grid.style.gridTemplateColumns = `repeat(${cols}, 1fr)`; this.list.forEach((elem) => this.grid.appendChild(elem.canvas)); } /** * Destroys the Drawer * @returns {Void} */ destroy() { if (this.onlyBorders) { this.toggleBorders(); } this.grid.innerHTML = ""; this.element.style.display = "none"; this.list.empty(); this.list = null; this.element = null; this.grid = null; this.button = null; } /** * Toggles between showing only border pieces or all * @returns {Void} */ toggleBorders() { this.button.innerHTML = this.onlyBorders ? "Only Borders" : "All Pieces"; this.grid.classList.toggle("drawer-borders"); this.onlyBorders = !this.onlyBorders; } /** * Returns true if the Position is in the Drawer bounds * @param {{top: Number, left: Number}} pos * @returns {Boolean} */ inBounds(pos) { return Utils.inElement(pos, this.element); } /** * Drops the Piece to the Drawer * @param {Piece} piece * @param {{top: Number, left: Number}} pos * @returns {Void} */ dropPiece(piece, pos) { const closestPiece = this.findClosest(pos, piece.id); if (closestPiece) { this.grid.insertBefore(piece.canvas, closestPiece.canvas); } else { this.grid.appendChild(piece.canvas); } if (piece.inDrawer) { this.list.remove((item) => item.id === piece.id); } if (closestPiece) { this.list.addBefore(piece, (item) => item.id === closestPiece.id); } else { this.list.addLast(piece); } this.instance.saveDrawerPieces(this.list); piece.dropInDrawer(); } /** * Removes a Piece from the Drawer * @param {Piece} piece * @returns {Void} */ removePiece(piece) { if (piece.inDrawer) { this.list.remove((elem) => elem.id === piece.id); this.instance.saveDrawerPieces(this.list); } } /** * Finds the Piece with the given ID * @param {Number} id * @returns {?Piece} */ findPiece(id) { return this.list.find((elem) => elem.id === id); } /** * Finds the closest Piece to the given position * @param {{top: Number, left: Number}} pos * @param {Number} skipID * @returns {?Piece} */ findClosest(pos, skipID) { let minDist = Number.POSITIVE_INFINITY; let result = null; this.list.some((elem) => { if (elem.id === skipID) { return false; } const bounds = elem.canvas.getBoundingClientRect(); if (Utils.inBounds(pos, bounds)) { result = elem; return true; } const center = { top : bounds.top + bounds.height / 2, left : bounds.left + bounds.width / 2 }; const dist = Utils.dist(pos, center); if (dist < minDist) { minDist = dist; result = elem; } }); return result; } }
2,547
https://github.com/yaroslavya/entity-space/blob/master/packages/libs/core/src/lib/criteria/criterion/set/not-in-set.fn.ts
Github Open Source
Open Source
MIT
2,021
entity-space
yaroslavya
TypeScript
Code
83
298
import { NotInNumberSetCriterion } from "./not-in-number-set-criterion"; import { NotInStringSetCriterion } from "./not-in-string-set-criterion"; function firstValueIsString(set: Iterable<unknown>): set is Iterable<string> { return typeof set[Symbol.iterator]().next().value === "string"; } function firstValueIsNumber(set: Iterable<unknown>): set is Iterable<number> { return typeof set[Symbol.iterator]().next().value === "number"; } export function notInSet(values: Iterable<number>): NotInNumberSetCriterion; export function notInSet(values: Iterable<string>): NotInStringSetCriterion; export function notInSet<T>(values: Iterable<T>): NotInNumberSetCriterion | NotInStringSetCriterion { if (firstValueIsString(values)) { return new NotInStringSetCriterion(values); } else if (firstValueIsNumber(values)) { return new NotInNumberSetCriterion(values); } else { throw new Error(`values empty or contain unsupported type`); } }
36,564
https://github.com/17500mph/CAP/blob/master/contrib/Timelord/timelord.h
Github Open Source
Open Source
LicenseRef-scancode-public-domain, LicenseRef-scancode-other-permissive
2,015
CAP
17500mph
C
Code
77
199
/* * timelord - UNIX Macintosh time server daemon * * 22/05/89 djh@munnari.oz * * Copyright (c) 1990, the University of Melbourne * */ /* general junk */ #define ZONE "*" /* NBP Zone */ #define MACSERVER "TimeLord" /* NBP Name */ #define TIME_OFFSET 0x7c25b080 /* Mac Time 00:00:00 GMT Jan 1, 1970 */ #define LOGFILE "/dev/null" /* available commands */ #define GETTIME 0 /* error messages */ #define ENOPERM 10 #define ENOLOGIN 11 #define ENONE 12
23,524
https://github.com/NzBernadine/Blockly4RPA/blob/master/scripts/blocks/file_blocks.js
Github Open Source
Open Source
Apache-2.0
2,022
Blockly4RPA
NzBernadine
JavaScript
Code
155
892
Blockly.Blocks['open_file'] = { init: function() { this.appendValueInput("FILE_NAME") .setCheck("String") .appendField("open file "); this.appendDummyInput() .appendField("to") .appendField(new Blockly.FieldDropdown([["read","r"], ["write","w"], ["creation","x"], ["append","a"], ["binary","b"], ["text","t"], ["update","+"]]), "MODE"); this.setInputsInline(true); this.setOutput(true, null); this.setColour(60); this.setTooltip("Opens a file and returns a file object"); this.setHelpUrl("https://www.w3schools.com/python/ref_func_open.asp"); } }; Blockly.Blocks['read_file'] = { init: function() { this.appendValueInput("FILE") .setCheck("VAR") .appendField("read in"); this.appendDummyInput() .appendField(new Blockly.FieldDropdown([["#","-1"], ["size","SIZE"]]), "SIZE_INPUT"); this.appendValueInput("SIZE") .setCheck("Number"); this.setInputsInline(true); this.setOutput(true, "String"); this.setColour(60); this.setTooltip("Returns the file content"); this.setHelpUrl("https://www.w3schools.com/python/ref_file_read.asp"); } }; Blockly.Blocks['write_file'] = { init: function() { this.appendValueInput("FILE") .setCheck("VAR") .appendField("write in "); this.appendValueInput("TEXT") .setCheck("String") .appendField("text"); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(60); this.setTooltip("Writes the specified string to the file"); this.setHelpUrl("https://www.w3schools.com/python/ref_file_write.asp"); } }; Blockly.Blocks['close_file'] = { init: function() { this.appendValueInput("FILE") .setCheck("VAR") .appendField("close file"); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(60); this.setTooltip("Closes the file"); this.setHelpUrl("https://www.w3schools.com/python/ref_file_close.asp"); } }; Blockly.Blocks['csv_reader'] = { init: function() { this.appendValueInput("FILE") .setCheck(null) .appendField("with") .appendField(new Blockly.FieldTextInput("csv"), "MODULE") .appendField("read"); this.appendValueInput("DIALECT") .setCheck("String") .appendField(new Blockly.FieldTextInput("newline"), "INSTRUCTION"); this.setInputsInline(true); this.setOutput(true, null); this.setColour(60); this.setTooltip("Return a reader object which will iterate over lines in the given csvfile"); this.setHelpUrl("https://docs.python.org/3/library/csv.html#module-contents"); } };
50,968
https://github.com/devCrossNet/chaptr/blob/master/src/app/app/mutations.ts
Github Open Source
Open Source
MIT
2,020
chaptr
devCrossNet
TypeScript
Code
63
206
import { IAppState } from './state'; export interface IAppMutations { CHANGE_LOCALE(state: IAppState, locale: string): void; SET_COOKIE_CONSENT_VERSION(state: IAppState, version: string): void; CHANGE_MENU_POSITION(state: IAppState): void; } export const AppMutations: IAppMutations = { CHANGE_LOCALE: (state, locale) => { state.locale = locale; }, SET_COOKIE_CONSENT_VERSION: (state, version) => { state.cookieConsentVersion = version; }, CHANGE_MENU_POSITION: (state) => { state.menuPosition = state.menuPosition === 'right' ? 'left' : 'right'; }, };
29,870
https://github.com/InternetLojas/new_ecograph/blob/master/resources/views/layouts/includes/boxes/forms/form_basket.blade.php
Github Open Source
Open Source
MIT
null
new_ecograph
InternetLojas
PHP
Code
32
150
{!! Form::open(array( 'method' => 'post', 'name'=>'basket', 'id'=>'basket', 'role' => 'Form')) !!} <div class="form-group text"> @foreach($post_inputs as $key=>$valor) <input id="{{$key}}" type="hidden" value="{{$valor}}" name="{{$key}}" class="form-control"> @endforeach <input id="produto_id" type="hidden" value="" name="produto_id" class="form-control"> </div> {!!Form::close()!!}
5,366
https://github.com/rajankaneria/escapecity/blob/master/application/views/home.php
Github Open Source
Open Source
MIT
null
escapecity
rajankaneria
PHP
Code
1,303
5,556
<!--=========================== main slider ========================--> <div id="mainSlider" class="carousel carousel-slider center z-depth-1" data-indicators="true"> <!--=======================slider for North India tours=======================--> <div class="carousel-item white-text" href="<?php echo base_url();?>details"> <div class="row"> <div class="col s4 m4"> <div class="location-title">Roopkund Trek</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/roopkund.jpg"></div> <div class="col s4 m4"> <div class="location-title">Leh Ladakh</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/Ladakh.jpg"></div> <div class="col s4 m4"> <div class="location-title"> Valley of Flowers</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/flowers.jpg"></div> </div> <div class="main-slider-item-title">North India</div> </div> <!--=======================slider for East India==============================--> <div class="carousel-item amber white-text" href="<?php base_url();?>dang"> <div class="row"> <div class="col s4 m4"> <div class="location-title"> Beyul Pamako Trek</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/beyul.jpg"></div> <div class="col s4 m4"> <div class="location-title"> The Bailey Trail Trek</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/bailey.jpg"></div> <div class="col s4 m4"> <div class="location-title">Lapti Valley Trek</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/lapti.jpg"></div> </div> <div class="main-slider-item-title">East India</div> </div> <!--=======================slider for West India================================--> <div class="carousel-item green white-text" href="<?php base_url();?>mulher"> <div class="row"> <div class="col s4 m4"> <div class="location-title">Bhimashankar</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/bhimashnkar.jpg"></div> <div class="col s4 m4"> <div class="location-title"> Lohagad</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/Lohagad.jpg"></div> <div class="col s4 m4"> <div class="location-title">Harihar Trek</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/harihar.jpg"></div> </div> <div class="main-slider-item-title">West India</div> </div> <!--=======================slider for South India============================--> <div class="carousel-item blue white-text" href="<?php base_url();?>songadh"> <div class="row"> <div class="col s4 m4"> <div class="location-title">Coorg, Karnataka,</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/coorg.JPG"></div> <div class="col s4 m4"> <div class="location-title">Munnar</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/Munnar.jpg"></div> <div class="col s4 m4"> <div class="location-title"> Kodachadri, Karnataka</div> <div class="parallax-overlay"></div><img src="<?php echo base_url(); ?>html/images/kodachadri.jpg"></div> </div> <div class="main-slider-item-title">South India</div> </div> </div> <!--=======================End of main slider================================--> <!--=======================START MAIN tours CARD ===========================--> <div class="parallax-container home_parallax z-depth-1" style="margin-top: 100px;"> <div class="parallax"> <div class="parallax-overlay"></div> <img src="<?php echo base_url(); ?>html/images/back_img.jpg"> </div> <!--=====================start container=====================================--> <div class="container"> <div class="carousel-fixed-item center"> <div class="page-sub-title">Take a Look at Our</div> <div class="page-main-title">MOST POPULAR TOURS</div> </div> <div id="toursSlider" class="carousel carousel-slider center hide-on-med-and-down" data-indicators="true"> <!--======================1.North India ==================================--> <div class="carousel-item carousel_card hide-on-med-and-down" href="#one!"> <div class="row"> <!--========================first card========================================--> <?php foreach ($tourDetails as $key => $tourRow) { ?> <div class="col s4 card_panel"> <div class="card"> <div class="card-image"> <img src="<?php echo base_url(); ?>html/images/<?php echo $tourRow['home_banner']; ?>" class="card-image"> </div> <div class="card-content"> <h6 class="card-title"><?php echo $tourRow['name']; ?></h6> <h5 class="card-sub-title"><?php echo $tourRow['tour_name']; ?></h5> <p><?php echo substr($tourRow['detail'],0,135)."...."; ?></p> <a class="waves-effect waves-light btn grey darken-4 lighten-2" href="<?php echo base_url();?>tour/id/<?php echo $tourRow['id']; ?>">Details</a> </div> </div> </div> <?php } ?> </div> </div> <!--===============================END North India=================================--> </div> <!-- Ende Deskotop tour slider --> <!-- Start here mobile responsive single slider --> <div class="row"> <div id="mobileSlider" class="carousel carousel-slider-mobile center"> <div class="carousel-item col s12" href="#one!" height="500"> <div class="tourBox-area"> <div class="imagesBox-area"> <img src="<?php echo base_url(); ?>html/images/Roopkundcard.jpg" class="responsive-img"> </div> <div class="tourContent-area"> <div class="tourTitle-name"> <h5>Roopkund Trek</h5> </div> <div class="tourSubtitle-area"> <p>North India</p> </div> <div class="tourDescripton-area"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="tourDetails-button"> <a class="waves-effect tourdetails-black-btn waves-light btn">Details</a> </div> </div> </div> </div> <div class="carousel-item col s12" href="#two!"> <div class="tourBox-area"> <div class="imagesBox-area"> <img src="<?php echo base_url(); ?>html/images/leh.jpg" class="responsive-img"> </div> <div class="tourContent-area"> <div class="tourTitle-name"> <h5>Leh Ladakh</h5> </div> <div class="tourSubtitle-area"> <p>North India</p> </div> <div class="tourDescripton-area"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> <div class="tourDetails-button"> <a class="waves-effect tourdetails-black-btn waves-light btn">Details</a> </div> </div> </div> </div> <div class="carousel-item col s12" href="#three!"> <div class="tourBox-area"> <div class="imagesBox-area"> <img src="<?php echo base_url(); ?>html/images/rishikes.jpg" class="responsive-img"> </div> <div class="tourContent-area"> <div class="tourTitle-name"> <h5>Rishikesh, Shivpuri</h5> </div> <div class="tourSubtitle-area"> <p>North India</p> </div> <div class="tourDescripton-area"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> <div class="tourDetails-button"> <a class="waves-effect tourdetails-black-btn waves-light btn">Details</a> </div> </div> </div> </div> </div> </div> <!-- Over here mobile responsive single slider --> </div> <!--============================END container====================================--> </div> <!--============================END MAIN tours card ===================================--> <!-- ================ Find Tour By Months Start Here =================== --> <div class="row white z-depth-1" style="margin-top:0px; overflow: hidden;"> <div class="tbm-title"> <h5>Find a Tour by <span>Month</span></h5> </div> <div class="tourByMonth-area"> <div class="carousel carousel-slider tmb-slider center" data-indicators="true"> <?php $output = [ array_slice($allMonthDetails,0,4), array_slice($allMonthDetails,3,4), array_slice($allMonthDetails,7,4) ]; ?> <?php foreach($output as $key=>$monthArray){ ?> <div class="carousel-item" href="#one!"> <div class="row"> <?php foreach($monthArray as $monthKey=>$monthRow){ $monthNum = $monthRow['month']; $monthName = date("F", mktime(0, 0, 0, $monthNum, 10));?> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/<?php echo $monthNum; ?>/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/tours/<?php echo $monthRow['image']; ?>" alt="<?php echo base_url(); ?>html/images/<?php echo $monthRow['image']; ?> not found" /> <figcaption> <div> <h4><?php echo $monthName; ?></h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> <?php } ?> </div> </div> <?php } ?> <!-- <div class="carousel-item" href="#two!"> <div class="row"> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/January/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" alt="sample84" /> <figcaption> <div> <h4>May</h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/January/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" alt="sample84" /> <figcaption> <div> <h4>June</h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/January/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" alt="sample84" /> <figcaption> <div> <h4>July</h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/January/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" alt="sample84" /> <figcaption> <div> <h4>August</h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> </div> </div> <div class="carousel-item " href="#three!"> <div class="row"> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/January/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" alt="sample84" /> <figcaption> <div> <h4>September</h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/January/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" alt="sample84" /> <figcaption> <div> <h4>October</h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/January/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" alt="sample84" /> <figcaption> <div> <h4>November</h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> <div class="col m3"> <div class="box" onclick="window.location.href='<?php echo base_url(); ?>tour/tourByMonth/January/'"> <figure class="snip1445"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" alt="sample84" /> <figcaption> <div> <h4>December</h4> </div> </figcaption> <a href="#"></a> </figure> </div> </div> </div> </div> --> </div> </div> </div> <!-- ================ Find Tour By Months Over Here =================== --> <!-- ==================== Latest Post ================= --> <div class="row"> <div class="col s12 m6"> <h5 class="latest-blog-title">Latest <span>Blog</span></h5> <div class="blog-item"> <div class="blog-image-container"><img src="<?php echo base_url(); ?>html/images/blog/<?php echo $latestBlog["image"]; ?>" class="responsive-img"></div> <div class="blog-details"> <div class="blog-main-title"><?php echo $latestBlog["title"]; ?></div> <div style="overflow: hidden;"> <div class="blog-date">21st September, 2017</div> <div class="blog-author">- by <span><?php echo "John Doe"; ?></span></div> </div> <p class="blog-content"><?php echo substr($latestBlog["details"],0,500); ?>...</p> </div> </div> <!-- <div class="blog-area z-depth-1"> <div class="blog-bg-img"> <img src="<?php echo base_url(); ?>html/images/blog/<?php echo $latestBlog["image"]; ?>" class="responsive-img"> </div> <div class="blog-description"> <h5 class="blog-title"><?php echo $latestBlog["title"]; ?></h5> <p class="blog-desc"><?php echo substr($latestBlog["details"],0,700); ?>...</p> <div class="readMore-btn"><center><button class="btn btn-black">Read More</button></center></div> </div> </div> --> </div> <div class="col s12 m6"> <h5 class="latest-blog-title">Latest <span>Testimonials</span></h5> <div class="Testimonials-area"> <div class="carousel carousel-slider testimoni-slider center" data-indicators="true"> <!-- <div class="carousel-item red white" href="#one!"> <h2 class="testimonials-name">Firts Name</h2> <div class="carousel-item red white" href="#one!"> <div class="testimonials-img"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" class="testi-img"> <div class="testi-name"> <p>Testimonial one</p> </div> </div> <div class="user-testimonials"> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> </div> </div> <div class="carousel-item red white" href="#one!"> <div class="testimonials-img"> <img src="<?php echo base_url(); ?>html/images/image-holder.jpg" class="testi-img"> </div> <div class="user-testimonials"> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> </div> </div> --> <?php foreach($testDetails as $key => $testRow){?> <div class="carousel-item" href="#one!"> <div class="testimonials-img"> <img src="<?php echo base_url(); ?>html/images/testimonials/<?php echo $testRow['image'];?>" class="testi-img"> </div> <div class="testimonial-title"><?php echo $testRow['title'];?></div> <div class="user-testimonials"> <p> <?php echo $testRow['details'];?> </p> </div> </div> <?php } ?> </div> </div> </div> </div>
4,810
https://github.com/xiaolong99999/supermallto/blob/master/src/components/content/mainTabbar/MainTabBar.vue
Github Open Source
Open Source
MIT
null
supermallto
xiaolong99999
Vue
Code
95
621
<template> <tab-bar> <tab-bar-item path="/home"> <template v-slot:item-icon> <img src="../assets/img/tabbar/首页.svg"> </template> <template v-slot:item-icon-active> <img src="../assets/img/tabbar/首页_active.svg"> </template> <template v-slot:item-text> <div>首页</div> </template> </tab-bar-item> <tab-bar-item path="category"> <template v-slot:item-icon> <img src="../assets/img/tabbar/分类.svg"> </template> <template v-slot:item-icon-active> <img src="../assets/img/tabbar/分类_active.svg"> </template> <template v-slot:item-text> <div>分类</div> </template> </tab-bar-item> <tab-bar-item path="/cart"> <template v-slot:item-icon> <img src="../assets/img/tabbar/购物车.svg"> </template> <template v-slot:item-icon-active> <img src="../assets/img/tabbar/购物车_active.svg"> </template> <template v-slot:item-text> <div>购物车</div> </template> </tab-bar-item> <tab-bar-item path="/profile"> <template v-slot:item-icon> <img src="../assets/img/tabbar/我的.svg"> </template> <template v-slot:item-icon-active> <img src="../assets/img/tabbar/我的_actice.svg"> </template> <template v-slot:item-text> <div>我的</div> </template> </tab-bar-item> </tab-bar> </template> <script> import TabBar from '../components/tabbar/TabBar' import TabBarItem from '../components/tabbar/TabBarItem' export default { name: "MainTabBar", components:{ TabBar, TabBarItem } } </script> <style scoped> </style>
35,275
https://github.com/NurbekGithub/react-boilerplate/blob/master/app/lib/MaterialTable/index.js
Github Open Source
Open Source
MIT
null
react-boilerplate
NurbekGithub
JavaScript
Code
88
248
import React, { useContext } from "react"; import MuiRemoteTable from "./MuiRemoteTable"; import { TableContext, registerTable } from "../../globalContexts/TableContext"; function MuiTable({ query = {}, remote = true, ...rest }) { const initialState = { // controlled selectedRows: [], isAllSelected: false, isIndeterminated: false, // uncontrolled data: [], total: 0, page: 0, per_page: 20, search: "", propFilters: {}, isLoading: false, order: "", // 'desc' | 'asc' | '' orderBy: "", ...query }; const dispatch = useContext(TableContext)[1]; dispatch(registerTable(rest.tableName, initialState)); if (remote) { return <MuiRemoteTable {...rest} initialState={initialState} />; } } export default React.memo(MuiTable);
37,403
https://github.com/DennyLindberg/Plant-Generator/blob/master/source/core/utilities.cpp
Github Open Source
Open Source
MIT
2,022
Plant-Generator
DennyLindberg
C++
Code
103
341
#include "utilities.h" #include <fstream> std::string TimeString(double time) { int seconds = int(time); int minutes = seconds / 60; int hours = minutes / 60; double decimals = time - double(seconds); return std::to_string(hours) + "h " + std::to_string(minutes % 60) + "m " + std::to_string(seconds % 60) + "." + std::to_string(int(decimals*10.0)) + "s"; } std::string FpsString(double deltaTime) { if (deltaTime == 0) { return "Inf"; } else { return std::to_string(int(round(1.0 / deltaTime))); } } bool LoadText(std::filesystem::path filePath, std::string& output) { output = ""; if (!std::filesystem::exists(filePath)) return false; std::ifstream InputFileStream(filePath.c_str()); if (InputFileStream && InputFileStream.is_open()) { output.assign((std::istreambuf_iterator<char>(InputFileStream)), std::istreambuf_iterator< char >()); return true; } return false; }
8,918
https://github.com/bellmit/low-code/blob/master/nodeModules/nti-formula-helper/src/packages/FormulaHelp/components/formulaPanel.vue
Github Open Source
Open Source
MIT
2,021
low-code
bellmit
Vue
Code
215
986
<template> <div class="full-panel"> <div class="full-panel_head">公式</div> <topTool @filter="handleInputFilter" /> <el-collapse accordion class="with-padding full-panel_body" style="padding: 0;"> <el-collapse-item v-for="item in list" :key="item.name" :name="item.name" > <span slot="title"> <el-tooltip :open-delay="500" content="插入公式"> <el-button type="text" size="mini" @click.stop="handleInsert(item)" style="margin-right: 5px;"> <i class="el-icon el-icon-plus" /> </el-button> </el-tooltip> {{item.expression}} </span> <el-row :gutter="20"> <el-col :span="8"> <h4>{{ item.name }}</h4> </el-col> <el-col :span="16"> <b v-if="item.title">{{item.title}}。</b> {{ item.desc }} </el-col> </el-row> <el-row :gutter="20" v-if="item.paramList"> <el-col :span="24"> <h4 style="padding-top: 5px">参数</h4> </el-col> <div v-for="p in item.paramList" :key="p.name"> <el-col :span="8">[{{ p.type }}]&nbsp;{{ p.name }}</el-col> <el-col :span="16">{{ p.desc }}</el-col> </div> </el-row> <el-row :gutter="20" v-if="item.return"> <el-col :span="24"> <h4 style="padding-top: 5px">返回结果</h4> </el-col> <el-col :span="8">{{ item.return.type }}</el-col> <el-col :span="16">{{ item.return.desc }}</el-col> </el-row> <el-row :gutter="20" v-if="item.demo"> <el-col :span="24"> <h4 style="padding-top: 5px">示例</h4> </el-col> <el-col :span="24">{{ item.demo }}</el-col> </el-row> </el-collapse-item> </el-collapse> </div> </template> <script> import topTool from './topTool.vue' export default { components: { topTool, }, props: { data: { type: Array, default: () => [] } }, data() { return { list: '', } }, watch: { data: { immediate: true, handler(data) { this.list = data } }, }, methods: { handleInputFilter(text) { this.list = this.filterList(text) }, filterList(value, key) { const { data, } = this console.log(value) if (!value) return data const upperValue = value.toUpperCase() return data.filter(item => { return (`${item.name || ''}##${item.title || ''}`) .toUpperCase() .indexOf(upperValue) !== -1 }) }, handleInsert(item) { this.$emit('insert', `${item.name}()`) }, }, } </script>
45,646
https://github.com/samuellundin/Agiletasks/blob/master/client/src/app/manage-projects/manage-navbar/manage-navbar.component.ts
Github Open Source
Open Source
MIT
null
Agiletasks
samuellundin
TypeScript
Code
28
103
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-manage-navbar', templateUrl: './manage-navbar.component.html', styleUrls: ['./manage-navbar.component.css'] }) export class ManageNavbarComponent implements OnInit { constructor() { } ngOnInit() { } }
1,485
https://github.com/jademperor/api-proxier/blob/master/cmd/proxier.go
Github Open Source
Open Source
MIT
2,019
api-proxier
jademperor
Go
Code
120
399
package main import ( "flag" "log" "os" "github.com/jademperor/api-proxier/internal/engine" "github.com/jademperor/api-proxier/internal/logger" "github.com/jademperor/common/pkg/utils" ) var ( addr = flag.String("addr", ":9000", "http server listen on") logpath = flag.String("logpath", "./logs", "log files folder") debug = flag.Bool("debug", false, "open debug") plugins utils.StringArray etcdAddrs utils.StringArray ) func main() { flag.Var(&etcdAddrs, "etcd-addr", "addr of etcd store") flag.Var(&plugins, "plugin", "plugin extension format like: [pluginName:plugin.so:/path/to/config]") flag.Parse() // valid command line arguments if len(etcdAddrs) == 0 { log.Println("etcd-addr must be set one or more values") os.Exit(-1) } // init logger configuration logger.Init(*logpath, *debug) // new engine to run e, err := engine.New(etcdAddrs, plugins, *debug) if err != nil { log.Fatal(err) } // run the server and serve with http request if err := e.Run(*addr); err != nil { log.Fatal(err) } }
28,812