code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
/**
* @param {Object} options
* @param {Number} options.size Max size of array to return
* @param {Number} options.page Location in pagination
* @param {String} options.first_name first name of user
* @param {String} options.last_name last name of user
* @param {Boolean} options.is_collaborator is `User`a collaborator?
* @param {Boolean} options.is_creator is `User`a creator?
* @param {String} options.city city location of user
* @param {String} options.state state location of user
* @param {Array} options.university_ids universities a `User`is associated with
* @param {String} options.project_id project_id the `User`is associated with
* @param {String} options.created_date date the `User`was created
* @param {String} options.modified_date date the `User`was modified
* @param {Array} options.keywords keyword
* @param {Array} options.skills skills to search for
* @param {Function} callback
*/
import models from '../../../../../model';
import bcrypt from 'bcrypt';
const Grant = models.grant;
const Post = models.post;
const Project = models.project;
const Review = models.review;
const Skill = models.skill;
const University = models.University;
const User = models.User;
const UserSkill = models.userkSkill;
export function getUsers (options, callback) {
// Implement you business logic here...
}
/**
* @param {Object} options
* @param {String} options.university_id ID of 'User' to fetch
* @param {Number} options.max max num of 'User' to fetch
* @param {Number} options.page page in pagination
* @param {Function} callback
*/
export function getUsersByUniversityId (options, callback) {
// Implement you business logic here...
}
/**
* @param {Object} options
* @param {String} options.project_id ID of 'Project' to fetch
* @param {Number} options.max max num of 'User' to fetch
* @param {Number} options.page page in pagination
* @param {Function} callback
*/
export function getUsersByProjectId (options, callback) {
// Implement you business logic here...
}
/**
* @param {Object} options
* @param {String} options.created_date Date that `User` object was created
* @param {Function} callback
*/
export function getUsersByCreatedDate (options, callback) {
// Implement you business logic here...
}
/**
* @param {Object} options
* @param {String} options.created_date Date that `User` object was created
* @param {Function} callback
*/
export function getUsersByCreatedDateForm (options, callback) {
// Implement you business logic here...
}
/**
* @param {Object} options
* @param {String} options.modified_date Date that `User` object was modified
* @param {Function} callback
*/
export function getUsersByModifiedDate (options, callback) {
// Implement you business logic here...
}
/**
* @param {Object} options
* @param {String} options.modified_date Date that `User` object was modified
* @param {Function} callback
*/
export function getUsersByModifiedDateForm (options, callback) {
// Implement you business logic here...
}
/**
* @param {Object} options
* @param {Array} options.keywords Keywords when searching for user
* @param {Function} callback
*/
export function getUsersByKeywords (options, callback) {
// Implement you business logic here...
}
/**
* @param {Object} options
* @param {Array} options.skills Skills when searching for user
* @param {Function} callback
*/
export function getUsersBySkills (options, callback) {
// Implement you business logic here...
}
| ArmRay/Arm_Ray_App | server/instances/search/src/api/services/Users.js | JavaScript | gpl-3.0 | 3,624 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.preference2.cts;
import android.preference2.cts.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class CustomPreference extends Preference {
protected boolean mOnPrepareCalled;
public CustomPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CustomPreference(Context context) {
this(context, null, 0);
}
public CustomPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
private void init(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.CustPref);
setTitle(a.getString(R.styleable.CustPref_title));
setIcon(a.getDrawable(R.styleable.CustPref_icon));
}
@Override
protected boolean callChangeListener(Object newValue) {
return super.callChangeListener(newValue);
}
@Override
protected Preference findPreferenceInHierarchy(String key) {
return super.findPreferenceInHierarchy(key);
}
@Override
protected boolean getPersistedBoolean(boolean defaultReturnValue) {
return super.getPersistedBoolean(defaultReturnValue);
}
@Override
protected float getPersistedFloat(float defaultReturnValue) {
return super.getPersistedFloat(defaultReturnValue);
}
@Override
protected int getPersistedInt(int defaultReturnValue) {
return super.getPersistedInt(defaultReturnValue);
}
@Override
protected long getPersistedLong(long defaultReturnValue) {
return super.getPersistedLong(defaultReturnValue);
}
@Override
protected String getPersistedString(String defaultReturnValue) {
return super.getPersistedString(defaultReturnValue);
}
@Override
protected void notifyChanged() {
super.notifyChanged();
}
@Override
protected void notifyHierarchyChanged() {
super.notifyHierarchyChanged();
}
@Override
protected void onAttachedToActivity() {
super.onAttachedToActivity();
}
@Override
protected void onAttachedToHierarchy(PreferenceManager preferenceManager) {
super.onAttachedToHierarchy(preferenceManager);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
}
@Override
protected void onClick() {
super.onClick();
}
@Override
protected View onCreateView(ViewGroup parent) {
return super.onCreateView(parent);
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return super.onGetDefaultValue(a, index);
}
@Override
protected void onPrepareForRemoval() {
super.onPrepareForRemoval();
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
}
@Override
protected Parcelable onSaveInstanceState() {
return super.onSaveInstanceState();
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
super.onSetInitialValue(restorePersistedValue, defaultValue);
}
@Override
protected boolean persistBoolean(boolean value) {
return super.persistBoolean(value);
}
@Override
protected boolean persistFloat(float value) {
return super.persistFloat(value);
}
@Override
protected boolean persistInt(int value) {
return super.persistInt(value);
}
@Override
protected boolean persistLong(long value) {
return super.persistLong(value);
}
@Override
protected boolean persistString(String value) {
return super.persistString(value);
}
@Override
protected boolean shouldPersist() {
return super.shouldPersist();
}
}
| wiki2014/Learning-Summary | alps/cts/tests/tests/preference2/src/android/preference2/cts/CustomPreference.java | Java | gpl-3.0 | 4,826 |
package com.idega.core.user.data;
import java.sql.SQLException;
import com.idega.data.GenericEntity;
/**
* Title: User
* Description:
* Copyright: Copyright (c) 2001
* Company: idega.is
* @author 2000 - idega team - <a href="mailto:gummi@idega.is">Guðmundur Ágúst Sæmundsson</a>
* @version 1.0
*/
public class GenderBMPBean extends com.idega.data.GenericEntity implements com.idega.core.user.data.Gender {
public static final String NAME_MALE="male";
public static final String NAME_FEMALE="female";
public GenderBMPBean() {
super();
}
public GenderBMPBean(int id) throws SQLException {
super(id);
}
public void initializeAttributes() {
this.addAttribute(this.getIDColumnName());
this.addAttribute(getNameColumnName(),"Nafn",true,true,"java.lang.String");
this.addAttribute(getDescriptionColumnName(),"Description",true,true,"java.lang.String",1000);
getEntityDefinition().setBeanCachingActiveByDefault(true);
}
public String getEntityName() {
return "ic_gender";
}
public void insertStartData() throws SQLException {
Gender male = ((com.idega.core.user.data.GenderHome)com.idega.data.IDOLookup.getHomeLegacy(Gender.class)).createLegacy();
male.setName(NAME_MALE);
male.insert();
Gender female = ((com.idega.core.user.data.GenderHome)com.idega.data.IDOLookup.getHomeLegacy(Gender.class)).createLegacy();
female.setName(NAME_FEMALE);
female.insert();
}
public static String getNameColumnName(){
return "name";
}
public static String getDescriptionColumnName(){
return "description";
}
public void setName(String name){
this.setColumn(getNameColumnName(),name);
}
public void setDescription(String description){
this.setColumn(getDescriptionColumnName(),description);
}
public String getName(){
return this.getStringColumnValue(getNameColumnName());
}
public String getDescription(){
return this.getStringColumnValue(getDescriptionColumnName());
}
public Gender getStaticInstance(){
return (Gender)GenericEntity.getStaticInstance(Gender.class);
}
}
| idega/com.idega.core | src/java/com/idega/core/user/data/GenderBMPBean.java | Java | gpl-3.0 | 2,124 |
<?php
namespace Core\Render;
use Core\Models\Content;
class TypeImage extends AbstractType
{
public function render()
{
if ($this->getContent()->getContent()) {
$info = json_decode($this->getContent()->getContent(), true);
return sprtinf('<img src="%s" />', $info['src']);
}
}
} | marcj/kryn.cms-standalone-very-old | src/Core/Render/TypeImage.php | PHP | gpl-3.0 | 333 |
<?php
/*
* Copyright Alexander Beider and Stephen P. Morse, 2008
* Copyright Olegs Capligins, 2013-2016
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* It is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License.
* If not, see <http://www.gnu.org/licenses/>.
*
*/
return [
0 => [
"/y/",
"/q/",
"/x/",
"/aj/",
"/ej/",
"/oj/",
"/uj/",
],
1 => [
"/uu/",
"/sj$/",
"/^sj/",
"/oe/",
"/[ln]h[aou]/",
"/^wr/",
],
];
| Haran/BMDMSoundex | library/bm/languages/gen/dutch/recognition.php | PHP | gpl-3.0 | 987 |
// These values are updated every 5 minutes
// using site_stats table from all wikis replicated in
// WMF Labs databases.
// Families updated include ["wikibooks", "wikipedia", "wiktionary", "wikimedia", "wikiquote", "wikisource", "wikinews", "wikiversity", "commons", "wikispecies", "wikidata", "wikivoyage"]
// More questions? emijrp AT gmail DOT com
var timenow = new Date().getTime();
var period = 20; // period update in miliseconds
var spliter = ",";
var spliter_r = new RegExp(/(^|\s)(\d+)(\d{3})/);
function init() {
adjustSizes();
var lang = "";
var header = "";
var donate = "";
var f11 = "";
var author = "";
if (navigator.systemLanguage) {
lang = navigator.systemLanguage;
}else if (navigator.userLanguage) {
lang = navigator.userLanguage;
}else if(navigator.language) {
lang = navigator.language;
}else {
lang = "en";
}
if (lang.length>2) { lang=lang.substring(0,2); }
switch(lang){
case "example":
header='<a href="http://www.wikimedia.org"></a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia"></a>';
f11='';
author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "af":
header='Totale wysigings in alle <a href="http://www.wikimedia.org">Wikimedia-projekte</a>:';
spliter=' ';
donate="<a href='http://wikimediafoundation.org/wiki/Skenk'>Skenk 'n donasie aan die Wikimedia-stigting</a>"; //be careful with 'n
f11='Druk op F11 vir volskerm';
author='Ontwikkel deur <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (inspirasie deur <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "als":
header='Gsamtaazahl Bearbeitige uff de <a href="http://www.wikimedia.org">Wikimedia-Brojäkt:</a>';
spliter=' ';
donate="<a href='http://wikimediafoundation.org/wiki/Finanzielli_Hilf'>Understütz d'Wikimedia Foundation</a>"; //be careful with d'
f11='Vollbild: F11';
author='Gschribe vum <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (uff Basis vu <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "an":
header='Edicions totals en <a href="http://www.wikimedia.org">prochectos Wikimedia</a>:';
spliter='.';
donate="<a href='http://wikimediafoundation.org/wiki/Support_Wikipedia'>Fer una donación t'a Fundación Wikimedia</a>"; //be careful with t'
f11='Pretar F11 ta veyer en pantalla completa';
author='Desembolicau por <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirau por <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "ar":
header='مجموع التعديلات في <a href="http://www.wikimedia.org">مشاريع ويكيميديا</a>:';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/جمع_تبرعات">تبرع لمؤسسة ويكيميديا</a>';
f11='للشاشة الكاملة اضغط F11';
author='من تطوير <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (ملهمة من <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "az":
header='<a href="http://www.wikimedia.org">Wikimedia layihəsində </a> redaktələrin ümumi sayı:';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/Bağışlar">Wikimedia Foundation təşkilatına ianələrin göndərilməsi</a>';
f11='Ekranın tam açılması üçün F11 düyməsini basın';
author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> tərəfindən (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> dəstəyi ilə) işlənmişdir';
break;
case "be":
header='Агулам правак у <a href="http://www.wikimedia.org">праектах Фундацыі «Вікімэдыя»</a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Ахвяруйце Фундацыі Вікімэдыя</a>';
f11='Націсьніце F11 для поўнаэкраннага прагляду';
author='Распрацаваў <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (ідэя <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "bg":
header='Общ брой редакции в <a href="http://www.wikimedia.org">проектите на Уикимедия</a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Подкрепете с дарение Фондация Уикимедия</a>';
f11='Натиснете F11 за показване на голям екран';
author='Разработено от <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (вдъхновено от <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "bn":
header='<a href="http://www.wikimedia.org">উইকিমিডিয়ার বিভিন্ন প্রকল্পে</a> সর্বমোট সম্পাদনার সংখ্যা:';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">উইকিমিডিয়া ফাউন্ডেশনে দান করুন</a>';
f11='সম্পূর্ন স্ক্রিন জুড়ে দেখতে হলে F11 চাপুন';
author='এই কাউন্টারটি তৈরী করেছেন <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> এর অনুপ্রেরণায়)';
break;
case "br":
header='Niver hollek a gemmoù er <a href="http://www.wikimedia.org">raktresoù Wikimedia</a> :';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Donezoniñ da Ziazezadur Wikimedia</a>';
f11='Pouezit war F11 evit ar mod skramm leun';
author='Diorroet gant <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Awenet gant <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "bs":
header='Ukupne izmjene u svim <a href="http://www.wikimedia.org">Wikimedia projektima</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Donirajte Wikimedia Fondaciji</a>';
f11='Pritisnite F11 za prikaz preko cijelog ekrana';
author='Razvio korisnik <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspiriran od strane <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "ca":
header='Edicions entre tots els <a href="http://www.wikimedia.org">projectes de Wikimedia</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Donatius">Dona a la Fundació Wikimedia</a>';
f11='Pantalla completa pulsant F11';
author='Desarrollat per <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirat en <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "ceb":
header='Mga tibuok kausaban sa <a href="http://www.wikimedia.org">mga proyekto sa Wikimedya</a>:';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Idonar sa Wikimedia Foundation</a>';
f11='Tuploka ang F11 aron mapuno sa tabil';
author='Gipalambo ni <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Nadasig sa <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "cs":
header='Celkový počet editací v <a href="http://www.wikimedia.org">projektech nadace Wikimedia</a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Sponzorství">Podpořte Wikimedia Foundation</a>';
f11='Stisknutím klávesy F11 zobrazíte stránku na celou obrazovku';
author='Vyvinul <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (inspirováno stránkami <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "cy":
header='Cyfanswm yr holl olygiadau ym <a href="http://www.wikimedia.org">mhrosiectau Wikimedia</a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Cyfrannwch at Sefydliad Wikimedia</a>';
f11='Gwasgwch F11 am sgrîn lawn';
author='Datblygwyd gan <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Ysbrydolwyd gan <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "da":
header='Samlet antal rettelser på tværs af alle <a href="http://www.wikimedia.org">Wikimedia-projekter</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Indsamling">Giv et bidrag til Wikimedia Foundation</a>';
f11='Tryk F11 for fuldskærmsvisning';
author='Udviklet af <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspireret af <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "de":
header='Gesamtzahl der Bearbeitungen in <a href="http://www.wikimedia.org">den Wikimedia-Projekten</a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Spenden">Spende an die Wikimedia Foundation</a>';
f11='Drücke F11 für die Vollbild-Anzeige';
author='Entwickelt von <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspiriert durch <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "el":
header='Συνολικές επεξεργασίες στα <a href="http://www.wikimedia.org">εγχειρήματα του Wikimedia</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Κάντε δωρεά στο Ίδρυμα Wikimedia</a>';
f11='Πατήστε F11 για πλήρη οθόνη';
author='Αναπτύχθηκε από τον <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Εμπνευσμένο από το <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "eo":
header='Totala nombro de redaktoj en <a href="http://www.wikimedia.org">Vikimediaj projektoj</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Monkolektado">Donaci al Fondaĵo Vikimedio</a>';
f11='Premu F11 por plenekrana modo';
author='Kreita de <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirita de <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "es":
header='Ediciones entre todos los <a href="http://www.wikimedia.org">proyectos Wikimedia</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Donaciones">Dona a la Fundación Wikimedia</a>';
f11='Pantalla completa pulsando F11';
author='Desarrollado por <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirado en <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "et":
header='<a href="http://www.wikimedia.org">Wikimedia projektides</a> tehtud redigeerimiste koguarv:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Anneta Wikimedia sihtasutusele</a>';
f11='Täisekraani jaoks vajuta F11';
author='Kasutajalt <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> eeskujul)';
break;
case "eu":
header='<a href="http://www.wikimedia.org">Wikimedia proiektuetan</a> egindako eguneraketak guztira:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Dohaintzak">Wikimedia Foundazioari dohaintza egin</a>';
f11='F11 sakatu pantaila osoan erakusteko';
author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a>-ek garatua (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>-ek inspiratuta)';
break;
case "fa":
header='مجموع ویرایشها در <a href="http://www.wikimedia.org">پروژه ویکیمدیا</a>:';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">کمک مالی به بنیاد ویکیمدیا</a>';
f11='را برای نمایش تمام صفحه فشار دهید F11کلید';
author='گسترشیافته بوسیله <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (با الهام از <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "fr":
header="Nombre total d'éditions dans les <a href='http://www.wikimedia.org'>projets Wikimedia</a>:"; // be careful with d'éditions
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Faire_un_don">Donner à la Wikimedia Foundation</a>';
f11='Appuyez sur F11 pour passer en plein écran';
author='Développé par <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspiré par <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "gu":
header='<a href="http://www.wikimedia.org">વિકિમીડિયા પરિયોજના </a> માં કુલ સંપાદનો';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">વિકિમીડિયા ફાઉન્ડેશનને દાન આપો</a>';
f11='ફુલ સ્ક્રીન માટે F11 દબાવો';
author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp ધ્વારા વિકસિત </a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7 ધ્વરા પ્રેરિત </a>)';
break;
case "hi":
header='<a href="http://www.wikimedia.org">विकिमीडिया परियोजना</a> में कुल संपादन:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Donate/hi">विकिमीडिया फ़ौंडेशन को दान करें। </a>';
f11='पूर्ण स्क्रीन के लिए ऍफ़११ [F11] दबाएँ।';
author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">एमिजआरपी [emijrp]</a> द्वारा विकसित (<a href="http://www.7is7.com/software/firefox/partycounter.html">७इस७ [7is7]</a> द्वारा प्रेरित।)';
break;
case "hu":
header='<a href="http://www.wikimedia.org">A Wikimédia projektek</a> együttes szerkesztésszáma:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia/hu">Támogasd a Wikimédia Alapítványt</a>';
f11='Teljes képernyős mód: F11';
author='Készítette: <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> ötlete alapján)';
break;
case "id":
header='Jumlah suntingan di <a href="http://www.wikimedia.org">proyek Wikimedia</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Penggalangan_dana">Menyumbang untuk Yayasan Wikimedia</a>';
f11='Tekan F11 untuk tampilan layar penuh';
author='Dikembangkan oleh <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Terinspirasi dari <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "it":
header='Modifiche totali nei <a href="http://www.wikimedia.org">progetti Wikimedia</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Donazioni">Fai una donazione a Wikimedia Foundation</a>';
f11='Premi F11 per passare a schermo intero';
author='Sviluppato da <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (ispirato da <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "ja":
header='<a href="http://www.wikimedia.org">ウィキメディア・プロジェクト</a>の総編集回数';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">ウィキメディア財団に寄付</a>';
f11='F11キーでフルスクリーン表示';
author='開発:<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (原案:<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "kl":
header='Tamakkiisumik amerlassutsit aaqqissuussinerni <a href="http://www.wikimedia.org">Wikimedia suliniutaani</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Wikimedia suliniutaani tunissuteqarit</a>';
f11='F11 tooruk tamaat saqqummissagukku';
author='Siuarsaasuuvoq <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Peqatigalugu <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "ko":
header='<a href="http://www.wikimedia.org">위키미디어 재단에서 운영하는 프로젝트</a>의 총 편집 횟수:';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">위키미디어 재단에 기부하기</a>';
f11='F11 키를 누르면 전체 화면 모드로 전환합니다';
author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a>이 만듬 (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>에서 영감을 얻음)';
break;
case "nl":
header='Totaal aantal bewerkingen in <a href="http://www.wikimedia.org">Wikimediaprojecten</a>:';
//spliter=' ';
//donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia"></a>';
//f11='';
//author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "oc":
header='Edicions totalas dins <a href="http://www.wikimedia.org">los projèctes de Wikimedia</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Far una donacion a la fondacion Wikimedia</a>';
f11="Quichar sus F11 per un afichatge sus tot l'ecran";
author='Desvolopat per <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirat de <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "pl":
header='Ogólna liczba edycji w <a href="http://www.wikimedia.org">projektach Wikimedia</a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Dary_pieniężne">Wesprzyj Wikimedia Foundation</a>';
f11='Naciśnij F11, aby włączyć tryb pełnoekranowy';
author='Stworzony przez <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (zainspirowany przez <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "pt":
header='Total de edições nos <a href="http://www.wikimedia.org">projetos Wikimedia</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Coleta_de_fundos">Doe para a Fundação Wikimedia</a>';
f11='Pressione F11 para tela cheia';
author='Desenvolvido por <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirado em <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "ro":
header='Numărul total de modificări în <a href="http://www.wikimedia.org">proiectele Wikimedia</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Donaţii">Donaţi pentru Wikimedia</a>';
f11='Apăsați F11 pentru afișarea pe tot ecranul';
author='Dezvoltat de <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (inspirat de la <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "ru":
header='Всего правок в <a href="http://www.wikimedia.org">проектах Викимедиа</a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia/ru">Пожертвуйте «Фонду Викимедиа»</a>';
f11='Нажмите F11 для показа на весь экран';
author='Разработал <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Основано на <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "sv":
header='Antal redigeringar i <a href="http://www.wikimedia.org">Wikimediaprojekten</a>:';
spliter=' ';
donate='<a href="http://wikimediafoundation.org/wiki/Insamling">Donera till Wikimedia Foundation</a>';
f11='Tryck F11 för helskärm';
author='Utvecklad av <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspirerad av <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "te":
header='<a href="http://www.wikimedia.org">వికీమీడియా ప్రాజెక్టుల</a>లో మొత్తం దిద్దుబాట్లు:';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">వికీమీడియా ఫౌండేషనుకి విరాళమివ్వండి</a>';
f11='నిండుతెర కొరకు F11 నొక్కండి';
author='రూపొందించినది <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (<a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a> ప్రేరణతో)';
break;
case "tr":
header='<a href="http://www.wikimedia.org">Wikimedia projelerindeki</a> toplam düzenleme sayısı:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Wikimedia Vakfına bağışta bulunun</a>';
f11='Tam ekran görüntülemek için F11 tuşuna basın';
author='<a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> tarafından geliştirilmiştir (Esin kaynağı <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
case "ur":
header=' جملہ ترامیم در <a href="http://www.wikimedia.org">ویکیمیڈیا منصوبہ جات</a>:';
spliter='.';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">مؤسسہ ویکیمیڈیا کو عطیہ دیں</a>';
f11='مکمل سکرین دیکھنے کے لیے کلک رکیں F11';
author='ترقی دہندہ <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (متاثر از <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
break;
default:
header='Total edits in <a href="http://www.wikimedia.org">Wikimedia projects</a>:';
spliter=',';
donate='<a href="http://wikimediafoundation.org/wiki/Support_Wikipedia">Donate to Wikimedia Foundation</a>';
f11='Press F11 for fullscreen';
author='Developed by <a href="https://en.wikipedia.org/wiki/User:Emijrp">emijrp</a> (Inspired by <a href="http://www.7is7.com/software/firefox/partycounter.html">7is7</a>)';
}
document.getElementById('header').innerHTML = header;
document.getElementById('donate').innerHTML = donate;
document.getElementById('f11').innerHTML = f11;
document.getElementById('author').innerHTML = author;
window.setTimeout(update, period);
}
function update() {
timenow2 = new Date().getTime();
if (Math.round(((timenow2-timenow)/1000)+1) % 300 == 0) { window.setTimeout(window.location.reload(), 1100); } //refresh page
editnow = editinit + (timenow2-timeinit) * editrate;
editnowtext = ""+Math.round(editnow);
for(var i=3; i<editnowtext.length; i+=3) {
editnowtext = editnowtext.replace(spliter_r,'$2'+spliter+'$3');
}
document.getElementById('counter').innerHTML = editnowtext;
window.setTimeout(update, period);
}
function adjustSizes(){
var width=800;
var height=600;
if (self.innerWidth) {
width=self.innerWidth;
height=self.innerHeight;
} else if (document.documentElement && document.documentElement.clientWidth) {
width=document.documentElement.clientWidth;
height=document.documentElement.clientHeight;
} else if (document.body) {
width=document.body.clientWidth;
height=document.body.clientHeight;
}
document.getElementById('wrapper').style.height=(height-10)+'px';
document.getElementById('header').style.fontSize=width/45+'pt';
document.getElementById('footer').style.fontSize=width/45+'pt';
document.getElementById('counter').style.fontSize=width/12+'pt';
}
window.onload = init;
window.onresize = adjustSizes;
| emijrp/wmcounter | public_html/wmcounter.js | JavaScript | gpl-3.0 | 27,529 |
<?php
// clicking the 'More Info' button for a task group gives all details specific to this group
// including group attributes and group membership
function viewmembergroup_GET(Web $w) {
$p = $w->pathMatch("id");
// tab: Members
// get all members in a task group given a task group ID
$member_group = $w->Task->getMemberGroup($p['id']);
// get the group attributes given a task group ID
$taskgroup = $w->Task->getTaskGroup($p['id']);
if (empty($taskgroup->id)) {
$w->error("Taskgroup not found", '/task');
}
// put the group title into the page heading
$w->Task->navigation($w, "Task Group - " . $taskgroup->title);
History::add("Task Group: " . $taskgroup->title, null, $taskgroup);
// set columns headings for display of members
$line[] = array("Member", "Role", "");
// if their are members, display their full name, role and buttons to edit or delete the member
if ($member_group) {
foreach ($member_group as $member) {
$line[] = array($w->Task->getUserById($member->user_id), $member->role,
Html::box(WEBROOT . "/task-group/viewmember/" . $member->id, " Edit ", true) .
" " .
Html::box(WEBROOT . "/task-group/deletegroupmember/" . $member->id, " Delete ", true)
);
}
} else {
// if there are no members, say as much
$line[] = array("Group currently has no members. Please Add New Members.", "", "");
}
// display list of group members
$w->ctx("viewmembers", Html::table($line, null, "tablesorter", true));
// tab: Notify
$notify = $w->Task->getTaskGroupNotify($taskgroup->id);
if ($notify) {
foreach ($notify as $n) {
$v[$n->role][$n->type] = $n->value;
}
} else {
$v['guest']['creator'] = 0;
$v['member']['creator'] = 0;
$v['member']['assignee'] = 0;
$v['owner']['creator'] = 0;
$v['owner']['assignee'] = 0;
$v['owner']['other'] = 0;
}
$notifyForm['Task Group Notifications'] = array(
array(array("", "hidden", "task_group_id", $taskgroup->id)),
array(
array("", "static", ""),
array("Creator", "static", "creator"),
array("Assignee", "static", "assignee"),
array("All Others", "static", "others"),
),
array(
array("Guest", "static", "guest"),
array("", "checkbox", "guest_creator", $v['guest']['creator'])
),
array(
array("Member", "static", "member"),
array("", "checkbox", "member_creator", $v['member']['creator']),
array("", "checkbox", "member_assignee", $v['member']['assignee']),
),
array(
array("Owner", "static", "owner"),
array("", "checkbox", "owner_creator", $v['owner']['creator']),
array("", "checkbox", "owner_assignee", $v['owner']['assignee']),
array("", "checkbox", "owner_other", $v['owner']['other']),
),
);
$w->ctx("taskgroup", $taskgroup);
$w->ctx("notifymatrix", Html::multiColForm($notifyForm, $w->localUrl("/task-group/updategroupnotify/")));
}
| 2pisoftware/cmfive | system/modules/task/actions/group/viewmembergroup.php | PHP | gpl-3.0 | 2,837 |
# Copyright 2019-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Abydos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Abydos. If not, see <http://www.gnu.org/licenses/>.
"""abydos.distance._roberts.
Roberts similarity
"""
from typing import Any, Optional
from ._token_distance import _TokenDistance
from ..tokenizer import _Tokenizer
__all__ = ['Roberts']
class Roberts(_TokenDistance):
r"""Roberts similarity.
For two multisets X and Y drawn from an alphabet S, Roberts similarity
:cite:`Roberts:1986` is
.. math::
sim_{Roberts}(X, Y) =
\frac{\Big[\sum_{i \in S} (X_i + Y_i) \cdot
\frac{min(X_i, Y_i)}{max(X_i, Y_i)}\Big]}
{\sum_{i \in S} (X_i + Y_i)}
.. versionadded:: 0.4.0
"""
def __init__(
self, tokenizer: Optional[_Tokenizer] = None, **kwargs: Any
) -> None:
"""Initialize Roberts instance.
Parameters
----------
tokenizer : _Tokenizer
A tokenizer instance from the :py:mod:`abydos.tokenizer` package
**kwargs
Arbitrary keyword arguments
Other Parameters
----------------
qval : int
The length of each q-gram. Using this parameter and tokenizer=None
will cause the instance to use the QGram tokenizer with this
q value.
.. versionadded:: 0.4.0
"""
super(Roberts, self).__init__(tokenizer=tokenizer, **kwargs)
def sim(self, src: str, tar: str) -> float:
"""Return the Roberts similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
Returns
-------
float
Roberts similarity
Examples
--------
>>> cmp = Roberts()
>>> cmp.sim('cat', 'hat')
0.5
>>> cmp.sim('Niall', 'Neil')
0.36363636363636365
>>> cmp.sim('aluminum', 'Catalan')
0.11764705882352941
>>> cmp.sim('ATCG', 'TAGC')
0.0
.. versionadded:: 0.4.0
"""
if src == tar:
return 1.0
self._tokenize(src, tar)
alphabet = self._total().keys()
return sum(
(self._src_tokens[i] + self._tar_tokens[i])
* min(self._src_tokens[i], self._tar_tokens[i])
/ max(self._src_tokens[i], self._tar_tokens[i])
for i in alphabet
) / sum((self._src_tokens[i] + self._tar_tokens[i]) for i in alphabet)
if __name__ == '__main__':
import doctest
doctest.testmod()
| chrislit/abydos | abydos/distance/_roberts.py | Python | gpl-3.0 | 3,233 |
package com.thiha.libraryservices.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AppController {
@RequestMapping("/")
String home(ModelMap modal) {
modal.addAttribute("title","Library Services");
return "index";
}
@RequestMapping("/partials/{page}")
String partialHandler(@PathVariable("page") final String page) {
return page;
}
}
| ThihaZaw-MM/librarysystem | libraryservices/src/main/java/com/thiha/libraryservices/controllers/AppController.java | Java | gpl-3.0 | 586 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Graph.slug'
db.alter_column('muparse_graph', 'slug', self.gf('django.db.models.fields.SlugField')(max_length=128, null=True))
# Adding index on 'Graph', fields ['slug']
db.create_index('muparse_graph', ['slug'])
# Changing field 'Graph.name'
db.alter_column('muparse_graph', 'name', self.gf('django.db.models.fields.CharField')(max_length=255))
# Removing index on 'Graph', fields ['name']
db.delete_index('muparse_graph', ['name'])
def backwards(self, orm):
# Adding index on 'Graph', fields ['name']
db.create_index('muparse_graph', ['name'])
# Removing index on 'Graph', fields ['slug']
db.delete_index('muparse_graph', ['slug'])
# Changing field 'Graph.slug'
db.alter_column('muparse_graph', 'slug', self.gf('django.db.models.fields.CharField')(max_length=128, null=True))
# Changing field 'Graph.name'
db.alter_column('muparse_graph', 'name', self.gf('django.db.models.fields.SlugField')(max_length=255))
models = {
'muparse.graph': {
'Meta': {'ordering': "['name']", 'object_name': 'Graph'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['muparse.GraphCategory']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'muparse.graphcategory': {
'Meta': {'ordering': "['name']", 'object_name': 'GraphCategory'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.SlugField', [], {'max_length': '255'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'muparse.node': {
'Meta': {'ordering': "['name']", 'object_name': 'Node'},
'graphs': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['muparse.Graph']", 'null': 'True', 'through': "orm['muparse.NodeGraphs']", 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['muparse.NodeGroup']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.SlugField', [], {'max_length': '255'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '512'})
},
'muparse.nodegraphs': {
'Meta': {'object_name': 'NodeGraphs'},
'baseurl': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'graph': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['muparse.Graph']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'node': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['muparse.Node']"}),
'pageurl': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'muparse.nodegroup': {
'Meta': {'ordering': "['name']", 'object_name': 'NodeGroup'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '512'})
},
'muparse.savedsearch': {
'Meta': {'object_name': 'SavedSearch'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_type': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'graphs': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['muparse.NodeGraphs']", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['muparse'] | grnet/mupy | muparse/migrations/0004_auto__chg_field_graph_slug__chg_field_graph_name.py | Python | gpl-3.0 | 4,828 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbpOven.Templates.Application
{
interface IEntityAppService
{
}
}
| eramosr16/AbpOven | Templates/Application/IEntityAppService.cs | C# | gpl-3.0 | 208 |
#include "../../headers.h"
const int SIZE = 100000+500;
struct _t{
int idx,l,r,h;
friend bool operator < (const _t &a,const _t&b){
return a.h < b.h;
}
}que[SIZE];
#define lson(x) ((x)<<1)
#define rson(x) (lson(x)|1)
#define ls lson(t)
#define rs rson(t)
struct stNode_t{
int sum;
}ST[SIZE<<2];
inline void _pushUp( int t ){
ST[t].sum = ST[ls].sum + ST[rs].sum;
}
//inline void _pushDown( int t ){
// if ( 0 == ST[t].delay ) return;
// llt &x = ST[t].delay;
//
// ST[ls].sum += ST[ls].flag * x;
// ST[ls].delay += x;
//
// ST[rs].sum += ST[rs].flag * x;
// ST[rs].delay += x;
//
// x = 0;
//}
void build( int t,int s,int e ){
// ST[t].delay = 0;
if ( s == e ){
ST[t].sum = 0;
return;
}
int m = (s+e)>>1;
build( ls , s, m);
build( rs , m+1,e);
_pushUp(t);
}
void modify( int t,int s,int e,int a,int b,int delta){
if (a <= s && e <= b ){
ST[t].sum += delta;
return;
}
// _pushDown(t);
int m = (s + e)>>1;
if ( a <= m ) modify(ls,s,m,a,b,delta);
if ( m < b ) modify( rs,m+1,e,a,b,delta);
_pushUp(t);
}
int query( int t,int s,int e,int a,int b ){
if ( a <= s && e <= b ){
return ST[t].sum;
}
// _pushDown(t);
int ret = 0;
int m = (s + e)>>1;
if (a <= m) ret += query(ls,s,m,a,b);
if (m < b) ret += query(rs,m+1,e,a,b);
return ret;
}
struct _brick{
int idx;
int h;
friend bool operator < (const _brick & a,const _brick & b){
return a.h < b.h ;
}
}brick[SIZE];
int ans[SIZE];
int main(){
int kase = 1;
int t;scanf( "%d",&t);while(t-- ){
int n,m;
scanf("%d%d",&n,&m);
for (int i = 1 ;i <= n;++i ) {
scanf("%d",&brick[i].h);
brick[i].idx = i;
}
for ( int i = 0;i < m;++i ){
scanf("%d%d%d",&que[i].l,&que[i].r,&que[i].h);
que[i].l++;
que[i].r++;
que[i].idx = i;
}
sort ( brick+1,brick+n+1);
sort ( que,que+m);
int bi = 1;
build( 1,1,n );
// CLEAR(ST);
for (int i = 0;i < m;++i ){
while ( bi <= n && brick[bi].h <= que[i].h ){
modify( 1,1,n, brick[bi].idx ,brick[bi].idx,1);
bi++;
}
ans[ que[i].idx ] = query(1,1,n,que[i].l,que[i].r);
}
printf("Case %d:\n",kase++);
for ( int i = 0;i < m;++i ){
printf("%d\n",ans[i]);
}
}
return 0;
}
| bitwater1997/ACM | hdu/hdu4417/main.cpp | C++ | gpl-3.0 | 2,534 |
# Standard Library
from builtins import str
import os
import zipfile
from urllib.parse import quote_plus
from urllib.request import urlopen
# Third Party Stuff
from django import template
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models import Q
# Spoken Tutorial Stuff
from creation.models import *
from creation.views import (
is_administrator,
is_contenteditor,
is_contributor,
is_domainreviewer,
is_external_contributor,
is_internal_contributor,
is_qualityreviewer,
is_videoreviewer,
is_language_manager
)
from spoken.forms import TutorialSearchForm
register = template.Library()
def format_component_title(name):
return name.replace('_', ' ').capitalize()
def get_url_name(name):
return quote_plus(name)
def get_zip_content(path):
file_names = None
try:
zf = zipfile.ZipFile(path, 'r')
file_names = zf.namelist()
return file_names
except Exception as e:
return False
def is_script_available(path):
try:
code = urlopen(script_path).code
except Exception as e:
code = e.code
if(int(code) == 200):
return True
return False
def get_review_status_list(key):
status_list = ['Pending', 'Waiting for Admin Review', 'Waiting for Domain Review', 'Waiting for Quality Review', 'Accepted', 'Need Improvement', 'Not Required']
return status_list[key];
def get_review_status_class(key):
status_list = ['danger', 'active', 'warning', 'info', 'success', 'danger', 'success']
return status_list[key];
def get_review_status_symbol(key):
status_list = ['fa fa-1 fa-minus-circle review-pending-upload', 'fa fa-1 fa-check-circle review-admin-review', 'fa fa-1 fa-check-circle review-domain-review', 'fa fa-1 fa-check-circle review-quality-review', 'fa fa-1 fa-check-circle review-accepted', 'fa fa-1 fa-times-circle review-pending-upload', 'fa fa-1 fa-ban review-accepted']
return status_list[key];
def get_username(key):
user = User.objects.get(pk = key)
return user.username
def get_last_video_upload_time(key):
rec = None
try:
rec = ContributorLog.objects.filter(tutorial_resource_id = key.id).order_by('-created')[0]
tmpdt = key.updated
for tmp in rec:
tmpdt = rec.created
return tmpdt
except:
return key.updated
def get_component_name(comp):
comps = {
1: 'Outline',
2: 'Script',
3: 'Video',
4: 'Slides',
5: 'Codefiles',
6: 'Assignment'
}
key = ''
try:
key = comps[comp]
except:
pass
return key.title()
def get_missing_component_reply(mcid):
rows = TutorialMissingComponentReply.objects.filter(missing_component_id = mcid)
replies = ''
for row in rows:
replies += '<p>' + row.reply_message + '<b> -' + row.user.username + '</b></p>'
if replies:
replies = '<br /><b>Replies:</b>' + replies
return replies
def formatismp4(path):
'''
** Registered to be used in jinja template **
Function takes in a file name and checks if the
last 3 characters are `mp4`.
'''
return path[-3:] == 'mp4' or path[-3:] == 'mov'
def instruction_sheet(foss, lang):
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Instruction-Sheet-' + lang.name + '.pdf'
if lang.name != 'English':
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Instruction-Sheet-' + lang.name + '.pdf'
return file_path
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Instruction-Sheet-English.pdf'
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Instruction-Sheet-English.pdf'
return file_path
return False
def installation_sheet(foss, lang):
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Installation-Sheet-' + lang.name + '.pdf'
if lang.name != 'English':
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Installation-Sheet-' + lang.name + '.pdf'
return file_path
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Installation-Sheet-English.pdf'
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Installation-Sheet-English.pdf'
return file_path
return False
def brochure(foss, lang):
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Brochure-' + lang.name + '.pdf'
if lang.name != 'English':
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Brochure-' + lang.name + '.pdf'
return file_path
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Brochure-English.pdf'
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Brochure-English.pdf'
return file_path
return False
def get_thumb_path(row, append_str):
path = settings.MEDIA_URL + 'videos/' + str(row.foss_id) + '/' + str(row.id) + '/' + row.tutorial.replace(' ', '-') + '-' + append_str + '.png'
return path
def get_srt_path(tr):
data = ''
english_srt = settings.MEDIA_ROOT + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tr.tutorial_detail.tutorial.replace(' ', '-') + '-English.srt'
if os.path.isfile(english_srt):
data = '<track kind="captions" src="'+ settings.MEDIA_URL + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tr.tutorial_detail.tutorial.replace(' ', '-') + '-English.srt' + '" srclang="en" label="English"></track>'
if tr.language.name != 'English':
native_srt = settings.MEDIA_ROOT + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tr.tutorial_detail.tutorial.replace(' ', '-') + '-' + tr.language.name +'.srt'
print(native_srt)
if os.path.isfile(native_srt):
data += '<track kind="captions" src="'+ settings.MEDIA_URL + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tr.tutorial_detail.tutorial.replace(' ', '-') + '-' + tr.language.name + '.srt' + '" srclang="en" label="' + tr.language.name + '"></track>'
return data
def get_video_visits(tr):
tr.hit_count = tr.hit_count + 1
tr.save()
return tr.hit_count
def get_prerequisite(tr, td):
print((tr, td))
try:
tr_rec = TutorialResource.objects.get(Q(status = 1) | Q(status = 2), tutorial_detail = td, language_id = tr.language_id)
return get_url_name(td.foss.foss) + '/' + get_url_name(td.tutorial) + '/' + tr_rec.language.name
except Exception as e:
print(e)
if tr.language.name != 'English':
try:
tr_rec = TutorialResource.objects.get(Q(status = 1) | Q(status = 2), tutorial_detail = td, language__name = 'English')
return get_url_name(td.foss.foss) + '/' + get_url_name(td.tutorial) + '/English'
except:
return None
pass
return None
def get_prerequisite_from_td(td, lang):
try:
tr_rec = TutorialResource.objects.get(Q(status = 1) | Q(status = 2), tutorial_detail = td, language_id = lang.id)
return tr_rec.id
except:
if lang.name != 'English':
try:
tr_rec = TutorialResource.objects.get(Q(status = 1) | Q(status = 2), tutorial_detail = td, language__name = 'English')
return tr_rec.id
except:
pass
return None
def get_timed_script(script_path, timed_script_path):
if timed_script_path:
timed_script = settings.SCRIPT_URL + timed_script_path
else:
timed_script = settings.SCRIPT_URL + script_path + '-timed'
print(script_path)
code = 0
try:
code = urlopen(timed_script).code
except Exception as e:
timed_script = settings.SCRIPT_URL + \
script_path.replace(' ', '-').replace('_', '-') + '-timed'
print(timed_script)
try:
code = urlopen(timed_script).code
except Exception as e:
print((code, '----', e))
code = 0
if(int(code) == 200):
return timed_script
return ''
def tutorialsearch():
context = {
'form': TutorialSearchForm()
}
return context
def get_mp4_video(tr):
video_name = tr.video
splitat = -4
tname, text = video_name[:splitat], video_name[splitat:]
path = settings.MEDIA_ROOT + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tname + '.mp4'
if os.path.isfile(path):
return 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tname + '.mp4'
return False
register.inclusion_tag('spoken/templates/tutorial_search_form.html')(tutorialsearch)
#register.filter('tutorialsearch', tutorialsearch)
register.filter('get_timed_script', get_timed_script)
register.filter('formatismp4', formatismp4)
register.filter('get_prerequisite_from_td', get_prerequisite_from_td)
register.filter('get_prerequisite', get_prerequisite)
register.filter('get_video_visits', get_video_visits)
register.filter('get_srt_path', get_srt_path)
register.filter('get_thumb_path', get_thumb_path)
register.filter('get_missing_component_reply', get_missing_component_reply)
register.filter('get_component_name', get_component_name)
register.filter('get_url_name', get_url_name)
register.filter('get_zip_content', get_zip_content)
register.filter('get_contributor', is_contributor)
register.filter('get_internal_contributor', is_internal_contributor)
register.filter('get_external_contributor', is_external_contributor)
register.filter('get_videoreviewer', is_videoreviewer)
register.filter('get_domainreviewer', is_domainreviewer)
register.filter('get_qualityreviewer', is_qualityreviewer)
register.filter('get_administrator', is_administrator)
register.filter('get_last_video_upload_time', get_last_video_upload_time)
register.filter('get_review_status_list', get_review_status_list)
register.filter('get_review_status_symbol', get_review_status_symbol)
register.filter('get_review_status_class', get_review_status_class)
register.filter('get_username', get_username)
register.filter('instruction_sheet', instruction_sheet)
register.filter('installation_sheet', installation_sheet)
register.filter('brochure', brochure)
register.filter('get_contenteditor', is_contenteditor)
register.filter('format_component_title', format_component_title)
register.filter('get_mp4_video', get_mp4_video)
register.filter('get_language_manager',is_language_manager) | Spoken-tutorial/spoken-website | creation/templatetags/creationdata.py | Python | gpl-3.0 | 11,230 |
/*
Copyright © 2011-2012 Clint Bellanger
This file is part of FLARE.
FLARE is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
FLARE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
FLARE. If not, see http://www.gnu.org/licenses/
*/
/**
* class NPCManager
*
* NPCs which are not combatative enemies are handled by this Manager.
* Most commonly this involves vendor and conversation townspeople.
*/
#include "FileParser.h"
#include "NPCManager.h"
#include "NPC.h"
#include "SharedResources.h"
#include "MapRenderer.h"
#include "LootManager.h"
#include "StatBlock.h"
using namespace std;
NPCManager::NPCManager(MapRenderer *_map, LootManager *_loot, ItemManager *_items, StatBlock *_stats) {
stats = _stats;
map = _map;
loot = _loot;
items = _items;
tip = new WidgetTooltip();
FileParser infile;
// load tooltip_margin from engine config file
if (infile.open(mods->locate("engine/tooltips.txt").c_str())) {
while (infile.next()) {
if (infile.key == "npc_tooltip_margin") {
tooltip_margin = atoi(infile.val.c_str());
}
}
infile.close();
} else fprintf(stderr, "Unable to open engine/tooltips.txt!\n");
}
void NPCManager::addRenders(std::vector<Renderable> &r) {
for (unsigned i=0; i<npcs.size(); i++) {
r.push_back(npcs[i]->getRender());
}
}
void NPCManager::handleNewMap() {
Map_NPC mn;
ItemStack item_roll;
// remove existing NPCs
for (unsigned i=0; i<npcs.size(); i++)
delete(npcs[i]);
npcs.clear();
// read the queued NPCs in the map file
while (!map->npcs.empty()) {
mn = map->npcs.front();
map->npcs.pop();
NPC *npc = new NPC(map, items);
npc->load(mn.id, stats->level);
npc->pos.x = mn.pos.x;
npc->pos.y = mn.pos.y;
// if this NPC needs randomized items
while (npc->random_stock > 0 && npc->stock_count < NPC_VENDOR_MAX_STOCK) {
item_roll.item = loot->randomItem(npc->level);
item_roll.quantity = rand() % items->items[item_roll.item].rand_vendor + 1;
npc->stock.add(item_roll);
npc->random_stock--;
}
npc->stock.sort();
npcs.push_back(npc);
}
}
void NPCManager::logic() {
for (unsigned i=0; i<npcs.size(); i++) {
npcs[i]->logic();
}
}
int NPCManager::checkNPCClick(Point mouse, Point cam) {
Point p;
SDL_Rect r;
for (unsigned i=0; i<npcs.size(); i++) {
p = map_to_screen(npcs[i]->pos.x, npcs[i]->pos.y, cam.x, cam.y);
r.w = npcs[i]->render_size.x;
r.h = npcs[i]->render_size.y;
r.x = p.x - npcs[i]->render_offset.x;
r.y = p.y - npcs[i]->render_offset.y;
if (isWithin(r, mouse)) {
return i;
}
}
return -1;
}
/**
* On mouseover, display NPC's name
*/
void NPCManager::renderTooltips(Point cam, Point mouse) {
Point p;
SDL_Rect r;
for (unsigned i=0; i<npcs.size(); i++) {
p = map_to_screen(npcs[i]->pos.x, npcs[i]->pos.y, cam.x, cam.y);
r.w = npcs[i]->render_size.x;
r.h = npcs[i]->render_size.y;
r.x = p.x - npcs[i]->render_offset.x;
r.y = p.y - npcs[i]->render_offset.y;
if (isWithin(r, mouse)) {
// adjust dest.y so that the tooltip floats above the item
p.y -= tooltip_margin;
// use current tip or make a new one?
if (tip_buf.lines[0] != npcs[i]->name) {
tip_buf.clear();
tip_buf.num_lines = 1;
tip_buf.lines[0] = npcs[i]->name;
}
tip->render(tip_buf, p, STYLE_TOPLABEL);
break; // display only one NPC tooltip at a time
}
}
}
NPCManager::~NPCManager() {
for (unsigned i=0; i<npcs.size(); i++) {
delete npcs[i];
}
tip_buf.clear();
delete tip;
}
| makrohn/Keradon | src/NPCManager.cpp | C++ | gpl-3.0 | 3,880 |
/*
* Copyright © The DevOps Collective, Inc. All rights reserved.
* Licnesed under GNU GPL v3. See top-level LICENSE.txt for more details.
*/
using System;
using System.Collections.Generic;
using System.Composition.Convention;
using System.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Logging;
namespace Tug.Ext.Util
{
/// <summary>
/// Defines a base implementation of <see cref="IProviderManager<TProv, TProd>"/>
/// that supports dynamic extension provider discovery and loading from
/// built-in assemblies and file paths using the Managed Extensibility Framework
/// (MEF) version 2, or otherwise known as the <i>light</i> edition of MEF.
/// </summary>
public abstract class ProviderManagerBase<TProv, TProd> : IProviderManager<TProv, TProd>
where TProv : IProvider<TProd>
where TProd : IProviderProduct
{
private ILogger _logger;
private ServiceProviderExportDescriptorProvider _adapter;
private List<Assembly> _BuiltInAssemblies = new List<Assembly>();
private List<Assembly> _SearchAssemblies = new List<Assembly>();
private List<string> _SearchPaths = new List<string>();
private TProv[] _foundProviders = null;
/// <summary>
/// Constructs a base Provider Manager with default configuration settings.
/// </summary>
/// <param name="managerLogger">logger to be used internally</param>
/// <param name="adapter">an optional adapter to allow MEF dependencies
/// to be resolved by external DI sources</param>
/// <remarks>
/// The default configuration of the base Manager adds the assemblies
/// containing the generic typic parameters (TProv, TProd) to be added
/// as <i>built-in</i> assemblies, and to include all other loaded and
/// active assemblies as searchable assemblies (and no search paths).
/// <para>
/// Additionally if an adapter is provided it will be added to the internal
/// MEF resolution process as a last step in resolving dependencies.
/// </para>
/// </remarks>
public ProviderManagerBase(ILogger managerLogger,
ServiceProviderExportDescriptorProvider adapter = null)
{
_logger = managerLogger;
_adapter = adapter;
Init();
}
protected virtual void Init()
{
// By default we include the assemblies containing the
// principles a part of the built-ins and every other
// assembly in context a part of the search scope
_logger.LogInformation("Adding BUILTINS");
AddBuiltIns(
typeof(TProv).GetTypeInfo().Assembly,
typeof(TProd).GetTypeInfo().Assembly);
#if DOTNET_FRAMEWORK
var asms = AppDomain.CurrentDomain.GetAssemblies();
_logger.LogInformation("Adding [{asmCount}] resolved Search Assemblies", asms.Length);
AddSearchAssemblies(asms);
#else
_logger.LogInformation("Resolving active runtime assemblies");
// TODO: see if this works as expected on .NET Core
var dc = DependencyContext.Load(Assembly.GetEntryAssembly());
var libs = dc.RuntimeLibraries;
var asms = new List<AssemblyName>();
_logger.LogInformation(" discovered [{libCount}] runtime libraries", libs.Count());
foreach (var lib in dc.RuntimeLibraries)
{
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug(" Runtime Library: {rtLib}", lib.Name);
foreach (var rtasm in lib.Assemblies)
{
if (asms.Contains(rtasm.Name))
continue;
asms.Add(rtasm.Name);
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug(" Adding newly found Runtime Assembly: {rtAsm}", rtasm.Name.FullName);
//AssemblyLoadContext.Default.LoadFromAssemblyName(rtasm.Name);
AddSearchAssemblies(Assembly.Load(rtasm.Name));
}
}
_logger.LogInformation("Added [{asmCount}] resolved Search Assemblies", asms.Count);
#endif
}
/// <summary>
/// Lists the built-in assemblies that will be
/// searched first for matching providers.
/// </summary>
public IEnumerable<Assembly> BuiltInAssemblies
{
get { return _BuiltInAssemblies; }
}
/// <summary>
/// Lists the built-in assemblies that will be
/// searched first for matching providers.
/// </summary>
public IEnumerable<Assembly> SearchAssemblies
{
get { return _SearchAssemblies; }
}
/// <summary>
/// Lists the built-in assemblies that will be
/// searched first for matching providers.
/// </summary>
public IEnumerable<string> SearchPaths
{
get { return _SearchPaths; }
}
/// <summary>
/// Returns all the matching provider implementations that
/// have previously been discovered. If necessary, invokes
/// the resolution process to find matching providers.
/// </summary>
public IEnumerable<string> FoundProvidersNames
{
get
{
if (_foundProviders == null)
{
_logger.LogInformation("providers have not yet been resolved -- resolving");
this.FindProviders();
}
return _foundProviders.Select(p => p.Describe().Name);
}
}
public TProv GetProvider(string name)
{
return _foundProviders.FirstOrDefault(p => name.Equals(p.Describe().Name));
}
/// <summary>
/// Resets the list of built-in assemblies to be searched.
/// </summary>
protected ProviderManagerBase<TProv, TProd> ClearBuiltIns()
{
_BuiltInAssemblies.Clear();
return this;
}
/// <summary>
/// Adds one or more built-in assemblies to be searched for matching provider
/// implementations.
/// </summary>
protected ProviderManagerBase<TProv, TProd> AddBuiltIns(params Assembly[] assemblies)
{
return AddBuiltIns((IEnumerable<Assembly>)assemblies);
}
/// <summary>
/// Adds one or more built-in assemblies to be searched for matching provider
/// implementations.
/// </summary>
protected ProviderManagerBase<TProv, TProd> AddBuiltIns(IEnumerable<Assembly> assemblies)
{
foreach (var a in assemblies)
if (!_BuiltInAssemblies.Contains(a))
_BuiltInAssemblies.Add(a);
return this;
}
/// <summary>
/// Resets the list of external assemblies to be searched.
/// </summary>
protected ProviderManagerBase<TProv, TProd> ClearSearchAssemblies()
{
_SearchAssemblies.Clear();
return this;
}
/// <summary>
/// Adds one or more exteranl assemblies to be searched for matching provider
/// implementations.
/// </summary>
protected ProviderManagerBase<TProv, TProd> AddSearchAssemblies(params Assembly[] assemblies)
{
return AddSearchAssemblies((IEnumerable<Assembly>)assemblies);
}
/// <summary>
/// Adds one or more exteranl assemblies to be searched for matching provider
/// implementations.
/// </summary>
protected ProviderManagerBase<TProv, TProd> AddSearchAssemblies(IEnumerable<Assembly> assemblies)
{
foreach (var a in assemblies)
if (!_BuiltInAssemblies.Contains(a) && !_SearchAssemblies.Contains(a))
_SearchAssemblies.Add(a);
return this;
}
protected static AssemblyName GetAssemblyName(string asmName)
{
#if DOTNET_FRAMEWORK
return AssemblyName.GetAssemblyName(asmName);
#else
return System.Runtime.Loader.AssemblyLoadContext.GetAssemblyName(asmName);
#endif
}
protected static Assembly GetAssembly(AssemblyName asmName)
{
#if DOTNET_FRAMEWORK
return Assembly.Load(asmName);
#else
return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyName(asmName);
#endif
}
/// <summary>
/// Resets the list of directory paths to be searched.
/// </summary>
protected ProviderManagerBase<TProv, TProd> ClearSearchPaths()
{
_SearchPaths.Clear();
return this;
}
/// <summary>
/// Adds one or more directory paths to be searched for matching provider
/// implementations.
/// </summary>
protected ProviderManagerBase<TProv, TProd> AddSearchPath(params string[] paths)
{
return AddSearchPath((IEnumerable<string>)paths);
}
/// <summary>
/// Adds one or more directory paths to be searched for matching provider
/// implementations.
/// </summary>
protected ProviderManagerBase<TProv, TProd> AddSearchPath(IEnumerable<string> paths)
{
foreach (var p in paths)
if (!_SearchPaths.Contains(p))
_SearchPaths.Add(p);
return this;
}
/// <summary>
/// Evaluates whether a candidate type is a provider type.
/// </summary>
/// <remarks>
/// The default implementation simply tests if the candidate type
/// is a qualified descendent of the TProv provider type.
/// <para>
/// Subclasses may add, or replace with, other conditions such as testing
/// for the presence of a particular class-level custom attribute or
/// testing for the presence of other features of the class definition
/// such as a qualifying constructor signature.
/// </para>
/// </remarks>
protected bool MatchProviderType(Type candidate)
{
return MefExtensions.IsDescendentOf(candidate, typeof(TProv));
}
/// <summary>
/// Each time this is invoked, the search paths and patterns
/// (built-in assemblies and directory paths + patterns) are
/// searched to resolve matching components. The results are
/// cached and available in <see cref="FoundProviders">.
/// </summary>
protected virtual IEnumerable<TProv> FindProviders()
{
try
{
_logger.LogInformation("resolving providers");
var conventions = new ConventionBuilder();
// conventions.ForTypesDerivedFrom<TProv>()
conventions.ForTypesMatching<TProv>(MatchProviderType)
.Export<TProv>()
.Shared();
var existingPaths = _SearchPaths.Where(x => Directory.Exists(x));
var configuration = new ContainerConfiguration()
.WithAssemblies(_BuiltInAssemblies, conventions)
.WithAssemblies(_SearchAssemblies, conventions)
.WithAssembliesInPaths(existingPaths.ToArray(), conventions);
if (_adapter != null)
configuration.WithProvider(_adapter);
using (var container = configuration.CreateContainer())
{
_foundProviders = container.GetExports<TProv>().ToArray();
}
return _foundProviders;
}
catch (System.Reflection.ReflectionTypeLoadException ex)
{
Console.Error.WriteLine(">>>>>> Load Exceptions:");
foreach (var lex in ex.LoaderExceptions)
{
Console.Error.WriteLine(">>>>>> >>>>" + lex);
}
throw ex;
}
}
}
} | majst32/tug | src/Tug.Base/Ext/Util/ProviderManagerBase.cs | C# | gpl-3.0 | 12,354 |
export const LOGGED_IN = 'LOGGED_IN';
export const LOGGED_OUT = 'LOGGED_OUT'; | csujedihy/react-native-textgo | app/actions/types.js | JavaScript | gpl-3.0 | 77 |
#include "drivercommon.h"
#include <common/fortconf.h>
#include <common/fortioctl.h>
#include <common/fortlog.h>
#include <common/fortprov.h>
namespace DriverCommon {
QString deviceName()
{
return QLatin1String(FORT_DEVICE_NAME);
}
quint32 ioctlValidate()
{
return FORT_IOCTL_VALIDATE;
}
quint32 ioctlSetConf()
{
return FORT_IOCTL_SETCONF;
}
quint32 ioctlSetFlags()
{
return FORT_IOCTL_SETFLAGS;
}
quint32 ioctlGetLog()
{
return FORT_IOCTL_GETLOG;
}
quint32 ioctlAddApp()
{
return FORT_IOCTL_ADDAPP;
}
quint32 ioctlDelApp()
{
return FORT_IOCTL_DELAPP;
}
quint32 ioctlSetZones()
{
return FORT_IOCTL_SETZONES;
}
quint32 ioctlSetZoneFlag()
{
return FORT_IOCTL_SETZONEFLAG;
}
quint32 userErrorCode()
{
return FORT_ERROR_USER_ERROR;
}
qint64 systemToUnixTime(qint64 systemTime)
{
return fort_system_to_unix_time(systemTime);
}
int bufferSize()
{
return FORT_BUFFER_SIZE;
}
quint32 confIoConfOff()
{
return FORT_CONF_IO_CONF_OFF;
}
quint32 logBlockedHeaderSize()
{
return FORT_LOG_BLOCKED_HEADER_SIZE;
}
quint32 logBlockedSize(quint32 pathLen)
{
return FORT_LOG_BLOCKED_SIZE(pathLen);
}
quint32 logBlockedIpHeaderSize()
{
return FORT_LOG_BLOCKED_IP_HEADER_SIZE;
}
quint32 logBlockedIpSize(quint32 pathLen)
{
return FORT_LOG_BLOCKED_IP_SIZE(pathLen);
}
quint32 logProcNewHeaderSize()
{
return FORT_LOG_PROC_NEW_HEADER_SIZE;
}
quint32 logProcNewSize(quint32 pathLen)
{
return FORT_LOG_PROC_NEW_SIZE(pathLen);
}
quint32 logStatHeaderSize()
{
return FORT_LOG_STAT_HEADER_SIZE;
}
quint32 logStatTrafSize(quint16 procCount)
{
return FORT_LOG_STAT_TRAF_SIZE(procCount);
}
quint32 logStatSize(quint16 procCount)
{
return FORT_LOG_STAT_SIZE(procCount);
}
quint32 logTimeSize()
{
return FORT_LOG_TIME_SIZE;
}
quint8 logType(const char *input)
{
return fort_log_type(input);
}
void logBlockedHeaderWrite(char *output, bool blocked, quint32 pid, quint32 pathLen)
{
fort_log_blocked_header_write(output, blocked, pid, pathLen);
}
void logBlockedHeaderRead(const char *input, int *blocked, quint32 *pid, quint32 *pathLen)
{
fort_log_blocked_header_read(input, blocked, pid, pathLen);
}
void logBlockedIpHeaderWrite(char *output, int inbound, int inherited, quint8 blockReason,
quint8 ipProto, quint16 localPort, quint16 remotePort, quint32 localIp, quint32 remoteIp,
quint32 pid, quint32 pathLen)
{
fort_log_blocked_ip_header_write(output, inbound, inherited, blockReason, ipProto, localPort,
remotePort, localIp, remoteIp, pid, pathLen);
}
void logBlockedIpHeaderRead(const char *input, int *inbound, int *inherited, quint8 *blockReason,
quint8 *ipProto, quint16 *localPort, quint16 *remotePort, quint32 *localIp,
quint32 *remoteIp, quint32 *pid, quint32 *pathLen)
{
fort_log_blocked_ip_header_read(input, inbound, inherited, blockReason, ipProto, localPort,
remotePort, localIp, remoteIp, pid, pathLen);
}
void logProcNewHeaderWrite(char *output, quint32 pid, quint32 pathLen)
{
fort_log_proc_new_header_write(output, pid, pathLen);
}
void logProcNewHeaderRead(const char *input, quint32 *pid, quint32 *pathLen)
{
fort_log_proc_new_header_read(input, pid, pathLen);
}
void logStatTrafHeaderRead(const char *input, quint16 *procCount)
{
fort_log_stat_traf_header_read(input, procCount);
}
void logTimeWrite(char *output, int timeChanged, qint64 unixTime)
{
fort_log_time_write(output, timeChanged, unixTime);
}
void logTimeRead(const char *input, int *timeChanged, qint64 *unixTime)
{
fort_log_time_read(input, timeChanged, unixTime);
}
void confAppPermsMaskInit(void *drvConf)
{
PFORT_CONF conf = (PFORT_CONF) drvConf;
fort_conf_app_perms_mask_init(conf, conf->flags.group_bits);
}
bool confIpInRange(const void *drvConf, quint32 ip, bool included, int addrGroupIndex)
{
const PFORT_CONF conf = (const PFORT_CONF) drvConf;
const PFORT_CONF_ADDR_GROUP addr_group = fort_conf_addr_group_ref(conf, addrGroupIndex);
const bool is_empty = included ? addr_group->include_is_empty : addr_group->exclude_is_empty;
if (is_empty)
return false;
const PFORT_CONF_ADDR_LIST addr_list = included
? fort_conf_addr_group_include_list_ref(addr_group)
: fort_conf_addr_group_exclude_list_ref(addr_group);
return fort_conf_ip_inlist(ip, addr_list);
}
quint16 confAppFind(const void *drvConf, const QString &kernelPath)
{
const PFORT_CONF conf = (const PFORT_CONF) drvConf;
const QString kernelPathLower = kernelPath.toLower();
const quint32 len = quint32(kernelPathLower.size()) * sizeof(WCHAR);
const WCHAR *p = (PCWCHAR) kernelPathLower.utf16();
const FORT_APP_FLAGS app_flags =
fort_conf_app_find(conf, (const PVOID) p, len, fort_conf_app_exe_find);
return app_flags.v;
}
quint8 confAppGroupIndex(quint16 appFlags)
{
const FORT_APP_FLAGS app_flags = { appFlags };
return app_flags.group_index;
}
bool confAppBlocked(const void *drvConf, quint16 appFlags, qint8 *blockReason)
{
const PFORT_CONF conf = (const PFORT_CONF) drvConf;
return fort_conf_app_blocked(conf, { appFlags }, blockReason);
}
quint16 confAppPeriodBits(const void *drvConf, quint8 hour, quint8 minute)
{
const PFORT_CONF conf = (const PFORT_CONF) drvConf;
FORT_TIME time;
time.hour = hour;
time.minute = minute;
return fort_conf_app_period_bits(conf, time, nullptr);
}
bool isTimeInPeriod(quint8 hour, quint8 minute, quint8 fromHour, quint8 fromMinute, quint8 toHour,
quint8 toMinute)
{
FORT_TIME time;
time.hour = hour;
time.minute = minute;
FORT_PERIOD period;
period.from.hour = fromHour;
period.from.minute = fromMinute;
period.to.hour = toHour;
period.to.minute = toMinute;
return is_time_in_period(time, period);
}
int bitScanForward(quint32 mask)
{
return bit_scan_forward(mask);
}
void provUnregister()
{
fort_prov_unregister(nullptr);
}
}
| tnodir/fort | src/ui/driver/drivercommon.cpp | C++ | gpl-3.0 | 6,014 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="gl_ES" version="2.1">
<context>
<name>ContentWidget</name>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="244"/>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="290"/>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="378"/>
<source>Shut down</source>
<translation>Apagar</translation>
</message>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="246"/>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="295"/>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="381"/>
<source>Reboot</source>
<translation>Reiniciar</translation>
</message>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="291"/>
<source>Are you sure to shut down?</source>
<translation>Tes a certeza de querer apagar?</translation>
</message>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="296"/>
<source>Are you sure to reboot?</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="300"/>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="390"/>
<source>Log out</source>
<translation>Pechar a sesión</translation>
</message>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="301"/>
<source>Are you sure to log out?</source>
<translation>Tes a certeza de querer pechar a sesión?</translation>
</message>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="384"/>
<source>Suspend</source>
<translation>Suspender</translation>
</message>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="387"/>
<source>Lock</source>
<translation>Bloquear</translation>
</message>
<message>
<location filename="../dde-shutdown/view/contentwidget.cpp" line="394"/>
<source>Switch user</source>
<translation>Cambiar de usuario</translation>
</message>
</context>
<context>
<name>DisplayModeProvider</name>
<message>
<location filename="../dde-osd/displaymodeprovider.cpp" line="158"/>
<source>Duplicate</source>
<translation>Duplicar</translation>
</message>
<message>
<location filename="../dde-osd/displaymodeprovider.cpp" line="160"/>
<source>Extend</source>
<translation>Extender</translation>
</message>
</context>
<context>
<name>InhibitWarnView</name>
<message>
<location filename="../dde-shutdown/view/inhibitwarnview.cpp" line="50"/>
<source>Cancel</source>
<translation>Cancelar</translation>
</message>
</context>
<context>
<name>KBLayoutIndicator</name>
<message>
<location filename="../dde-osd/kblayoutindicator.cpp" line="152"/>
<source>Add keyboard layout</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>LockManager</name>
<message>
<location filename="../dde-lock/lockmanager.cpp" line="154"/>
<source>Login</source>
<translation>Inicio de sesión</translation>
</message>
<message>
<location filename="../dde-lock/lockmanager.cpp" line="405"/>
<source>Please enter your password manually if fingerprint password timed out</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-lock/lockmanager.cpp" line="420"/>
<source>Wrong Password</source>
<translation>Contrasinal non válido</translation>
</message>
<message>
<location filename="../dde-lock/lockmanager.cpp" line="550"/>
<source>Enter your password to reboot</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-lock/lockmanager.cpp" line="555"/>
<source>Enter your password to shutdown</source>
<translation>Insire o teu contrasinal para apagar</translation>
</message>
</context>
<context>
<name>LoginManager</name>
<message>
<location filename="../lightdm-deepin-greeter/app/loginmanager.cpp" line="297"/>
<source>Login</source>
<translation>Inicio de sesión</translation>
</message>
<message>
<location filename="../lightdm-deepin-greeter/app/loginmanager.cpp" line="473"/>
<source>Please enter your password manually if fingerprint password timed out</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../lightdm-deepin-greeter/app/loginmanager.cpp" line="527"/>
<source>Wrong Password</source>
<translation>Contrasinal non válido</translation>
</message>
</context>
<context>
<name>MultiUsersWarningView</name>
<message>
<location filename="../dde-shutdown/view/multiuserswarningview.cpp" line="124"/>
<source>The above users still keep logged in and the data will be lost due to shutdown, are you sure to shut down? </source>
<translation>Estes usuarios aínda están conectados, ao apagar perderanse todos os seus datos, tes a certeza de querer continuar?</translation>
</message>
<message>
<location filename="../dde-shutdown/view/multiuserswarningview.cpp" line="130"/>
<source>The above users still keep logged in and the data will be lost due to reboot, are you sure to reboot? </source>
<translation>Estes usuarios aínda están conectados, ao reiniciar perderanse todos os seus datos, tes a certeza de querer continuar?</translation>
</message>
</context>
<context>
<name>ShutdownWidget</name>
<message>
<location filename="../widgets/shutdownwidget.cpp" line="45"/>
<source>Shut down</source>
<translation>Apagar</translation>
</message>
<message>
<location filename="../widgets/shutdownwidget.cpp" line="49"/>
<source>Reboot</source>
<translation>Reiniciar</translation>
</message>
<message>
<location filename="../widgets/shutdownwidget.cpp" line="53"/>
<source>Suspend</source>
<translation>Suspender</translation>
</message>
</context>
<context>
<name>SuspendDialog</name>
<message>
<location filename="../dde-suspend-dialog/suspenddialog.cpp" line="34"/>
<source>External monitor detected, suspend?</source>
<translation>Monitor externo detectado, suspender?</translation>
</message>
<message>
<location filename="../dde-suspend-dialog/suspenddialog.cpp" line="34"/>
<location filename="../dde-suspend-dialog/suspenddialog.cpp" line="55"/>
<source>%1s</source>
<translation>%1s</translation>
</message>
<message>
<location filename="../dde-suspend-dialog/suspenddialog.cpp" line="45"/>
<source>Cancel</source>
<translation>Cancelar</translation>
</message>
<message>
<location filename="../dde-suspend-dialog/suspenddialog.cpp" line="45"/>
<source>Suspend</source>
<translation>Suspender</translation>
</message>
</context>
<context>
<name>SystemMonitor</name>
<message>
<location filename="../dde-shutdown/view/systemmonitor.cpp" line="47"/>
<source>Start system monitor</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TimeWidget</name>
<message>
<location filename="../dde-lock/timewidget.cpp" line="76"/>
<source>hh:mm</source>
<translation> hh:mm </translation>
</message>
<message>
<location filename="../dde-lock/timewidget.cpp" line="77"/>
<source>yyyy-MM-dd dddd</source>
<translation>dddd dd-MM-yyyy</translation>
</message>
</context>
<context>
<name>UpdateContent</name>
<message>
<location filename="../dde-welcome/updatecontent.cpp" line="41"/>
<source>Welcome, system updated successfully</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-welcome/updatecontent.cpp" line="42"/>
<source>Current Edition:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-welcome/updatecontent.cpp" line="43"/>
<source>Enter</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WMChooser</name>
<message>
<location filename="../dde-wm-chooser/wmchooser.cpp" line="56"/>
<source>Effect Mode</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-wm-chooser/wmchooser.cpp" line="59"/>
<source>Common Mode</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-wm-chooser/wmchooser.cpp" line="63"/>
<source>Friendly Reminder</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-wm-chooser/wmchooser.cpp" line="67"/>
<source>System has detected that you are using a virtual machine, which will affect the system performance and operation experience, for a smooth experience, it is recommended to select Common Mode</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dde-wm-chooser/wmchooser.cpp" line="70"/>
<source>Effect Mode: You can smoothly and gorgeously experience. Common Mode: You can extremely rapidly experience</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WMStateProvider</name>
<message>
<location filename="../dde-osd/wmstateprovider.cpp" line="43"/>
<source>Window effect enabled</source>
<translation>Efecto da xanela activado</translation>
</message>
<message>
<location filename="../dde-osd/wmstateprovider.cpp" line="45"/>
<source>Window effect disabled</source>
<translation>Efecto da xanela desactivado</translation>
</message>
<message>
<location filename="../dde-osd/wmstateprovider.cpp" line="47"/>
<source>Failed to enable window effects</source>
<translation>Non foi posible activar os efectos das xanelas</translation>
</message>
</context>
<context>
<name>WarningDialog</name>
<message>
<location filename="../dde-warning-dialog/warningdialog.cpp" line="38"/>
<source>Kindly Reminder</source>
<translation>Recordatorio</translation>
</message>
<message>
<location filename="../dde-warning-dialog/warningdialog.cpp" line="39"/>
<source>This application can not run without window effect</source>
<translation>Esta aplicación non pode correr sen efecto de xanela</translation>
</message>
<message>
<location filename="../dde-warning-dialog/warningdialog.cpp" line="43"/>
<source>OK</source>
<translation>Aceptar</translation>
</message>
</context>
<context>
<name>Window</name>
<message>
<location filename="../dde-lowpower/window.cpp" line="39"/>
<source>Low battery, please plug in</source>
<translation>Batería baixa, por favor conecta á corrente</translation>
</message>
</context>
</TS> | oberon2007/deepin-session-ui-manjaro | translations/dde-session-ui_gl_ES.ts | TypeScript | gpl-3.0 | 11,648 |
<?php /* Smarty version 2.6.2, created on 2014-11-17 07:44:59
compiled from /var/www/openemr/interface/forms/vitals/templates/vitals/general_new.html */ ?>
<?php require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'xl', '/var/www/openemr/interface/forms/vitals/templates/vitals/general_new.html', 29, false),array('function', 'math', '/var/www/openemr/interface/forms/vitals/templates/vitals/general_new.html', 152, false),array('modifier', 'date_format', '/var/www/openemr/interface/forms/vitals/templates/vitals/general_new.html', 129, false),array('modifier', 'string_format', '/var/www/openemr/interface/forms/vitals/templates/vitals/general_new.html', 194, false),array('modifier', 'substr', '/var/www/openemr/interface/forms/vitals/templates/vitals/general_new.html', 287, false),)), $this); ?>
<html>
<head>
<?php html_header_show(); ?>
<style type="text/css">@import url(<?php echo $this->_tpl_vars['FORM_ACTION']; ?>
/library/dynarch_calendar.css);</style>
<script type="text/javascript" src="<?php echo $this->_tpl_vars['FORM_ACTION']; ?>
/library/dialog.js"></script>
<script type="text/javascript" src="<?php echo $this->_tpl_vars['FORM_ACTION']; ?>
/library/textformat.js"></script>
<script type="text/javascript" src="<?php echo $this->_tpl_vars['FORM_ACTION']; ?>
/library/dynarch_calendar.js"></script>
<?php include_once("{$GLOBALS['srcdir']}/dynarch_calendar_en.inc.php"); ?>
<script type="text/javascript" src="<?php echo $this->_tpl_vars['FORM_ACTION']; ?>
/library/dynarch_calendar_setup.js"></script>
<script type="text/javascript">
var mypcc = '<?php echo $GLOBALS['phone_country_code'] ?>';
<?php echo '
// Only load jquery if not already closing. This page serves two purposes now,
// for entring of vitals and for graphing/trending previous vitals by being embedded
// in the interface/patient_file/encounter/trend_form.php page.
if (typeof jQuery == \'undefined\') {
document.write("<script type=\'text/javascript\' src=\''; echo $GLOBALS['webroot']; echo '/library/js/jquery.js\'><\\/script>")
}
function vitalsFormSubmitted() {
var invalid = "";
var elementsToValidate = new Array();
elementsToValidate[0] = new Array();
elementsToValidate[0][0] = \'weight_input\';
elementsToValidate[0][1] = \''; echo smarty_function_xl(array('t' => 'Weight'), $this); echo '\' + \' (\' + \''; echo smarty_function_xl(array('t' => 'lbs'), $this); echo '\' + \')\';
elementsToValidate[1] = new Array();
elementsToValidate[1][0] = \'weight_input_metric\';
elementsToValidate[1][1] = \''; echo smarty_function_xl(array('t' => 'Weight'), $this); echo '\' + \' (\' + \''; echo smarty_function_xl(array('t' => 'kg'), $this); echo '\' + \')\';
elementsToValidate[2] = new Array();
elementsToValidate[2][0] = \'height_input\';
elementsToValidate[2][1] = \''; echo smarty_function_xl(array('t' => "Height/Length"), $this); echo '\' + \' (\' + \''; echo smarty_function_xl(array('t' => 'in'), $this); echo '\' + \')\';
elementsToValidate[3] = new Array();
elementsToValidate[3][0] = \'height_input_metric\';
elementsToValidate[3][1] = \''; echo smarty_function_xl(array('t' => "Height/Length"), $this); echo '\' + \' (\' + \''; echo smarty_function_xl(array('t' => 'cm'), $this); echo '\' + \')\';
elementsToValidate[4] = new Array();
elementsToValidate[4][0] = \'bps_input\';
elementsToValidate[4][1] = \''; echo smarty_function_xl(array('t' => 'BP Systolic'), $this); echo '\';
elementsToValidate[5] = new Array();
elementsToValidate[5][0] = \'bpd_input\';
elementsToValidate[5][1] = \''; echo smarty_function_xl(array('t' => 'BP Diastolic'), $this); echo '\';
for (var i = 0; i < elementsToValidate.length; i++) {
var current_elem_id = elementsToValidate[i][0];
var tag_name = elementsToValidate[i][1];
document.getElementById(current_elem_id).classList.remove(\'error\');
if (isNaN(document.getElementById(current_elem_id).value)) {
invalid += "'; echo smarty_function_xl(array('t' => 'The following field has an invalid value'), $this); echo '" + ": " + tag_name + "\\n";
document.getElementById(current_elem_id).className = document.getElementById(current_elem_id).className + " error";
document.getElementById(current_elem_id).focus();
}
}
if (invalid.length > 0) {
invalid += "\\n" + "'; echo smarty_function_xl(array('t' => "Please correct the value(s) before proceeding!"), $this); echo '";
alert(invalid);
return false;
} else {
return top.restoreSession();
}
}
</script>
<style type="text/css" title="mystyles" media="all">
.title {
font-size: 120%;
font-weight: bold;
}
.currentvalues {
border-right: 1px solid black;
padding-right:5px;
text-align: left;
}
.valuesunfocus {
border-right: 1px solid black;
padding-right:5px;
background-color: #ccc;
text-align: left;
}
.unfocus {
background-color: #ccc;
}
.historicalvalues {
background-color: #ccc;
border-bottom: 1px solid #ddd;
border-right: 1px solid #ddd;
text-align: right;
}
table {
border-collapse: collapse;
}
td,th {
padding-right: 10px;
padding-left: 10px;
}
.hide {
display:none;
}
.readonly {
display:none;
}
.error {
border:2px solid red;
}
</style>
'; ?>
</head>
<body bgcolor="<?php echo $this->_tpl_vars['STYLE']['BGCOLOR2']; ?>
">
<p><table><tr><td><span class="title"><?php echo smarty_function_xl(array('t' => 'Vitals'), $this);?>
</span></td><td> <a href="../summary/demographics.php" class="readonly css_button_small" onclick="top.restoreSession()"> <span><?php echo smarty_function_xl(array('t' => 'View Patient'), $this);?>
</span></a></td></tr></table></p>
<form name="vitals" method="post" action="<?php echo $this->_tpl_vars['FORM_ACTION']; ?>
/interface/forms/vitals/save.php" onSubmit="return vitalsFormSubmitted()">
<div id="chart"></div>
<table>
<tr><th align="left"><?php echo smarty_function_xl(array('t' => 'Name'), $this);?>
</th><th align="left"><?php echo smarty_function_xl(array('t' => 'Unit'), $this);?>
</th>
<th class='currentvalues' title='<?php echo smarty_function_xl(array('t' => 'Date and time of this observation'), $this);?>
'>
<input type='text' size='14' name='date' id='date'
value='<?php echo ((is_array($_tmp=$this->_tpl_vars['vitals']->get_date())) ? $this->_run_mod_handler('date_format', true, $_tmp, "%Y-%m-%d %H:%M") : smarty_modifier_date_format($_tmp, "%Y-%m-%d %H:%M")); ?>
'
onkeyup='datekeyup(this,mypcc,true)' onblur='dateblur(this,mypcc,true)' />
<img src='<?php echo $this->_tpl_vars['FORM_ACTION']; ?>
/interface/pic/show_calendar.gif' id='img_date' align='absbottom'
width='24' height='22' border='0' alt='[?]' style='cursor:pointer' />
</th>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<th class='historicalvalues'><?php echo ((is_array($_tmp=$this->_tpl_vars['result']['date'])) ? $this->_run_mod_handler('date_format', true, $_tmp, "%Y-%m-%d %H:%M") : smarty_modifier_date_format($_tmp, "%Y-%m-%d %H:%M")); ?>
</th>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 4): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus graph" id="weight"><?php else: ?><td class="graph" id="weight"><?php endif; echo smarty_function_xl(array('t' => 'Weight'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'lbs'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' name='weight' id='weight_input' value="<?php if ($this->_tpl_vars['vitals']->get_weight() != 0): echo $this->_tpl_vars['vitals']->get_weight(); endif; ?>" onChange="convLbtoKg('weight_input');" title='<?php echo smarty_function_xl(array('t' => "Decimal pounds or pounds and ounces separated by #(e.g. 5#4)"), $this);?>
'/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php echo $this->_tpl_vars['vitals']->display_weight($this->_tpl_vars['result']['weight']); ?>
</td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 3): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus graph" id="weight_metric"><?php else: ?><td class="graph" id="weight_metric"><?php endif; echo smarty_function_xl(array('t' => 'Weight'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'kg'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' id='weight_input_metric' value="<?php if ($this->_tpl_vars['vitals']->get_weight() != 0): echo smarty_function_math(array('equation' => "number * constant",'number' => $this->_tpl_vars['vitals']->get_weight(),'constant' => "0.45359237",'format' => "%.2f"), $this); endif; ?>" onChange="convKgtoLb('weight_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['weight'] != 0): echo smarty_function_math(array('equation' => "number * constant",'number' => $this->_tpl_vars['result']['weight'],'constant' => "0.45359237",'format' => "%.2f"), $this); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 4): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus graph" id="height"><?php else: ?><td class="graph" id="height"><?php endif; echo smarty_function_xl(array('t' => "Height/Length"), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'in'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' name='height' id='height_input' value="<?php if ($this->_tpl_vars['vitals']->get_height() != 0): echo $this->_tpl_vars['vitals']->get_height(); endif; ?>" onChange="convIntoCm('height_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['height'] != 0): echo $this->_tpl_vars['result']['height']; endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 3): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus graph" id="height_metric"><?php else: ?><td class="graph" id="height_metric"><?php endif; echo smarty_function_xl(array('t' => "Height/Length"), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'cm'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' id='height_input_metric' value="<?php if ($this->_tpl_vars['vitals']->get_height() != 0): echo smarty_function_math(array('equation' => "number * constant",'number' => $this->_tpl_vars['vitals']->get_height(),'constant' => "2.54",'format' => "%.2f"), $this); endif; ?>" onChange="convCmtoIn('height_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['height'] != 0): echo smarty_function_math(array('equation' => "number * constant",'number' => $this->_tpl_vars['result']['height'],'constant' => "2.54",'format' => "%.2f"), $this); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr><td class="graph" id="bps"><?php echo smarty_function_xl(array('t' => 'BP Systolic'), $this);?>
</td><td><?php echo smarty_function_xl(array('t' => 'mmHg'), $this);?>
</td>
<td class='currentvalues'><input type="text" size='5'
name='bps' id='bps_input' value="<?php echo $this->_tpl_vars['vitals']->get_bps(); ?>
"/></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php echo $this->_tpl_vars['result']['bps']; ?>
</td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr><td class="graph" id="bpd"><?php echo smarty_function_xl(array('t' => 'BP Diastolic'), $this);?>
</td><td><?php echo smarty_function_xl(array('t' => 'mmHg'), $this);?>
</td>
<td class='currentvalues'><input type="text" size='5'
name='bpd' id='bpd_input' value="<?php echo $this->_tpl_vars['vitals']->get_bpd(); ?>
"/></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php echo $this->_tpl_vars['result']['bpd']; ?>
</td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr><td class="graph" id="pulse"><?php echo smarty_function_xl(array('t' => 'Pulse'), $this);?>
</td><td><?php echo smarty_function_xl(array('t' => 'per min'), $this);?>
</td>
<td class='currentvalues'><input type="text" size='5'
name='pulse' id='pulse_input' value="<?php if ($this->_tpl_vars['vitals']->get_pulse() != 0): echo ((is_array($_tmp=$this->_tpl_vars['vitals']->get_pulse())) ? $this->_run_mod_handler('string_format', true, $_tmp, "%.0f") : smarty_modifier_string_format($_tmp, "%.0f")); endif; ?>"/></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['pulse'] != 0): echo ((is_array($_tmp=$this->_tpl_vars['result']['pulse'])) ? $this->_run_mod_handler('string_format', true, $_tmp, "%.0f") : smarty_modifier_string_format($_tmp, "%.0f")); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr><td class="graph" id="respiration"><?php echo smarty_function_xl(array('t' => 'Respiration'), $this);?>
</td><td><?php echo smarty_function_xl(array('t' => 'per min'), $this);?>
</td>
<td class='currentvalues'><input type="text" size='5'
name='respiration' id='respiration_input' value="<?php if ($this->_tpl_vars['vitals']->get_respiration() != 0): echo ((is_array($_tmp=$this->_tpl_vars['vitals']->get_respiration())) ? $this->_run_mod_handler('string_format', true, $_tmp, "%.0f") : smarty_modifier_string_format($_tmp, "%.0f")); endif; ?>"/></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['respiration'] != 0): echo ((is_array($_tmp=$this->_tpl_vars['result']['respiration'])) ? $this->_run_mod_handler('string_format', true, $_tmp, "%.0f") : smarty_modifier_string_format($_tmp, "%.0f")); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 4): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus graph" id="temperature"><?php else: ?><td class="graph" id="temperature"><?php endif; echo smarty_function_xl(array('t' => 'Temperature'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'F'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' name='temperature' id='temperature_input' value="<?php if ($this->_tpl_vars['vitals']->get_temperature() != 0): echo $this->_tpl_vars['vitals']->get_temperature(); endif; ?>" onChange="convFtoC('temperature_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['temperature'] != 0): echo $this->_tpl_vars['result']['temperature']; endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 3): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus graph" id="temperature_metric"><?php else: ?><td class="graph" id="temperature_metric"><?php endif; echo smarty_function_xl(array('t' => 'Temperature'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'C'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' id='temperature_input_metric' value="<?php if ($this->_tpl_vars['vitals']->get_temperature() != 0): echo smarty_function_math(array('equation' => "(number - constant2 ) * constant",'number' => $this->_tpl_vars['vitals']->get_temperature(),'constant' => "0.5556",'constant2' => 32,'format' => "%.2f"), $this); endif; ?>" onChange="convCtoF('temperature_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['temperature'] != 0): echo smarty_function_math(array('equation' => "(number - constant2 ) * constant",'number' => $this->_tpl_vars['result']['temperature'],'constant' => "0.5556",'constant2' => 32,'format' => "%.2f"), $this); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr><td><?php echo smarty_function_xl(array('t' => 'Temp Location'), $this);?>
<td></td></td>
<td class='currentvalues'><select name="temp_method" id='temp_method'/><option value=""> </option>
<option value="Oral" <?php if ($this->_tpl_vars['vitals']->get_temp_method() == 'Oral' || $this->_tpl_vars['vitals']->get_temp_method() == 2): ?> selected<?php endif; ?>><?php echo smarty_function_xl(array('t' => 'Oral'), $this);?>
<option value="Tympanic Membrane" <?php if ($this->_tpl_vars['vitals']->get_temp_method() == 'Tympanic Membrane' || $this->_tpl_vars['vitals']->get_temp_method() == 1): ?> selected<?php endif; ?>><?php echo smarty_function_xl(array('t' => 'Tympanic Membrane'), $this);?>
<option value="Rectal" <?php if ($this->_tpl_vars['vitals']->get_temp_method() == 'Rectal' || $this->_tpl_vars['vitals']->get_temp_method() == 3): ?> selected<?php endif; ?>><?php echo smarty_function_xl(array('t' => 'Rectal'), $this);?>
<option value="Axillary" <?php if ($this->_tpl_vars['vitals']->get_temp_method() == 'Axillary' || $this->_tpl_vars['vitals']->get_temp_method() == 4): ?> selected<?php endif; ?>><?php echo smarty_function_xl(array('t' => 'Axillary'), $this);?>
<option value="Temporal Artery" <?php if ($this->_tpl_vars['vitals']->get_temp_method() == 'Temporal Artery'): ?> selected<?php endif; ?>><?php echo smarty_function_xl(array('t' => 'Temporal Artery'), $this);?>
</select></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['temp_method']): echo smarty_function_xl(array('t' => $this->_tpl_vars['result']['temp_method']), $this); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr><td class="graph" id="oxygen_saturation"><?php echo smarty_function_xl(array('t' => 'Oxygen Saturation'), $this);?>
</td><td><?php echo smarty_function_xl(array('t' => "%"), $this);?>
</td>
<td class='currentvalues'><input type="text" size='5'
name='oxygen_saturation' id='oxygen_saturation_input' value="<?php if ($this->_tpl_vars['vitals']->get_oxygen_saturation() != 0): echo ((is_array($_tmp=$this->_tpl_vars['vitals']->get_oxygen_saturation())) ? $this->_run_mod_handler('string_format', true, $_tmp, "%.0f") : smarty_modifier_string_format($_tmp, "%.0f")); endif; ?>"/></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['oxygen_saturation'] != 0): echo ((is_array($_tmp=$this->_tpl_vars['result']['oxygen_saturation'])) ? $this->_run_mod_handler('string_format', true, $_tmp, "%.0f") : smarty_modifier_string_format($_tmp, "%.0f")); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 4 || $this->_tpl_vars['gbl_vitals_options'] > 0): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus graph" id="head_circ"><?php else: ?><td class="graph" id="head_circ"><?php endif; echo smarty_function_xl(array('t' => 'Head Circumference'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'in'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' name='head_circ' id='head_circ_input' value="<?php if ($this->_tpl_vars['vitals']->get_head_circ() != 0): echo $this->_tpl_vars['vitals']->get_head_circ(); endif; ?>" onChange="convIntoCm('head_circ_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['head_circ'] != 0): echo $this->_tpl_vars['result']['head_circ']; endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 3 || $this->_tpl_vars['gbl_vitals_options'] > 0): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus graph" id="head_circ_metric"><?php else: ?><td class="graph" id="head_circ_metric"><?php endif; echo smarty_function_xl(array('t' => 'Head Circumference'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'cm'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' id='head_circ_input_metric' value="<?php if ($this->_tpl_vars['vitals']->get_head_circ() != 0): echo smarty_function_math(array('equation' => "number * constant",'number' => $this->_tpl_vars['vitals']->get_head_circ(),'constant' => "2.54",'format' => "%.2f"), $this); endif; ?>" onChange="convCmtoIn('head_circ_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['head_circ'] != 0): echo smarty_function_math(array('equation' => "number * constant",'number' => $this->_tpl_vars['result']['head_circ'],'constant' => "2.54",'format' => "%.2f"), $this); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 4 || $this->_tpl_vars['gbl_vitals_options'] > 0): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus graph" id="waist_circ"><?php else: ?><td class="graph" id="waist_circ"><?php endif; echo smarty_function_xl(array('t' => 'Waist Circumference'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'in'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 2): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' name='waist_circ' id='waist_circ_input' value="<?php if ($this->_tpl_vars['vitals']->get_waist_circ() != 0): echo $this->_tpl_vars['vitals']->get_waist_circ(); endif; ?>" onChange="convIntoCm('waist_circ_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['waist_circ'] != 0): echo $this->_tpl_vars['result']['waist_circ']; endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<?php if ($this->_tpl_vars['units_of_measurement'] == 3 || $this->_tpl_vars['gbl_vitals_options'] > 0): ?><tr class="hide"><?php else: ?><tr><?php endif; ?>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus graph" id="waist_circ_metric"><?php else: ?><td class="graph" id="waist_circ_metric"><?php endif; echo smarty_function_xl(array('t' => 'Waist Circumference'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="unfocus"><?php else: ?><td><?php endif; echo smarty_function_xl(array('t' => 'cm'), $this);?>
</td>
<?php if ($this->_tpl_vars['units_of_measurement'] == 1): ?><td class="valuesunfocus"><?php else: ?><td class='currentvalues'><?php endif; ?>
<input type="text" size='5' id='waist_circ_input_metric' value="<?php if ($this->_tpl_vars['vitals']->get_waist_circ() != 0): echo smarty_function_math(array('equation' => "number * constant",'number' => $this->_tpl_vars['vitals']->get_waist_circ(),'constant' => "2.54",'format' => "%.2f"), $this); endif; ?>" onChange="convCmtoIn('waist_circ_input');"/>
</td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['waist_circ'] != 0): echo smarty_function_math(array('equation' => "number * constant",'number' => $this->_tpl_vars['result']['waist_circ'],'constant' => "2.54",'format' => "%.2f"), $this); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr><td class="graph" id="BMI"><?php echo smarty_function_xl(array('t' => 'BMI'), $this);?>
</td><td><?php echo smarty_function_xl(array('t' => "kg/m^2"), $this);?>
</td>
<td class='currentvalues'><input type="text" size='5'
name='BMI' id='BMI_input' value="<?php if ($this->_tpl_vars['vitals']->get_BMI() != 0): echo ((is_array($_tmp=$this->_tpl_vars['vitals']->get_BMI())) ? $this->_run_mod_handler('substr', true, $_tmp, 0, 5) : substr($_tmp, 0, 5)); endif; ?>"/></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['BMI'] != 0): echo ((is_array($_tmp=$this->_tpl_vars['result']['BMI'])) ? $this->_run_mod_handler('substr', true, $_tmp, 0, 5) : substr($_tmp, 0, 5)); endif; ?></td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr><td><?php echo smarty_function_xl(array('t' => 'BMI Status'), $this);?>
</td><td><?php echo smarty_function_xl(array('t' => 'Type'), $this);?>
</td>
<td class='currentvalues'><input type="text" size='15'
name="BMI_status" id="BMI_status' value="<?php echo $this->_tpl_vars['vitals']->get_BMI_status(); ?>
"/></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php if ($this->_tpl_vars['result']['BMI_status']): echo smarty_function_xl(array('t' => $this->_tpl_vars['result']['BMI_status']), $this); endif; ?></td>
<?php endforeach; unset($_from); endif; ?>
</tr>
<tr><td><?php echo smarty_function_xl(array('t' => 'Other Notes'), $this);?>
<td></td></td>
<td class='currentvalues'><input type="text" size='20'
name="note" id='note' value="<?php echo $this->_tpl_vars['vitals']->get_note(); ?>
" /></td>
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
<td class='historicalvalues'><?php echo $this->_tpl_vars['result']['note']; ?>
</td>
<?php endforeach; unset($_from); endif; ?></tr>
<tr>
<td colspan='3' style='text-align:center'>
<?php if ($this->_tpl_vars['patient_age'] <= 20 || ( preg_match ( '/month/' , $this->_tpl_vars['patient_age'] ) )): ?>
<!-- only show growth-chart button for patients < 20 years old -->
<!-- <input type="button" id="growthchart" value="<?php echo smarty_function_xl(array('t' => "Growth-Chart"), $this);?>
" style='margin-left: 20px;'> -->
<input type="button" id="pdfchart" value="<?php echo smarty_function_xl(array('t' => "Growth-Chart"), $this);?>
(<?php echo smarty_function_xl(array('t' => 'PDF'), $this);?>
)" style='margin-left: 20px;'>
<input type="button" id="htmlchart" value="<?php echo smarty_function_xl(array('t' => "Growth-Chart"), $this);?>
(<?php echo smarty_function_xl(array('t' => 'HTML'), $this);?>
)" style='margin-left: 20px;'>
<?php endif; ?>
</td>
</tr>
<tr><td colspan='3' style='text-align:center'> </td></tr>
<tr>
<td colspan='3' style='text-align:center'>
<input type="submit" class="editonly" name="Submit" value="<?php echo smarty_function_xl(array('t' => 'Save Form'), $this);?>
">
<input type="button" class="editonly" id="cancel" value="<?php echo smarty_function_xl(array('t' => "Don't Save"), $this);?>
">
</td>
</tr>
</table>
<br><br>
<input type="hidden" name="id" id='id' value="<?php echo $this->_tpl_vars['vitals']->get_id(); ?>
" />
<input type="hidden" name="activity" id='activity' value="<?php echo $this->_tpl_vars['vitals']->get_activity(); ?>
">
<input type="hidden" name="pid" id='pid' value="<?php echo $this->_tpl_vars['vitals']->get_pid(); ?>
">
<input type="hidden" name="process" id='process' value="true">
</form>
</body>
<script language="javascript">
var formdate = '<?php echo ((is_array($_tmp=$this->_tpl_vars['vitals']->get_date())) ? $this->_run_mod_handler('date_format', true, $_tmp, "%Y%m%d") : smarty_modifier_date_format($_tmp, "%Y%m%d")); ?>
';
// vitals array elements are in the format:
// date-height-weight-head_circumference
var vitals = new Array();
// get values from the current form elements
vitals[0] = formdate+'-<?php echo $this->_tpl_vars['vitals']->get_height(); ?>
-<?php echo $this->_tpl_vars['vitals']->get_weight(); ?>
-<?php echo $this->_tpl_vars['vitals']->get_head_circ(); ?>
';
// historic values
<?php if (count($_from = (array)$this->_tpl_vars['results'])):
foreach ($_from as $this->_tpl_vars['result']):
?>
vitals[vitals.length] = '<?php echo ((is_array($_tmp=$this->_tpl_vars['result']['date'])) ? $this->_run_mod_handler('date_format', true, $_tmp, "%Y%m%d") : smarty_modifier_date_format($_tmp, "%Y%m%d")); ?>
-<?php echo $this->_tpl_vars['result']['height']; ?>
-<?php echo $this->_tpl_vars['result']['weight']; ?>
-<?php echo $this->_tpl_vars['result']['head_circ']; ?>
';
<?php endforeach; unset($_from); endif; ?>
var patientAge='<?php echo $this->_tpl_vars['patient_age']; ?>
';
var patient_dob='<?php echo $this->_tpl_vars['patient_dob']; ?>
';
var webroot = '<?php echo $this->_tpl_vars['FORM_ACTION']; ?>
';
var pid = '<?php echo $this->_tpl_vars['vitals']->get_pid(); ?>
';
var cancellink = '<?php echo $this->_tpl_vars['DONT_SAVE_LINK']; ?>
';
var birth_xl='<?php echo smarty_function_xl(array('t' => "Birth-24 months"), $this);?>
'
var older_xl='<?php echo smarty_function_xl(array('t' => "2-20 years"), $this);?>
';
<?php echo '
function addGCSelector()
{
var options=new Array();
var birth={\'display\':birth_xl,\'param\':\'birth\'};
var age2={\'display\':older_xl,\'param\':\'2-20\'}
if((patientAge.indexOf(\'24 month\')>=0) || (patientAge.indexOf(\'month\')==-1))
{
var dob_data=patient_dob.split("-");
var dob_date=new Date(dob_data[0],parseInt(dob_data[1])-1,dob_data[2]);
options[0]=age2;
for(var idx=0;idx<vitals.length;idx++)
{
var str_data_date=vitals[idx].split("-")[0];
var data_date=new Date(str_data_date.substr(0,4),parseInt(str_data_date.substr(4,2))-1,str_data_date.substr(6,2));
if(((data_date-dob_date)/86400000)<=2*365)
{
idx=vitals.length;
options[1]=birth
}
}
}
else
{
options[0]=birth;
}
var chart_buttons_cell=$("#pdfchart").parent("td");
var select=$("<select id=\'chart_type\'></select>");
chart_buttons_cell.prepend(select);
for(idx=0;idx<options.length;idx++)
{
var option=$("<option value=\'"+options[idx].param+"\'>"+options[idx].display+"</option>");
select.append(option);
}
select.find("option:first").attr("selected","true");
if(options.length<2)
{
select.css("display","none");
}
}
$(document).ready(function(){
$("#growthchart").click(function() { ShowGrowthchart(); });
$("#pdfchart").click(function() { ShowGrowthchart(1); });
$("#htmlchart").click(function() { ShowGrowthchart(2); });
$("#cancel").click(function() { location.href=cancellink; });
addGCSelector();
});
function ShowGrowthchart(doPDF) {
// get values from the current form elements
'; ?>
vitals[0] = formdate+'-'+$("#height_input").val()+'-'+$("#weight_input").val()+'-'+$("#head_circ_input").val();
<?php echo '
// build the data string
var datastring = "";
for(var i=0; i<vitals.length; i++) {
datastring += vitals[i]+"~";
}
newURL = webroot+\'/interface/forms/vitals/growthchart/chart.php?pid=\'+pid+\'&data=\'+datastring;
if (doPDF == 1) newURL += "&pdf=1";
if (doPDF == 2) newURL += "&html=1";
newURL+="&chart_type="+$("#chart_type").val();
// do the new window stuff
top.restoreSession();
window.open(newURL, \'_blank\', "menubar=1,toolbar=1,scrollbars=1,resizable=1,width=600,height=450");
}
function convLbtoKg(name) {
var lb = $("#"+name).val();
var hash_loc=lb.indexOf("#");
if(hash_loc>=0)
{
var pounds=lb.substr(0,hash_loc);
var ounces=lb.substr(hash_loc+1);
var num=parseInt(pounds)+parseInt(ounces)/16;
lb=num;
$("#"+name).val(lb);
}
if (lb == "0") {
$("#"+name+"_metric").val("0");
}
else if (lb == parseFloat(lb)) {
kg = lb*0.45359237;
kg = kg.toFixed(2);
$("#"+name+"_metric").val(kg);
}
else {
$("#"+name+"_metric").val("");
}
if (name == "weight_input") {
calculateBMI();
}
}
function convKgtoLb(name) {
var kg = $("#"+name+"_metric").val();
if (kg == "0") {
$("#"+name).val("0");
}
else if (kg == parseFloat(kg)) {
lb = kg/0.45359237;
lb = lb.toFixed(2);
$("#"+name).val(lb);
}
else {
$("#"+name).val("");
}
if (name == "weight_input") {
calculateBMI();
}
}
function convIntoCm(name) {
var inch = $("#"+name).val();
if (inch == "0") {
$("#"+name+"_metric").val("0");
}
else if (inch == parseFloat(inch)) {
cm = inch*2.54;
cm = cm.toFixed(2);
$("#"+name+"_metric").val(cm);
}
else {
$("#"+name+"_metric").val("");
}
if (name == "height_input") {
calculateBMI();
}
}
function convCmtoIn(name) {
var cm = $("#"+name+"_metric").val();
if (cm == "0") {
$("#"+name).val("0");
}
else if (cm == parseFloat(cm)) {
inch = cm/2.54;
inch = inch.toFixed(2);
$("#"+name).val(inch);
}
else {
$("#"+name).val("");
}
if (name == "height_input") {
calculateBMI();
}
}
function convFtoC(name) {
var Fdeg = $("#"+name).val();
if (Fdeg == "0") {
$("#"+name+"_metric").val("0");
}
else if (Fdeg == parseFloat(Fdeg)) {
Cdeg = (Fdeg-32)*0.5556;
Cdeg = Cdeg.toFixed(2);
$("#"+name+"_metric").val(Cdeg);
}
else {
$("#"+name+"_metric").val("");
}
}
function convCtoF(name) {
var Cdeg = $("#"+name+"_metric").val();
if (Cdeg == "0") {
$("#"+name).val("0");
}
else if (Cdeg == parseFloat(Cdeg)) {
Fdeg = (Cdeg/0.5556)+32;
Fdeg = Fdeg.toFixed(2);
$("#"+name).val(Fdeg);
}
else {
$("#"+name).val("");
}
}
function calculateBMI() {
var bmi = 0;
var height = $("#height_input").val();
var weight = $("#weight_input").val();
if(height == 0 || weight == 0) {
$("#BMI").val("");
}
else if((height == parseFloat(height)) && (weight == parseFloat(weight))) {
bmi = weight/height/height*703;
bmi = bmi.toFixed(1);
$("#BMI_input").val(bmi);
}
else {
$("#BMI_input").val("");
}
}
Calendar.setup({inputField:"date", ifFormat:"%Y-%m-%d %H:%M", button:"img_date", showsTime:true});
</script>
'; ?>
</html> | stephenwaite/cmsopenemr | interface/main/calendar/modules/PostCalendar/pntemplates/compiled/%%-13^%%-1326759229^general_new.html.php | PHP | gpl-3.0 | 38,858 |
#!/usr/bin/env python
"""
crate_anon/nlp_manager/number.py
===============================================================================
Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CRATE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CRATE. If not, see <https://www.gnu.org/licenses/>.
===============================================================================
**Number conversion functions.**
"""
from typing import Optional
def to_float(s: str) -> Optional[float]:
"""
Convert a string to a float, or return ``None``.
Before converting:
- strips out commas (as thousands separator); this is not internationalized
well!
- replace Unicode minus and en dash with a hyphen (minus sign)
"""
if s:
s = s.replace(',', '') # comma as thousands separator
s = s.replace('−', '-') # Unicode minus
s = s.replace('–', '-') # en dash
try:
return float(s)
except (TypeError, ValueError):
return None
def to_pos_float(s: str) -> Optional[float]:
"""
Converts a string to a positive float, by using :func:`to_float` followed
by :func:`abs`. Returns ``None`` on failure.
"""
try:
return abs(to_float(s))
except TypeError: # to_float() returned None
return None
| RudolfCardinal/crate | crate_anon/nlp_manager/number.py | Python | gpl-3.0 | 1,874 |
<?php
/**
* Created by PhpStorm.
* Project : My-Resume-PHP.
* User: Hamza Alayed
* Date: 5/8/14
* Time: 5:56 PM
*/ ?>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Hamza Alayed Resume</title>
<link rel="shortcut icon" type="image/x-icon" href=""/>
<link rel="stylesheet" type="text/css" media="all"
href="<?php echo base_url()?>assets/style/style.css">
<link rel="stylesheet" type="text/css" media="all"
href="<?php echo base_url()?>assets/style/responsive.css">
</head> | developh/My-Resume-PHP | application/views/Head.php | PHP | gpl-3.0 | 607 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using VRStandardAssets.Utils;
using System.Diagnostics;
public class InteractionPanel : MonoBehaviour {
[SerializeField] private VRInput input;
[SerializeField] private VRCameraFade fader;
[SerializeField] private Transform cameraTransform;
[SerializeField] private float distance = 5;
[SerializeField] private VRUIAnimationClick btnTeclado;
[SerializeField] private VRUIAnimationClick btnRec;
[SerializeField] private TextMesh speechRecognitionResult;
[SerializeField] private GCSpeechRecognition speechRecognition;
[SerializeField] GameObject panelSub;
[SerializeField] GameObject panelInput;
[SerializeField] GameObject teclado;
//[SerializeField] GameObject hintButton;
//[SerializeField] GameObject skipButton;
[SerializeField] Text keyboardInp;
[SerializeField] GameObject panelAnswer;
[SerializeField] GameObject panelQuestion;
//[SerializeField] GameObject panelHint;
[SerializeField] GameObject panelHintText;
[SerializeField] GameObject panelSkipHint;
[SerializeField] GameObject gifRipple;
[SerializeField] GameObject gifProcessing;
[SerializeField] GameObject noWifi;
[SerializeField] TextMesh answer;
[SerializeField] Material UI_SpeechStart;
[SerializeField] Material UI_SpeechStop;
[SerializeField] private MediaManager mediaManager;
[SerializeField] private Blinker blinker;
Stopwatch counter;
bool recording;
// Use this for initialization
void Start () {
if (btnRec != null)
{
btnRec.OnAnimationComplete += StartRecordButtonOnClickHandler;
}
if (btnTeclado != null)
{
btnTeclado.OnAnimationComplete += ButtonTecladoOnClick;
}
noWifi.SetActive (false);
speechRecognition = GCSpeechRecognition.Instance;
//speechRecognition.RecognitionSuccessEvent += SpeechRecognizedSuccessEventHandler; // Posiblemente
//speechRecognition.RecognitionFailedEvent += SpeechRecognizedFailedEventHandler; // redundantes
recording = false;
this.counter = new Stopwatch ();
}
// Update is called once per frame
// Update is called once per frame
void Update () {
if (recording && ElapsedTime (10000)) {
Timeout ();
}
}
void Restart ()
{
this.counter.Reset ();
this.counter.Start ();
}
bool ElapsedTime(int seconds)
{
return this.counter.ElapsedMilliseconds > seconds;
}
private void ButtonTecladoOnClick()
{
mediaManager.SetInactiveButtonGuia ();
panelSub.SetActive (false);
panelInput.SetActive (false);
teclado.SetActive (true);
panelSkipHint.SetActive(false);
//hintButton.SetActive(false);
//skipButton.SetActive(false);
panelQuestion.SetActive (false);
panelHintText.SetActive (false);
//panelHint.SetActive (false);
panelAnswer.SetActive (false);
keyboardInp.text = "";
}
private void OnDestroy()
{
speechRecognition.RecognitionSuccessEvent -= SpeechRecognizedSuccessEventHandler;
speechRecognition.RecognitionFailedEvent -= SpeechRecognizedFailedEventHandler;
}
private void StartRecordButtonOnClickHandler()
{
mediaManager.SetInactiveButtonGuia ();
speechRecognition.RecognitionSuccessEvent += SpeechRecognizedSuccessEventHandler;
speechRecognition.RecognitionFailedEvent += SpeechRecognizedFailedEventHandler;
bool connection = CheckConnectivity.checkInternetStatus ();
if (connection) {
speechRecognitionResult.text = string.Empty;
speechRecognitionResult.text = "Recording...";
answer.text = "";
gifRipple.SetActive (true);
gifProcessing.SetActive (false);
if (btnRec != null) {
btnRec.GetComponent<Renderer> ().material = UI_SpeechStop;
btnRec.OnAnimationComplete -= StartRecordButtonOnClickHandler;
btnRec.OnAnimationComplete += StopRecordButtonOnClickHandler;
}
Restart ();
recording = true;
speechRecognition.StartRecord (false);
} else
{
noWifi.SetActive (true);
blinker.SetComponent (ref noWifi, 10);
mediaManager.DisplayWarningMessage("No hay conexión a Internet");
}
}
private void StopRecordButtonOnClickHandler()
{
if(btnRec != null)
{
btnRec.GetComponent<Renderer>().material = UI_SpeechStart;
btnRec.OnAnimationComplete -= StopRecordButtonOnClickHandler;
btnRec.OnAnimationComplete += StartRecordButtonOnClickHandler;
}
// this.counter.Stop ();
gifRipple.SetActive (false);
speechRecognition.StopRecord();
// recording = false;
gifProcessing.SetActive (true);
}
private void Timeout()
{
if(btnRec != null)
{
btnRec.GetComponent<Renderer>().material = UI_SpeechStart;
btnRec.OnAnimationComplete -= StopRecordButtonOnClickHandler;
btnRec.OnAnimationComplete += StartRecordButtonOnClickHandler;
}
this.counter.Stop ();
gifRipple.SetActive (false);
gifProcessing.SetActive (false);
speechRecognition.StopRecord();
recording = false;
mediaManager.DisplayWarningMessage("No se detectaron palabras.");
}
private void LanguageDropdownOnValueChanged(int value)
{
value = 1;
speechRecognition.SetLanguage((Enumerators.LanguageCode)value);
}
private void SpeechRecognizedFailedEventHandler(string obj, long requestIndex)
{
speechRecognition.RecognitionSuccessEvent -= SpeechRecognizedSuccessEventHandler;
speechRecognition.RecognitionFailedEvent -= SpeechRecognizedFailedEventHandler;
}
private void SpeechRecognizedSuccessEventHandler(RecognitionResponse obj, long requestIndex)
{
this.counter.Stop ();
recording = false;
gifProcessing.SetActive (false);
if (obj != null && obj.results.Length > 0)
{
speechRecognitionResult.text = obj.results[0].alternatives[0].transcript;
}
mediaManager.ValidateAnswer (speechRecognitionResult.text);
speechRecognition.RecognitionSuccessEvent -= SpeechRecognizedSuccessEventHandler;
speechRecognition.RecognitionFailedEvent -= SpeechRecognizedFailedEventHandler;
}
}
| s-varela/learningmr | src/prototypes/lesson1/lesson1/Assets/Media/EasyMovieTexture/Scripts/InteractionPanel.cs | C# | gpl-3.0 | 5,888 |
<?php
/* ext/sex.php - NexusServV3
* Copyright (C) 2012-2013 #Nexus project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if ($chan[0] == "#") {
if ($toys == "" || $toys == "0") {
echo("NOTICE $nick :Toys are disabled in \002$chan\002.\n");
}
elseif ($toys == "1") {
echo("NOTICE $nick :I want to be a part of your sick fantasies!\n");
}
elseif ($toys == "2") {
echo("PRIVMSG $chan :\002$nick\002: I want to be a part of your sick fantasies!\n");
}
}
else {
echo("NOTICE $nick :I want to be a part of your sick fantasies!\n");
}
?> | Nexus-IRC/NexusServV3 | ext/sex.php | PHP | gpl-3.0 | 1,157 |
"""!
@brief Cluster analysis algorithm: Expectation-Maximization Algorithm for Gaussian Mixture Model.
@details Implementation based on paper @cite article::ema::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
import numpy
import random
from pyclustering.cluster import cluster_visualizer
from pyclustering.cluster.center_initializer import kmeans_plusplus_initializer
from pyclustering.cluster.kmeans import kmeans
from pyclustering.utils import pi, calculate_ellipse_description, euclidean_distance_square
from enum import IntEnum
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import patches
def gaussian(data, mean, covariance):
"""!
@brief Calculates gaussian for dataset using specified mean (mathematical expectation) and variance or covariance in case
multi-dimensional data.
@param[in] data (list): Data that is used for gaussian calculation.
@param[in] mean (float|numpy.array): Mathematical expectation used for calculation.
@param[in] covariance (float|numpy.array): Variance or covariance matrix for calculation.
@return (list) Value of gaussian function for each point in dataset.
"""
dimension = float(len(data[0]))
if dimension != 1.0:
inv_variance = numpy.linalg.pinv(covariance)
else:
inv_variance = 1.0 / covariance
divider = (pi * 2.0) ** (dimension / 2.0) * numpy.sqrt(numpy.linalg.norm(covariance))
if divider != 0.0:
right_const = 1.0 / divider
else:
right_const = float('inf')
result = []
for point in data:
mean_delta = point - mean
point_gaussian = right_const * numpy.exp( -0.5 * mean_delta.dot(inv_variance).dot(numpy.transpose(mean_delta)) )
result.append(point_gaussian)
return result
class ema_init_type(IntEnum):
"""!
@brief Enumeration of initialization types for Expectation-Maximization algorithm.
"""
## Means are randomly taken from input dataset and variance or covariance is calculated based on
## spherical data that belongs to the chosen means.
RANDOM_INITIALIZATION = 0
## Two step initialization. The first is calculation of initial centers using K-Means++ method.
## The second is K-Means clustering using obtained centers in the first step. Obtained clusters
## and its centers are used for calculation of variance (covariance in case of multi-dimensional)
## data.
KMEANS_INITIALIZATION = 1
class ema_initializer():
"""!
@brief Provides services for preparing initial means and covariances for Expectation-Maximization algorithm.
@details Initialization strategy is defined by enumerator 'ema_init_type': random initialization and
kmeans with kmeans++ initialization. Here an example of initialization using kmeans strategy:
@code
from pyclustering.utils import read_sample
from pyclustering.samples.definitions import FAMOUS_SAMPLES
from pyclustering.cluster.ema import ema_initializer
sample = read_sample(FAMOUS_SAMPLES.SAMPLE_OLD_FAITHFUL)
amount_clusters = 2
initial_means, initial_covariance = ema_initializer(sample, amount_clusters).initialize()
print(initial_means)
print(initial_covariance)
@endcode
"""
__MAX_GENERATION_ATTEMPTS = 10
def __init__(self, sample, amount):
"""!
@brief Constructs EM initializer.
@param[in] sample (list): Data that will be used by the EM algorithm.
@param[in] amount (uint): Amount of clusters that should be allocated by the EM algorithm.
"""
self.__sample = sample
self.__amount = amount
def initialize(self, init_type = ema_init_type.KMEANS_INITIALIZATION):
"""!
@brief Calculates initial parameters for EM algorithm: means and covariances using
specified strategy.
@param[in] init_type (ema_init_type): Strategy for initialization.
@return (float|list, float|numpy.array) Initial means and variance (covariance matrix in case multi-dimensional data).
"""
if init_type == ema_init_type.KMEANS_INITIALIZATION:
return self.__initialize_kmeans()
elif init_type == ema_init_type.RANDOM_INITIALIZATION:
return self.__initialize_random()
raise NameError("Unknown type of EM algorithm initialization is specified.")
def __calculate_initial_clusters(self, centers):
"""!
@brief Calculate Euclidean distance to each point from the each cluster.
@brief Nearest points are captured by according clusters and as a result clusters are updated.
@return (list) updated clusters as list of clusters. Each cluster contains indexes of objects from data.
"""
clusters = [[] for _ in range(len(centers))]
for index_point in range(len(self.__sample)):
index_optim, dist_optim = -1, 0.0
for index in range(len(centers)):
dist = euclidean_distance_square(self.__sample[index_point], centers[index])
if (dist < dist_optim) or (index == 0):
index_optim, dist_optim = index, dist
clusters[index_optim].append(index_point)
return clusters
def __calculate_initial_covariances(self, initial_clusters):
covariances = []
for initial_cluster in initial_clusters:
if len(initial_cluster) > 1:
cluster_sample = [self.__sample[index_point] for index_point in initial_cluster]
covariances.append(numpy.cov(cluster_sample, rowvar=False))
else:
dimension = len(self.__sample[0])
covariances.append(numpy.zeros((dimension, dimension)) + random.random() / 10.0)
return covariances
def __initialize_random(self):
initial_means = []
for _ in range(self.__amount):
mean = self.__sample[ random.randint(0, len(self.__sample)) - 1 ]
attempts = 0
while (mean in initial_means) and (attempts < ema_initializer.__MAX_GENERATION_ATTEMPTS):
mean = self.__sample[ random.randint(0, len(self.__sample)) - 1 ]
attempts += 1
if attempts == ema_initializer.__MAX_GENERATION_ATTEMPTS:
mean = [ value + (random.random() - 0.5) * value * 0.2 for value in mean ]
initial_means.append(mean)
initial_clusters = self.__calculate_initial_clusters(initial_means)
initial_covariance = self.__calculate_initial_covariances(initial_clusters)
return initial_means, initial_covariance
def __initialize_kmeans(self):
initial_centers = kmeans_plusplus_initializer(self.__sample, self.__amount).initialize()
kmeans_instance = kmeans(self.__sample, initial_centers, ccore = True)
kmeans_instance.process()
means = kmeans_instance.get_centers()
covariances = []
initial_clusters = kmeans_instance.get_clusters()
for initial_cluster in initial_clusters:
if len(initial_cluster) > 1:
cluster_sample = [ self.__sample[index_point] for index_point in initial_cluster ]
covariances.append(numpy.cov(cluster_sample, rowvar=False))
else:
dimension = len(self.__sample[0])
covariances.append(numpy.zeros((dimension, dimension)) + random.random() / 10.0)
return means, covariances
class ema_observer:
"""!
@brief Observer of EM algorithm for collecting algorithm state on each step.
@details It can be used to obtain whole picture about clustering process of EM algorithm. Allocated clusters,
means and covariances are stored in observer on each step. Here an example of usage:
@code
from pyclustering.cluster.ema import ema, ema_observer
from pyclustering.utils import read_sample
from pyclustering.samples.definitions import SIMPLE_SAMPLES
# Read data from text file.
sample = read_sample(SIMPLE_SAMPLES.SAMPLE_SIMPLE3)
# Create EM observer.
observer = ema_observer()
# Create EM algorithm to allocated four clusters and pass observer to it.
ema_instance = ema(sample, 4, observer=observer)
# Run clustering process.
ema_instance.process()
# Print amount of steps that were done by the algorithm.
print("EMA steps:", observer.get_iterations())
# Print evolution of means and covariances.
print("Means evolution:", observer.get_evolution_means())
print("Covariances evolution:", observer.get_evolution_covariances())
# Print evolution of clusters.
print("Clusters evolution:", observer.get_evolution_clusters())
# Print final clusters.
print("Allocated clusters:", observer.get_evolution_clusters()[-1])
@endcode
"""
def __init__(self):
"""!
@brief Initializes EM observer.
"""
self.__means_evolution = []
self.__covariances_evolution = []
self.__clusters_evolution = []
def __len__(self):
"""!
@return (uint) Amount of iterations that were done by the EM algorithm.
"""
return len(self.__means_evolution)
def get_iterations(self):
"""!
@return (uint) Amount of iterations that were done by the EM algorithm.
"""
return len(self.__means_evolution)
def get_evolution_means(self):
"""!
@return (list) Mean of each cluster on each step of clustering.
"""
return self.__means_evolution
def get_evolution_covariances(self):
"""!
@return (list) Covariance matrix (or variance in case of one-dimensional data) of each cluster on each step of clustering.
"""
return self.__covariances_evolution
def get_evolution_clusters(self):
"""!
@return (list) Allocated clusters on each step of clustering.
"""
return self.__clusters_evolution
def notify(self, means, covariances, clusters):
"""!
@brief This method is used by the algorithm to notify observer about changes where the algorithm
should provide new values: means, covariances and allocated clusters.
@param[in] means (list): Mean of each cluster on currect step.
@param[in] covariances (list): Covariances of each cluster on current step.
@param[in] clusters (list): Allocated cluster on current step.
"""
self.__means_evolution.append(means)
self.__covariances_evolution.append(covariances)
self.__clusters_evolution.append(clusters)
class ema_visualizer:
"""!
@brief Visualizer of EM algorithm's results.
@details Provides services for visualization of particular features of the algorithm, for example,
in case of two-dimensional dataset it shows covariance ellipses.
"""
@staticmethod
def show_clusters(clusters, sample, covariances, means, figure=None, display=True):
"""!
@brief Draws clusters and in case of two-dimensional dataset draws their ellipses.
@details Allocated figure by this method should be closed using `close()` method of this visualizer.
@param[in] clusters (list): Clusters that were allocated by the algorithm.
@param[in] sample (list): Dataset that were used for clustering.
@param[in] covariances (list): Covariances of the clusters.
@param[in] means (list): Means of the clusters.
@param[in] figure (figure): If 'None' then new is figure is creater, otherwise specified figure is used
for visualization.
@param[in] display (bool): If 'True' then figure will be shown by the method, otherwise it should be
shown manually using matplotlib function 'plt.show()'.
@return (figure) Figure where clusters were drawn.
"""
visualizer = cluster_visualizer()
visualizer.append_clusters(clusters, sample)
if figure is None:
figure = visualizer.show(display=False)
else:
visualizer.show(figure=figure, display=False)
if len(sample[0]) == 2:
ema_visualizer.__draw_ellipses(figure, visualizer, clusters, covariances, means)
if display is True:
plt.show()
return figure
@staticmethod
def close(figure):
"""!
@brief Closes figure object that was used or allocated by the visualizer.
@param[in] figure (figure): Figure object that was used or allocated by the visualizer.
"""
plt.close(figure)
@staticmethod
def animate_cluster_allocation(data, observer, animation_velocity = 75, movie_fps = 1, save_movie = None):
"""!
@brief Animates clustering process that is performed by EM algorithm.
@param[in] data (list): Dataset that is used for clustering.
@param[in] observer (ema_observer): EM observer that was used for collection information about clustering process.
@param[in] animation_velocity (uint): Interval between frames in milliseconds (for run-time animation only).
@param[in] movie_fps (uint): Defines frames per second (for rendering movie only).
@param[in] save_movie (string): If it is specified then animation will be stored to file that is specified in this parameter.
"""
figure = plt.figure()
def init_frame():
return frame_generation(0)
def frame_generation(index_iteration):
figure.clf()
figure.suptitle("EM algorithm (iteration: " + str(index_iteration) +")", fontsize = 18, fontweight = 'bold')
clusters = observer.get_evolution_clusters()[index_iteration]
covariances = observer.get_evolution_covariances()[index_iteration]
means = observer.get_evolution_means()[index_iteration]
ema_visualizer.show_clusters(clusters, data, covariances, means, figure, False)
figure.subplots_adjust(top=0.85)
return [figure.gca()]
iterations = len(observer)
cluster_animation = animation.FuncAnimation(figure, frame_generation, iterations, interval = animation_velocity, init_func = init_frame, repeat_delay = 5000)
if save_movie is not None:
cluster_animation.save(save_movie, writer='ffmpeg', fps=movie_fps, bitrate=1500)
else:
plt.show()
plt.close(figure)
@staticmethod
def __draw_ellipses(figure, visualizer, clusters, covariances, means):
ax = figure.get_axes()[0]
for index in range(len(clusters)):
angle, width, height = calculate_ellipse_description(covariances[index])
color = visualizer.get_cluster_color(index, 0)
ema_visualizer.__draw_ellipse(ax, means[index][0], means[index][1], angle, width, height, color)
@staticmethod
def __draw_ellipse(ax, x, y, angle, width, height, color):
if (width > 0.0) and (height > 0.0):
ax.plot(x, y, color=color, marker='x', markersize=6)
ellipse = patches.Ellipse((x, y), width, height, alpha=0.2, angle=-angle, linewidth=2, fill=True, zorder=2, color=color)
ax.add_patch(ellipse)
class ema:
"""!
@brief Expectation-Maximization clustering algorithm for Gaussian Mixture Model (GMM).
@details The algorithm provides only clustering services (unsupervised learning).
Here an example of data clustering process:
@code
from pyclustering.cluster.ema import ema, ema_visualizer
from pyclustering.utils import read_sample
from pyclustering.samples.definitions import FCPS_SAMPLES
# Read data from text file.
sample = read_sample(FCPS_SAMPLES.SAMPLE_LSUN)
# Create EM algorithm to allocated four clusters.
ema_instance = ema(sample, 3)
# Run clustering process.
ema_instance.process()
# Get clustering results.
clusters = ema_instance.get_clusters()
covariances = ema_instance.get_covariances()
means = ema_instance.get_centers()
# Visualize obtained clustering results.
ema_visualizer.show_clusters(clusters, sample, covariances, means)
@endcode
Here is clustering results of the Expectation-Maximization clustering algorithm where popular sample 'OldFaithful' was used.
Initial random means and covariances were used in the example. The first step is presented on the left side of the figure and
final result (the last step) is on the right side:
@image html ema_old_faithful_clustering.png
@see ema_visualizer
@see ema_observer
"""
def __init__(self, data, amount_clusters, means=None, variances=None, observer=None, tolerance=0.00001, iterations=100):
"""!
@brief Initializes Expectation-Maximization algorithm for cluster analysis.
@param[in] data (list): Dataset that should be analysed and where each point (object) is represented by the list of coordinates.
@param[in] amount_clusters (uint): Amount of clusters that should be allocated.
@param[in] means (list): Initial means of clusters (amount of means should be equal to amount of clusters for allocation).
If this parameter is 'None' then K-Means algorithm with K-Means++ method will be used for initialization by default.
@param[in] variances (list): Initial cluster variances (or covariances in case of multi-dimensional data). Amount of
covariances should be equal to amount of clusters that should be allocated. If this parameter is 'None' then
K-Means algorithm with K-Means++ method will be used for initialization by default.
@param[in] observer (ema_observer): Observer for gathering information about clustering process.
@param[in] tolerance (float): Defines stop condition of the algorithm (when difference between current and
previous log-likelihood estimation is less then 'tolerance' then clustering is over).
@param[in] iterations (uint): Additional stop condition parameter that defines maximum number of steps that can be
performed by the algorithm during clustering process.
"""
self.__data = numpy.array(data)
self.__amount_clusters = amount_clusters
self.__tolerance = tolerance
self.__iterations = iterations
self.__observer = observer
self.__means = means
self.__variances = variances
self.__verify_arguments()
if (means is None) or (variances is None):
self.__means, self.__variances = ema_initializer(data, amount_clusters).initialize(ema_init_type.KMEANS_INITIALIZATION)
if len(self.__means) != amount_clusters:
self.__amount_clusters = len(self.__means)
self.__rc = [ [0.0] * len(self.__data) for _ in range(amount_clusters) ]
self.__pic = [1.0] * amount_clusters
self.__clusters = []
self.__gaussians = [ [] for _ in range(amount_clusters) ]
self.__stop = False
def process(self):
"""!
@brief Run clustering process of the algorithm.
@return (ema) Returns itself (EMA instance).
"""
previous_likelihood = -200000
current_likelihood = -100000
current_iteration = 0
while(self.__stop is False) and (abs(previous_likelihood - current_likelihood) > self.__tolerance) and (current_iteration < self.__iterations):
self.__expectation_step()
self.__maximization_step()
current_iteration += 1
self.__extract_clusters()
self.__notify()
previous_likelihood = current_likelihood
current_likelihood = self.__log_likelihood()
self.__stop = self.__get_stop_condition()
self.__normalize_probabilities()
return self
def get_clusters(self):
"""!
@return (list) Allocated clusters where each cluster is represented by list of indexes of points from dataset,
for example, two cluster may have following representation [[0, 1, 4], [2, 3, 5, 6]].
"""
return self.__clusters
def get_centers(self):
"""!
@return (list) Corresponding centers (means) of clusters.
"""
return self.__means
def get_covariances(self):
"""!
@return (list) Corresponding variances (or covariances in case of multi-dimensional data) of clusters.
"""
return self.__variances
def get_probabilities(self):
"""!
@brief Returns 2-dimensional list with belong probability of each object from data to cluster correspondingly,
where that first index is for cluster and the second is for point.
@code
# Get belong probablities
probabilities = ema_instance.get_probabilities();
# Show porbability of the fifth element in the first and in the second cluster
index_point = 5;
print("Probability in the first cluster:", probabilities[0][index_point]);
print("Probability in the first cluster:", probabilities[1][index_point]);
@endcode
@return (list) 2-dimensional list with belong probability of each object from data to cluster.
"""
return self.__rc
def __erase_empty_clusters(self):
clusters, means, variances, pic, gaussians, rc = [], [], [], [], [], []
for index_cluster in range(len(self.__clusters)):
if len(self.__clusters[index_cluster]) > 0:
clusters.append(self.__clusters[index_cluster])
means.append(self.__means[index_cluster])
variances.append(self.__variances[index_cluster])
pic.append(self.__pic[index_cluster])
gaussians.append(self.__gaussians[index_cluster])
rc.append(self.__rc[index_cluster])
if len(self.__clusters) != len(clusters):
self.__clusters, self.__means, self.__variances, self.__pic = clusters, means, variances, pic
self.__gaussians, self.__rc = gaussians, rc
self.__amount_clusters = len(self.__clusters)
def __notify(self):
if self.__observer is not None:
self.__observer.notify(self.__means, self.__variances, self.__clusters)
def __extract_clusters(self):
self.__clusters = [[] for _ in range(self.__amount_clusters)]
for index_point in range(len(self.__data)):
candidates = []
for index_cluster in range(self.__amount_clusters):
candidates.append((index_cluster, self.__rc[index_cluster][index_point]))
index_winner = max(candidates, key=lambda candidate: candidate[1])[0]
self.__clusters[index_winner].append(index_point)
self.__erase_empty_clusters()
def __log_likelihood(self):
likelihood = 0.0
for index_point in range(len(self.__data)):
particle = 0.0
for index_cluster in range(self.__amount_clusters):
particle += self.__pic[index_cluster] * self.__gaussians[index_cluster][index_point]
if particle > 0.0:
likelihood += numpy.log(particle)
return likelihood
def __probabilities(self, index_cluster, index_point):
divider = 0.0
for i in range(self.__amount_clusters):
divider += self.__pic[i] * self.__gaussians[i][index_point]
if (divider != 0.0) and (divider != float('inf')):
return self.__pic[index_cluster] * self.__gaussians[index_cluster][index_point] / divider
return 1.0
def __expectation_step(self):
self.__gaussians = [ [] for _ in range(self.__amount_clusters) ]
for index in range(self.__amount_clusters):
self.__gaussians[index] = gaussian(self.__data, self.__means[index], self.__variances[index])
self.__rc = [ [0.0] * len(self.__data) for _ in range(self.__amount_clusters) ]
for index_cluster in range(self.__amount_clusters):
for index_point in range(len(self.__data)):
self.__rc[index_cluster][index_point] = self.__probabilities(index_cluster, index_point)
def __maximization_step(self):
self.__pic = []
self.__means = []
self.__variances = []
amount_impossible_clusters = 0
for index_cluster in range(self.__amount_clusters):
mc = numpy.sum(self.__rc[index_cluster])
if mc == 0.0:
amount_impossible_clusters += 1
continue
self.__pic.append( mc / len(self.__data) )
self.__means.append( self.__update_mean(self.__rc[index_cluster], mc) )
self.__variances.append( self.__update_covariance(self.__means[-1], self.__rc[index_cluster], mc) )
self.__amount_clusters -= amount_impossible_clusters
def __get_stop_condition(self):
for covariance in self.__variances:
if numpy.linalg.norm(covariance) == 0.0:
return True
return False
def __update_covariance(self, means, rc, mc):
covariance = 0.0
for index_point in range(len(self.__data)):
deviation = numpy.array([self.__data[index_point] - means])
covariance += rc[index_point] * deviation.T.dot(deviation)
covariance = covariance / mc
return covariance
def __update_mean(self, rc, mc):
mean = 0.0
for index_point in range(len(self.__data)):
mean += rc[index_point] * self.__data[index_point]
mean = mean / mc
return mean
def __normalize_probabilities(self):
for index_point in range(len(self.__data)):
probability = 0.0
for index_cluster in range(len(self.__clusters)):
probability += self.__rc[index_cluster][index_point]
if abs(probability - 1.0) > 0.000001:
self.__normalize_probability(index_point, probability)
def __normalize_probability(self, index_point, probability):
if probability == 0.0:
return
normalization = 1.0 / probability
for index_cluster in range(len(self.__clusters)):
self.__rc[index_cluster][index_point] *= normalization
def __verify_arguments(self):
"""!
@brief Verify input parameters for the algorithm and throw exception in case of incorrectness.
"""
if len(self.__data) == 0:
raise ValueError("Input data is empty (size: '%d')." % len(self.__data))
if self.__amount_clusters < 1:
raise ValueError("Amount of clusters (current value '%d') should be greater or equal to 1." %
self.__amount_clusters)
| annoviko/pyclustering | pyclustering/cluster/ema.py | Python | gpl-3.0 | 28,795 |
<?php
require('../load.php');
require('classes/messages.php');
require('meta.php');
require('classes/tracklist.php');
?>
<!-- HTML TEMPLATE -->
<!-- body page -->
<body>
<script type="text/javascript">
$(document).ready(function(){
// Post password protection
if($('#post_protect').checked) $('#post_protect_password').show();
else $('#post_protect_password').hide();
$('#post_protect').click(function(){
if(this.checked)
$('#post_protect_password').show();
else
$('#post_protect_password').hide();
});
// Message system
<?php $messages->ShowMsg(); ?>
// Table effects
$('.table-list tr.plrow').hover(
function(){
$(this).stop().animate({'background-color':'#4395cb',color:"#fff"},100);
$(this).find('a').stop().animate({color:"#fff"},100);
},
function(){
$(this).stop().animate({'background-color':'#fff',color:"#000"},100);
$(this).find('a').stop().animate({color:"#1e6a92"},100);
}
);
// Check all posts
$("#all-check").click(function(){
$(".post-checks").prop("checked",$("#all-check").prop("checked"));
});
});
</script>
<!-- Whole page style -->
<div id="body">
<!-- Template style -->
<div id="main">
<!-- Header style -->
<?php require('header.php'); ?>
<!-- Main whole content style (articles and sidebar) -->
<div id="wrap">
<?php require('menu.php'); ?>
<div id="center">
<!-- THE THING -->
<div id="content">
<div id="message-s"></div>
<div id="message-f"></div>
<div class="art-title">Log list (<?php echo $tracklist->pca; ?>)
<a href="options.php" class="top-btn-link">Back to options</a>
</div>
<div class="article-block">
<form action="<?php echo $constants->cwd; ?>" method="post">
<table class="table-list">
<thead>
<th><input type="checkbox" id="all-check" /></th>
<th>When</th>
<th>Who</th>
<th>What</th>
<th>Log id</th>
<th>Action</th>
<th>Actions</th>
</thead>
<tbody>
<?php while($v=$tracklist->gtl->fetch_assoc()): ?>
<tr class="plrow">
<td><input type="checkbox" class="post-checks" name="track_checks[]" value="<?php echo $v['ti']; ?>" /></td>
<td><?php echo date("d.m.Y",$v['tn'])." ".date("H:m:s",$v['tn']); ?></td>
<td><a href="<?php echo "edituser.php?u=".$v['ui']; ?>"><?php echo $v['nm']; ?></a></td>
<td><?php echo $v['th']; ?></td>
<td><?php echo $v['ti']; ?></td>
<td><?php echo $v['ac']; ?></td>
<td>
<a href="<?php echo "delete.php?d=".$v['ti']."&t=log"."&h=".$host_uri->host_uri(); ?>"><img src="img/trash.png" alt="Delete post" title="Delete post" /></a>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<select name="list_action">
<option value="0">None</option>
<option value="1">Delete</option>
</select>
<input type="submit" value="Jump on it" name="list_btn" />
</form>
<!-- Page numbering (what page you at) -->
<div id="page-numbering"><?php echo $tracklist->pagwr; ?></div>
</div>
</div>
<!-- END OF THING -->
</div>
</div>
<!-- END OF HTML TEMPLATE -->
<?php
require('footer.php');
?> | cidecode/CideCMS | panel/tracking.php | PHP | gpl-3.0 | 3,512 |
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
* Copyright (C) 1997--2008 The R Development Core Team
* Copyright (C) 2003, 2004 The R Foundation
* Copyright (C) 2010 bedatadriven
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.renjin.primitives.combine;
import org.renjin.invoke.annotations.*;
import org.renjin.repackaged.guava.base.Function;
import org.renjin.repackaged.guava.collect.Iterables;
import org.renjin.sexp.ListVector;
import org.renjin.sexp.NamedValue;
import org.renjin.sexp.Null;
import org.renjin.sexp.SEXP;
/**
* Implementation of the combine-related functions, including c(), list(), unlist(),
* cbind(), rbind(), matrix(), and aperm()
*/
public class Combine {
/**
* combines its arguments to form a vector. All arguments are coerced to a common type which is the
* type of the returned value, and all attributes except names are removed.
*/
@Generic
@Builtin
public static SEXP c(@ArgumentList ListVector arguments,
@NamedFlag("recursive") boolean recursive) {
// Iterate over all the vectors in the argument
// list to determine which vector type to use
Inspector inspector = new Inspector(recursive);
inspector.acceptAll(Iterables.transform(arguments.namedValues(), VALUE_OF));
CombinedBuilder builder = inspector.newBuilder().useNames(true);
// Allocate a new vector with all the elements
return new Combiner(recursive, builder)
.add(arguments)
.build();
}
@Generic
@Internal
public static SEXP unlist(SEXP sexp, boolean recursive, boolean useNames) {
if(!(sexp instanceof ListVector)) {
return sexp;
}
ListVector vector = (ListVector) sexp;
// Iterate over all the vectors in the argument
// list to determine which vector type to use
Inspector inspector = new Inspector(recursive);
inspector.acceptAll(vector);
if(inspector.getResult() == Null.VECTOR_TYPE) {
return Null.INSTANCE;
}
CombinedBuilder builder = inspector.newBuilder().useNames(useNames);
return new Combiner(recursive, builder)
.add(vector)
.build();
}
private static final Function<NamedValue,SEXP> VALUE_OF =
new Function<NamedValue, SEXP>() {
@Override
public SEXP apply(NamedValue input) {
return input.getValue();
}
};
}
| jukiewiczm/renjin | core/src/main/java/org/renjin/primitives/combine/Combine.java | Java | gpl-3.0 | 3,051 |
import { moduleForModel, test } from 'ember-qunit'
moduleForModel('team', {
needs: [
'model:user'
, 'model:project'
, 'model:assignment'
, 'model:attendance'
]
})
test('it exists', function(assert) {
var model = this.subject()
// var store = this.store()
assert.ok(!!model)
})
| topaxi/timed | frontend/tests/unit/models/team-test.js | JavaScript | gpl-3.0 | 299 |
package arduinoLight.framework;
/**
* Classes that need to act upon shutdown, for example to close connections or clean up resources
* should implement this interface and add themselves to the ShutdownHandler.
*/
public interface ShutdownListener
{
/**
* Gets called if the application is shutting down.
* Obviously, should not be called of the application is not shutting down.
*/
public void onShutdown();
}
| greenkeeper/ArduinoLight | ArduinoLight/src/arduinoLight/framework/ShutdownListener.java | Java | gpl-3.0 | 436 |
#! /usr/bin/php
<?php
/**
* @author Xavier Schepler
* @copyright Réseau Quetelet
*/
require_once 'inc/headers.php';
function help()
{
echo <<<HEREDOC
*********************************************
* Question data bank administration utility *
*********************************************
Allows the *listing*, the *creation*, the *update*, or the *deletion* of administration accounts.
List useradmin --list OR useradmin -l
Create useradmin --add login OR useradmin -a login
Delete useradmin --delete login OR useradmin -d login
Password useradmin --password login OR useradmin -p login
HEREDOC;
exit(0);
}
function read_line_hidden()
{
system('stty -echo');
$line = '';
while (($c = fgetc(STDIN)) != "\n")
{
$line .= $c;
}
system('stty echo');
return $line;
}
function _list()
{
$userMapper = new DB_Mapper_User;
$list = $userMapper->findAll();
if (($l = count($list)) == 0)
{
echo "No account.\n";
exit(0);
}
for ($i = 0; $i < $l; $i++)
{
echo $list[$i]['user_name'], "\n";
}
}
function add($login, $password)
{
$userMapper = new DB_Mapper_User;
$user = new DB_Model_User;
$user->set_user_name($login);
$user->set_password($password);
try
{
$id = $userMapper->save($user);
}
catch (Exception $e)
{
echo "An error occured.\n", $e;
exit(1);
}
if ( ! $id)
{
echo "An error occured.\n";
exit(1);
}
echo "Login \"$login\" with password \"$password\" successfuly created.\n";
exit(0);
}
function delete($login)
{
$userMapper = new DB_Mapper_User;
$l = $userMapper->deleteByLogin($login);
if ($l > 0)
{
echo "Account \"$login\" deleted.\n";
exit(0);
}
else
{
echo "No account was deleted.\n";
exit(1);
}
}
function update($login, $password)
{
$userMapper = new DB_Mapper_User;
$user = $userMapper->findByLogin($login);
if ( ! $user)
{
echo "No user for login \"$login\"\n";
exit(1);
}
else
{
$user->set_password($password);
try
{
$id = $userMapper->save($user);
}
catch (Exception $e)
{
echo "An error occured.\n$e\n";
exit(1);
}
if ($id)
{
echo "Password changed to \"$password\" for login \"$login\".\n";
exit(1);
}
else
{
echo "An error occured.\n";
exit(0);
}
}
}
try
{
$opts = new Zend_Console_Getopt(
array(
'help|h' => 'Show an help message and exits.',
'list|l' => 'List all registered accounts',
'add|a=s' => 'Add an account.',
'delete|d=s' => 'Delete an account.',
'password|p=s' => 'Change an account password.',
)
);
}
catch (Exception $e)
{
echo $e->getUsageMessage();
exit(1);
}
try
{
if ( ! $opts->toArray())
{
echo $opts->getUsageMessage();
exit(0);
}
}
catch (Exception $e)
{
echo $opts->getUsageMessage();
exit(1);
}
if ($opts->getOption('help'))
{
help();
}
if ($list = $opts->getOption('list'))
{
_list();
}
if ($login = $opts->getOption('add'))
{
$userMapper = new DB_Mapper_User;
if ($userMapper->loginExists($login))
{
echo "An account named \"$login\" already exists.\n";
exit(1);
}
echo "Enter password for user $login :\n";
$password = read_line_hidden();
echo "Retype password for user $login :\n";
$_password = read_line_hidden();
if ($password != $_password)
{
echo "Passwords didn\'t match\n";
exit(1);
}
add($login, $password);
}
if ($login = $opts->getOption('delete'))
{
delete($login);
}
if ($login = $opts->getOption('update'))
{
echo "Enter password for user $login :\n";
$password = read_line_hidden();
echo "Retype password for user $login :\n";
$_password = read_line_hidden();
if ($password != $_password)
{
echo "Passwords didn\'t match\n";
exit(1);
}
update($login, $password);
} | CDSP-SCPO/BasedeQuestions | php/app/scripts/useradmin.php | PHP | gpl-3.0 | 3,699 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
**constants.py**
**Platform:**
Windows, Linux, Mac Os X.
**Description:**
Defines **Foundations** package default constants through the :class:`Constants` class.
**Others:**
"""
from __future__ import unicode_literals
import os
import platform
import foundations
__author__ = "Thomas Mansencal"
__copyright__ = "Copyright (C) 2008 - 2014 - Thomas Mansencal"
__license__ = "GPL V3.0 - http://www.gnu.org/licenses/"
__maintainer__ = "Thomas Mansencal"
__email__ = "thomas.mansencal@gmail.com"
__status__ = "Production"
__all__ = ["Constants"]
class Constants():
"""
Defines **Foundations** package default constants.
"""
application_name = "Foundations"
"""
:param application_name: Package Application name.
:type application_name: unicode
"""
major_version = "2"
"""
:param major_version: Package major version.
:type major_version: unicode
"""
minor_version = "1"
"""
:param minor_version: Package minor version.
:type minor_version: unicode
"""
change_version = "0"
"""
:param change_version: Package change version.
:type change_version: unicode
"""
version = ".".join((major_version, minor_version, change_version))
"""
:param version: Package version.
:type version: unicode
"""
logger = "Foundations_Logger"
"""
:param logger: Package logger name.
:type logger: unicode
"""
verbosity_level = 3
"""
:param verbosity_level: Default logging verbosity level.
:type verbosity_level: int
"""
verbosity_labels = ("Critical", "Error", "Warning", "Info", "Debug")
"""
:param verbosity_labels: Logging verbosity labels.
:type verbosity_labels: tuple
"""
logging_default_formatter = "Default"
"""
:param logging_default_formatter: Default logging formatter name.
:type logging_default_formatter: unicode
"""
logging_separators = "*" * 96
"""
:param logging_separators: Logging separators.
:type logging_separators: unicode
"""
default_codec = "utf-8"
"""
:param default_codec: Default codec.
:type default_codec: unicode
"""
codec_error = "ignore"
"""
:param codec_error: Default codec error behavior.
:type codec_error: unicode
"""
application_directory = os.sep.join(("Foundations", ".".join((major_version, minor_version))))
"""
:param application_directory: Package Application directory.
:type application_directory: unicode
"""
if platform.system() == "Windows" or platform.system() == "Microsoft" or platform.system() == "Darwin":
provider_directory = "HDRLabs"
"""
:param provider_directory: Package provider directory.
:type provider_directory: unicode
"""
elif platform.system() == "Linux":
provider_directory = ".HDRLabs"
"""
:param provider_directory: Package provider directory.
:type provider_directory: unicode
"""
null_object = "None"
"""
:param null_object: Default null object string.
:type null_object: unicode
"""
| KelSolaar/Foundations | foundations/globals/constants.py | Python | gpl-3.0 | 3,184 |
<?php
/**
* Backend booking dialogs
* @version 1.8.7
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) { exit; }
?>
<div id='bookacti-bookings-calendar-settings-dialog' class='bookacti-backend-dialog bookacti-bookings-dialog' style='display:none;' title='<?php esc_html_e( 'Bookings page calendar settings', 'booking-activities' ); ?>'>
<form id='bookacti-bookings-calendar-settings-form'>
<input type='hidden' name='action' value='bookactiUpdateBookingsCalendarSettings'/>
<?php
wp_nonce_field( 'bookacti_update_bookings_calendar_settings', 'nonce_update_bookings_calendar_settings', false );
?>
<div class='bookacti-backend-settings-only-notice bookacti-warning'>
<span class='dashicons dashicons-warning'></span>
<span>
<?php
/* translators: %s is a link to the "booking form editor". */
echo sprintf( esc_html__( 'These settings are used for the bookings page calendar only.', 'booking-activities' ) . ' ' . esc_html__( 'For your frontend calendars, use the "Calendar" field settings in the desired %s.', 'booking-activities' ), '<a href="' . admin_url( 'admin.php?page=bookacti_forms' ) . '">' . esc_html__( 'booking form editor', 'booking-activities' ) . '</a>' );
?>
</span>
</div>
<?php
$user_calendar_settings = bookacti_format_bookings_calendar_settings( get_user_meta( get_current_user_id(), 'bookacti_bookings_calendar_settings', true ) );
// Fill the array of tabs with their label, callback for content and display order
$calendar_tabs = apply_filters( 'bookacti_bookings_calendar_dialog_tabs', array (
array( 'label' => esc_html__( 'Display', 'booking-activities' ),
'id' => 'display',
'callback' => 'bookacti_fill_bookings_calendar_dialog_display_tab',
'parameters' => array( 'calendar_data' => $user_calendar_settings ),
'order' => 10 ),
array( 'label' => esc_html__( 'Calendar', 'booking-activities' ),
'id' => 'calendar',
'callback' => 'bookacti_fill_bookings_calendar_dialog_calendar_tab',
'parameters' => array( 'calendar_data' => $user_calendar_settings ),
'order' => 20 )
) );
// Display tabs
bookacti_display_tabs( $calendar_tabs, 'calendar' );
/**
* Display the content of the "Display" tab of the "Bookings Calendar" dialog
* @since 1.8.0
* @param array $params
*/
function bookacti_fill_bookings_calendar_dialog_display_tab( $params ) {
do_action( 'bookacti_bookings_calendar_dialog_display_tab_before', $params );
?>
<fieldset>
<legend><?php esc_html_e( 'Display', 'booking-activities' ); ?></legend>
<?php
$display_fields = apply_filters( 'bookacti_bookings_calendar_display_fields', array(
'show' => array(
'name' => 'show',
'type' => 'checkbox',
'title' => esc_html__( 'Display the calendar by default', 'booking-activities' ),
'value' => $params[ 'calendar_data' ][ 'show' ],
'tip' => esc_html__( 'Display the calendar by default on the bookings page.', 'booking-activities' )
),
'ajax' => array(
'name' => 'ajax',
'type' => 'checkbox',
'title' => esc_html__( 'AJAX filtering', 'booking-activities' ),
'value' => $params[ 'calendar_data' ][ 'ajax' ],
'tip' => esc_html__( 'Automatically filter the booking list when you change a filter or select an event.', 'booking-activities' )
),
), $params[ 'calendar_data' ] );
bookacti_display_fields( $display_fields );
?>
</fieldset>
<fieldset>
<legend><?php esc_html_e( 'Tooltip', 'booking-activities' ); ?></legend>
<?php
$undesired_columns = array( 'events', 'event_id', 'event_title', 'start_date', 'end_date', 'actions' );
$event_booking_list_columns = array_diff_key( bookacti_get_user_booking_list_columns_labels(), array_flip( $undesired_columns ) );
$tooltip_fields = apply_filters( 'bookacti_bookings_calendar_tooltip_fields', array(
'tooltip_booking_list' => array(
'name' => 'tooltip_booking_list',
'type' => 'checkbox',
'title' => esc_html__( 'Preview booking list', 'booking-activities' ),
'value' => $params[ 'calendar_data' ][ 'tooltip_booking_list' ],
'tip' => esc_html__( 'Display the event booking list when you mouse over an event.', 'booking-activities' )
),
'tooltip_booking_list_columns' => array(
'name' => 'tooltip_booking_list_columns',
'type' => 'select_items',
'title' => esc_html__( 'Preview booking list columns', 'booking-activities' ),
'id' => 'bookacti-event-booking-list-columns',
'options' => $event_booking_list_columns,
'value' => $params[ 'calendar_data' ][ 'tooltip_booking_list_columns' ],
'tip' => esc_html__( 'Add the columns in the order they will be displayed.', 'booking-activities' )
)
), $params[ 'calendar_data' ] );
bookacti_display_fields( $tooltip_fields );
?>
</fieldset>
<?php
do_action( 'bookacti_bookings_calendar_dialog_display_tab_after', $params );
}
/**
* Display the content of the "Calendar" tab of the "Bookings Calendar" dialog
* @since 1.8.0
* @version 1.13.0
* @param array $params
*/
function bookacti_fill_bookings_calendar_dialog_calendar_tab( $params ) {
do_action( 'bookacti_bookings_calendar_dialog_calendar_tab_before', $params );
?>
<fieldset>
<legend><?php esc_html_e( 'Working time', 'booking-activities' ); ?></legend>
<?php
$agenda_fields = bookacti_get_fullcalendar_fields_default_data( array( 'minTime', 'maxTime' ) );
$agenda_fields[ 'minTime' ][ 'value' ] = $params[ 'calendar_data' ][ 'minTime' ];
$agenda_fields[ 'maxTime' ][ 'value' ] = $params[ 'calendar_data' ][ 'maxTime' ];
bookacti_display_fields( $agenda_fields );
?>
</fieldset>
<?php
do_action( 'bookacti_bookings_calendar_dialog_calendar_tab_after', $params );
}
?>
<div class='bookacti-hidden-field'>
<?php bookacti_display_badp_promo(); ?>
</div>
<div class='bookacti-show-hide-advanced-options bookacti-show-advanced-options'
data-show-title='<?php esc_html_e( 'Show advanced options', 'booking-activities' ); ?>'
data-hide-title='<?php esc_html_e( 'Hide advanced options', 'booking-activities' ); ?>'>
<?php esc_html_e( 'Show advanced options', 'booking-activities' ); ?>
</div>
</form>
</div>
<div id='bookacti-change-booking-state-dialog' class='bookacti-backend-dialog bookacti-bookings-dialog' style='display:none;' title='<?php esc_html_e( 'Change booking state', 'booking-activities' ); ?>'>
<form id='bookacti-change-booking-state-form'>
<?php
wp_nonce_field( 'bookacti_change_booking_state', 'nonce_change_booking_state', false );
?>
<fieldset>
<legend><?php esc_html_e( 'Booking state', 'booking-activities' ); ?></legend>
<div>
<label for='bookacti-select-booking-state' ><?php esc_html_e( 'Booking state', 'booking-activities' ); ?></label>
<select name='select-booking-state' id='bookacti-select-booking-state' >
<?php
$booking_state_labels = bookacti_get_booking_state_labels();
$allowed_booking_states = apply_filters( 'bookacti_booking_states_you_can_manually_change', array( 'delivered', 'booked', 'pending', 'cancelled', 'refund_requested', 'refunded' ) );
foreach( $allowed_booking_states as $state_key ) {
$state_label = ! empty( $booking_state_labels[ $state_key ][ 'label' ] ) ? $booking_state_labels[ $state_key ][ 'label' ] : $state_key;
echo '<option value="' . esc_attr( $state_key ) . '" >' . $state_label . '</option>';
}
?>
</select>
</div>
<div>
<label for='bookacti-send-notifications-on-state-change' ><?php esc_html_e( 'Send notifications', 'booking-activities' ); ?></label>
<?php
$args = array(
'type' => 'checkbox',
'name' => 'send-notifications-on-state-change',
'id' => 'bookacti-send-notifications-on-state-change',
'value' => 0,
/* Translators: %s is a link to the "Notifications settings" */
'tip' => sprintf( esc_html__( 'Send the booking status change notifications configured in %s.', 'booking-activities' ), '<a href="' . admin_url( 'admin.php?page=bookacti_settings&tab=notifications' ) . '">' . esc_html__( 'Notifications settings', 'booking-activities' ) . '</a>' )
);
bookacti_display_field( $args );
?>
</div>
</fieldset>
<fieldset>
<legend><?php esc_html_e( 'Payment status', 'booking-activities' ); ?></legend>
<div>
<label for='bookacti-select-payment-status' ><?php esc_html_e( 'Payment status', 'booking-activities' ); ?></label>
<select name='select-payment-status' id='bookacti-select-payment-status' >
<?php
$payment_status = bookacti_get_payment_status_labels();
foreach( $payment_status as $payment_status_id => $payment_status_data ) {
echo '<option value="' . esc_attr( $payment_status_id ) . '" >' . esc_html( $payment_status_data[ 'label' ] ) . '</option>';
}
?>
</select>
</div>
</fieldset>
</form>
</div>
<div id='bookacti-change-booking-quantity-dialog' class='bookacti-backend-dialog bookacti-bookings-dialog' style='display:none;' title='<?php esc_html_e( 'Change booking quantity', 'booking-activities' ); ?>'>
<form id='bookacti-change-booking-quantity-form'>
<?php
wp_nonce_field( 'bookacti_change_booking_quantity', 'nonce_change_booking_quantity', false );
?>
<p class='bookacti-dialog-intro' ><?php esc_html_e( 'Input the desired booking quantity:', 'booking-activities' ); ?></p>
<?php
$booking_qty_fields = apply_filters( 'bookacti_change_booking_quantity_dialog_fields', array(
'quantity' => array(
'type' => 'number',
'name' => 'new_quantity',
'title' => esc_html__( 'Quantity', 'booking-activities' ),
'id' => 'bookacti-new-quantity',
'value' => 1,
'tip' => esc_html__( 'New total quantity. In case of booking groups, the quantity of all the bookings of the group will be updated.', 'booking-activities' )
)
));
bookacti_display_fields( $booking_qty_fields );
?>
<p class='bookacti-error'>
<span class='dashicons dashicons-warning'></span>
<span><?php esc_html_e( 'The new quantity will be enforced. No checks and no further actions will be performed.', 'booking-activities' ); ?></span>
</p>
</form>
</div>
<div id='bookacti-delete-booking-dialog' class='bookacti-backend-dialog bookacti-bookings-dialog' style='display:none;' title='<?php esc_html_e( 'Delete a booking', 'booking-activities' ); ?>'>
<form id='bookacti-delete-booking-dialog-content'>
<input type='hidden' name='action' value='bookactiDeleteBooking'/>
<input type='hidden' name='booking_id' value='0'/>
<input type='hidden' name='booking_type' value=''/>
<?php wp_nonce_field( 'bookacti_delete_booking', 'nonce_delete_booking' ); ?>
<p class='bookacti-dialog-intro bookacti-delete-single-booking-description' >
<?php esc_html_e( 'Are you sure to delete this booking permanently?', 'booking-activities' ); ?>
</p>
<p class='bookacti-error'>
<span class='dashicons dashicons-warning'></span>
<span><?php esc_html_e( 'This action cannot be undone.', 'booking-activities' ); ?></span>
</p>
<p class='bookacti-dialog-intro bookacti-delete-booking-group-description' style='display:none;'>
<?php esc_html_e( 'All the bookings included in this booking group will also be delete.', 'booking-activities' ); ?>
</p>
<?php do_action( 'bookacti_delete_booking_form_after' ); ?>
</form>
</div>
<div id='bookacti-export-bookings-dialog' class='bookacti-backend-dialog bookacti-bookings-dialog' style='display:none;' title='<?php esc_html_e( 'Export bookings', 'booking-activities' ); ?>'>
<form id='bookacti-export-bookings-form'>
<?php wp_nonce_field( 'bookacti_export_bookings_url', 'nonce_export_bookings_url', false ); ?>
<input type='hidden' name='export_type' value='csv' id='bookacti-export-type-field'/>
<div class='bookacti-info'>
<span class='dashicons dashicons-info'></span>
<span><?php esc_html_e( 'This will export all the bookings of the current list (filters applied).', 'booking-activities' ); ?></span>
</div>
<?php
// Display tabs
$user_settings = bookacti_get_bookings_export_settings();
$export_columns_raw = bookacti_get_bookings_export_columns();
$export_columns = array_combine( array_keys( $export_columns_raw ), array_map( 'bookacti_translate_text', $export_columns_raw ) );
$export_tabs = apply_filters( 'bookacti_export_bookings_dialog_tabs', array(
array(
'label' => esc_html__( 'CSV', 'booking-activities' ),
'id' => 'csv',
'callback' => 'bookacti_fill_export_bookings_csv_tab',
'parameters'=> array( 'user_settings' => $user_settings, 'export_columns' => $export_columns ),
'order' => 10
),
array(
'label' => esc_html__( 'iCal', 'booking-activities' ),
'id' => 'ical',
'callback' => 'bookacti_fill_export_bookings_ical_tab',
'parameters'=> array( 'user_settings' => $user_settings, 'export_columns' => $export_columns ),
'order' => 20
)
), $user_settings );
bookacti_display_tabs( $export_tabs, 'export_bookings' );
/**
* Display the content of the "csv" tab of the "Export bookings" dialog
* @param array $args
* @since 1.8.0
* @version 1.8.9
*/
function bookacti_fill_export_bookings_csv_tab( $args ) {
do_action( 'bookacti_fill_export_bookings_csv_tab_before', $args );
$excel_import_csv = '<a href="https://support.office.com/en-us/article/import-or-export-text-txt-or-csv-files-5250ac4c-663c-47ce-937b-339e391393ba#ID0EAAFAAA" target="_blank">' . esc_html_x( 'import', 'verb', 'booking-activities' ) . '</a>';
$excel_sync_csv = '<a href="https://support.office.com/en-us/article/import-data-from-external-data-sources-power-query-be4330b3-5356-486c-a168-b68e9e616f5a#ID0EAAHAAA" target="_blank">' . esc_html_x( 'sync', 'verb', 'booking-activities' ) . '</a>';
$gsheets_import_csv = '<a href="https://support.google.com/docs/answer/40608" target="_blank">' . esc_html_x( 'import', 'verb', 'booking-activities' ) . '</a>';
$gsheets_sync_csv = '<a href="https://support.google.com/docs/answer/3093335" target="_blank">' . esc_html_x( 'sync', 'verb', 'booking-activities' ) . '</a>';
?>
<div class='bookacti-info'>
<span class='dashicons dashicons-info'></span>
<span><?php echo '<strong>' . esc_html__( 'Types of use:', 'booking-activities' ) . '</strong> MS Excel (' . implode( ', ', array( $excel_import_csv, $excel_sync_csv ) ) . '), Google Sheets (' . implode( ', ', array( $gsheets_import_csv, $gsheets_sync_csv ) ) . ')...'; ?></span>
</div>
<?php
$csv_fields = apply_filters( 'bookacti_export_bookings_csv_fields', array(
'csv_columns' => array(
'type' => 'select_items',
'name' => 'csv_columns',
'title' => esc_html__( 'Columns to export (ordered)', 'booking-activities' ),
'id' => 'bookacti-csv-columns-to-export',
'options' => $args[ 'export_columns' ],
'value' => $args[ 'user_settings' ][ 'csv_columns' ],
'tip' => esc_html__( 'Add the columns you want to export in the order they will be displayed.', 'booking-activities' )
),
'csv_raw' => array(
'type' => 'checkbox',
'name' => 'csv_raw',
'title' => esc_html__( 'Raw data', 'booking-activities' ),
'id' => 'bookacti-csv-raw',
'value' => $args[ 'user_settings' ][ 'csv_raw' ],
'tip' => esc_html__( 'Display raw data (easy to manipulate), as opposed to formatted data (user-friendly). E.g.: A date will be displayed "1992-12-26 02:00:00" instead of "December 26th, 2020 2:00 AM".', 'booking-activities' )
),
'csv_export_groups' => array(
'type' => 'select',
'name' => 'csv_export_groups',
'title' => esc_html__( 'How to display the groups?', 'booking-activities' ),
'id' => 'bookacti-select-export-groups',
'options' => array(
'groups' => esc_html__( 'One single row per group', 'booking-activities' ),
'bookings' => esc_html__( 'One row for each booking of the group', 'booking-activities' )
),
'value' => $args[ 'user_settings' ][ 'csv_export_groups' ],
'tip' => esc_html__( 'Choose how to display the grouped bookings. Do you want to display all the bookings of the group, or only the group as a single row?', 'booking-activities' )
)
), $args );
bookacti_display_fields( $csv_fields );
do_action( 'bookacti_fill_export_bookings_csv_tab_after', $args );
}
/**
* Display the content of the "iCal" tab of the "Export bookings" dialog
* @since 1.8.0
* @version 1.8.9
* @param array $args
*/
function bookacti_fill_export_bookings_ical_tab( $args ) {
do_action( 'bookacti_fill_export_bookings_ical_tab_before', $args );
$gcal_import_ical = '<a href="https://support.google.com/calendar/answer/37118" target="_blank">' . esc_html_x( 'import', 'verb', 'booking-activities' ) . '</a>';
$gcal_sync_ical = '<a href="https://support.google.com/calendar/answer/37100" target="_blank">' . esc_html_x( 'sync', 'verb', 'booking-activities' ) . '</a>';
$outlook_com_ical = '<a href="https://support.office.com/en-us/article/import-or-subscribe-to-a-calendar-in-outlook-com-cff1429c-5af6-41ec-a5b4-74f2c278e98c" target="_blank">' . esc_html_x( 'import', 'verb', 'booking-activities' ) . ' / ' . esc_html_x( 'sync', 'verb', 'booking-activities' ) . '</a>';
$outlook_ms_ical = '<a href="https://support.office.com/en-us/article/video-import-calendars-8e8364e1-400e-4c0f-a573-fe76b5a2d379" target="_blank">' . esc_html_x( 'import', 'verb', 'booking-activities' ) . ' / ' . esc_html_x( 'sync', 'verb', 'booking-activities' ) . '</a>';
?>
<div class='bookacti-info'>
<span class='dashicons dashicons-info'></span>
<span><?php echo '<strong>' . esc_html__( 'Types of use:', 'booking-activities' ) . '</strong> Google Calendar (' . implode( ', ', array( $gcal_import_ical, $gcal_sync_ical ) ) . '), Outlook.com (' . $outlook_com_ical . '), MS Outlook (' . $outlook_ms_ical . ')...'; ?></span>
</div>
<?php
$ical_fields = apply_filters( 'bookacti_export_bookings_ical_fields', array(
'vevent_summary' => array(
'type' => 'text',
'name' => 'vevent_summary',
'title' => esc_html__( 'Event title', 'booking-activities' ),
'fullwidth' => 1,
'id' => 'bookacti-vevent-title',
'value' => $args[ 'user_settings' ][ 'vevent_summary' ],
'tip' => esc_html__( 'The title of the exported events, use the tags to display event data.', 'booking-activities' )
),
'vevent_description' => array(
'type' => 'editor',
'name' => 'vevent_description',
'title' => esc_html__( 'Event description', 'booking-activities' ),
'fullwidth' => 1,
'id' => 'bookacti-vevent-description',
'value' => $args[ 'user_settings' ][ 'vevent_description' ],
'tip' => esc_html__( 'The description of the exported events, use the tags to display event data.', 'booking-activities' )
)
), $args );
bookacti_display_fields( $ical_fields );
?>
<div class='bookacti-warning'>
<span class='dashicons dashicons-warning'></span>
<span><?php esc_html_e( 'HTML may not be supported by your calendar app.', 'booking-activities' ); ?></span>
</div>
<?php
$tags_args = array(
'title' => esc_html__( 'Available tags', 'booking-activities' ),
'tip' => esc_html__( 'Use these tags in the event title and description to display event specific data.', 'booking-activities' ),
'tags' => bookacti_get_bookings_export_event_tags(),
'id' => 'bookacti-tags-ical-bookings-export'
);
bookacti_display_tags_fieldset( $tags_args );
?>
<fieldset id='booakcti-ical-booking-list-fields-container' class='bookacti-fieldset-no-css'>
<legend class='bookacti-fullwidth-label'>
<?php
esc_html_e( 'Booking list tags settings', 'booking-activities' );
bookacti_help_tip( esc_html__( 'Configure the booking list displayed on the exported events.', 'booking-activities' ) );
?>
<span class='bookacti-show-hide-advanced-options bookacti-show-advanced-options' for='booakcti-ical-booking-list-fields' data-show-title='<?php esc_html_e( 'show', 'booking-activities' ); ?>' data-hide-title='<?php esc_html_e( 'hide', 'booking-activities' ); ?>'><?php esc_html_e( 'show', 'booking-activities' ); ?></span>
</legend>
<div id='booakcti-ical-booking-list-fields' class='bookacti-fieldset-toggled' style='display:none;'>
<div class='bookacti-info' style='margin-bottom:10px;'>
<span class='dashicons dashicons-info'></span>
<span><?php esc_html_e( 'These settings are used for the {booking_list} and {booking_list_raw} tags only.', 'booking-activities' ); ?></span>
</div>
<?php
$ical_booking_list_fields = apply_filters( 'bookacti_export_bookings_ical_booking_list_fields', array(
'ical_columns' => array(
'type' => 'select_items',
'name' => 'ical_columns',
'title' => esc_html__( 'Columns (ordered)', 'booking-activities' ),
'id' => 'bookacti-ical-booking-list-columns',
'options' => $args[ 'export_columns' ],
'value' => $args[ 'user_settings' ][ 'ical_columns' ],
'tip' => esc_html__( 'Add the columns in the order you want them to appear when using the {booking_list} or {booking_list_raw} tags.', 'booking-activities' )
),
'ical_raw' => array(
'type' => 'checkbox',
'name' => 'ical_raw',
'title' => esc_html__( 'Raw data', 'booking-activities' ),
'id' => 'bookacti-ical-raw',
'value' => $args[ 'user_settings' ][ 'ical_raw' ],
'tip' => esc_html__( 'Display raw data (easy to manipulate), as opposed to formatted data (user-friendly). E.g.: A date will be displayed "1992-12-26 02:00:00" instead of "December 26th, 2020 2:00 AM".', 'booking-activities' )
),
'ical_booking_list_header' => array(
'type' => 'checkbox',
'name' => 'ical_booking_list_header',
'title' => esc_html__( 'Show columns\' title', 'booking-activities' ),
'id' => 'bookacti-ical-booking-list-header',
'value' => $args[ 'user_settings' ][ 'ical_booking_list_header' ],
'tip' => esc_html__( 'Display the columns\' title in the first row of the booking list.', 'booking-activities' )
)
), $args );
bookacti_display_fields( $ical_booking_list_fields );
?>
</div>
</fieldset>
<?php
do_action( 'bookacti_fill_export_bookings_ical_tab_after', $args );
}
// Display global export fields
$export_fields = apply_filters( 'bookacti_export_bookings_dialog_fields', array(
'per_page' => array(
'type' => 'number',
'name' => 'per_page',
'title' => esc_html__( 'Limit', 'booking-activities' ),
'id' => 'bookacti-select-export-limit',
'value' => $user_settings[ 'per_page' ],
'tip' => esc_html__( 'Maximum number of bookings to export. You may need to increase your PHP max execution time if this number is too high.', 'booking-activities' )
)
), $user_settings );
bookacti_display_fields( $export_fields );
?>
<div id='bookacti-export-bookings-url-container' style='display:none;'>
<p><strong><?php esc_html_e( 'Secret address', 'booking-activities' ); ?></strong></p>
<div class='bookacti_export_url'>
<div class='bookacti_export_url_field'><input type='text' id='bookacti_export_bookings_url_secret' value='' readonly onfocus='this.select();'/></div>
<div class='bookacti_export_button'><input type='button' value='<?php echo esc_html_x( 'Export', 'action', 'booking-activities' ); ?>' class='button button-primary button-large'/></div>
</div>
<p>
<small><?php esc_html_e( 'Visit this address to get a file export of your bookings (according to filters and settings above), or use it as a dynamic URL feed to synchronize with other apps.', 'booking-activities' ); ?></small>
</p>
<p class='bookacti-warning'>
<span class='dashicons dashicons-warning'></span>
<span><small>
<?php esc_html_e( 'This link provides real-time data. However, some apps may synchronize only every 24h, or more.', 'booking-activities' ); ?>
<strong> <?php esc_html_e( 'That\'s why your changes won\'t be applied in real time on your synched apps.', 'booking-activities' ); ?></strong>
</small></span>
</p>
<p class='bookacti-warning'>
<span class='dashicons dashicons-warning'></span>
<span><small>
<?php echo esc_html__( 'Only share this address with those you trust to see all your bookings details.', 'booking-activities' ) . ' '
. esc_html__( 'You can reset your secret key with the "Reset" button below. This will nullify the previously generated export links.', 'booking-activities' ); ?>
</small></span>
</p>
</div>
<?php do_action( 'bookacti_export_bookings_after', $user_settings ); ?>
</form>
</div>
<?php
do_action( 'bookacti_backend_bookings_dialogs' ); | bookingactivities/booking-activities | view/view-backend-bookings-dialogs.php | PHP | gpl-3.0 | 25,141 |
package com.kingothepig.tutorialmod.creativetab;
import com.kingothepig.tutorialmod.init.ModItems;
import com.kingothepig.tutorialmod.reference.Reference;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class CreativeTabMod {
public static final CreativeTabs MOD_TAB = new CreativeTabs(Reference.MOD_ID.toLowerCase()){
@Override
public Item getTabIconItem(){
return ModItems.mapleLeaf;
}
};
}
| KingOThePig/TutorialMod | src/main/java/com/kingothepig/tutorialmod/creativetab/CreativeTabMod.java | Java | gpl-3.0 | 477 |
MODX Evolution 1.0.5 = dace793f0e7de11aadc0ecf54e834d93
| gohdan/DFC | known_files/hashes/assets/plugins/tinymce/jscripts/tiny_mce/themes/advanced/langs/bg.js | JavaScript | gpl-3.0 | 56 |
/***
* * WHAT
* * FILE
* * $Source: /home/vdmtools/cvsroot/toolbox/code/qtgui/optionsF.cc,v $
* * VERSION
* * $Revision: 1.29 $
* * DATE
* * $Date: 2006/02/07 01:52:03 $
* * AUTHOR
* * $Author: vdmtools $
* * COPYRIGHT
* * (C) Kyushu University
***/
#include "optionsF.h"
#include "mainF.h"
#include "interface2TB.h"
#include "interfacesF.h"
#include "qtport.h"
#if QT_VERSION < 0x040000
#include <qfile.h>
#endif // QT_VERSION < 0x040000
/*
* Constructs a optionsW which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*
* The dialog will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal dialog.
*/
optionsW::optionsW( QWidget* parent, const char* name, bool modal, WFlags fl )
#if QT_VERSION >= 0x040000
: QDialog( parent, fl )
#else
: QDialog( parent, name, modal, fl )
#endif // QT_VERSION >= 0x040000
{
this->mainw = (mainW*)parent;
this->setWindowName( (name == NULL) ? "optionsW" : name );
#if QT_VERSION >= 0x040000
this->setModal(modal);
this->setWindowTitle( tr( "Project Options" ) );
#else
if ( !name ) {
this->setName( "optionsW" );
}
this->setCaption( tr( "Project Options" ) );
#endif // QT_VERSION >= 0x040000
this->setSizeGripEnabled( true );
QVBoxLayout* layout = this->createVBoxLayout( this );
layout->setMargin( 11 );
layout->addWidget( this->createTabPart( this ) );
layout->addLayout( this->createButtonPart( this ) );
#ifdef VICE
#ifdef _MSC_VER
this->resize( this->sizeHint().width() + 40, this->sizeHint().height());
#else
this->resize( this->sizeHint() );
#endif // _MSC_VER
#else
this->resize( this->sizeHint() );
#endif // VICE
this->setOptions();
}
QWidget* optionsW::createTabPart( QWidget* parent )
{
#if QT_VERSION >= 0x040000
QTabWidget* tabWidget = new QTabWidget( this );
tabWidget->setTabPosition( QTabWidget::North );
#else
QTabWidget* tabWidget = new QTabWidget( this );
tabWidget->setTabPosition( QTabWidget::Top );
#endif // QT_VERSION >= 0x040000
tabWidget->setTabShape( QTabWidget::Rounded );
#if QT_VERSION >= 0x040000
tabWidget->addTab( this->createInterpreterTab( tabWidget ), tr( "Interpreter" ) );
#else
tabWidget->insertTab( this->createInterpreterTab( tabWidget ), tr( "Interpreter" ) );
#endif // QT_VERSION >= 0x040000
#ifdef VDMPP
#ifdef VICE
#if QT_VERSION >= 0x040000
tabWidget->addTab( this->createVICETab( tabWidget ), tr( "VICE" ) );
#else
tabWidget->insertTab( this->createVICETab( tabWidget ), tr( "VICE" ) );
#endif // QT_VERSION >= 0x040000
#endif // VICE
#endif // VDMPP
#if QT_VERSION >= 0x040000
tabWidget->addTab( this->createTypeCheckerTab( tabWidget ), tr( "Type checker" ) );
tabWidget->addTab( this->createPrettyPrinterTab( tabWidget ), tr( "Pretty printer" ) );
tabWidget->addTab( this->createCppCodeGeneratorTab( tabWidget ), tr( "C++ code generator" ) );
#ifdef VDMPP
tabWidget->addTab( this->createJavaCodeGeneratorTab( tabWidget ), tr( "Java code generator" ) );
tabWidget->addTab( this->createJ2VTab( tabWidget ), tr( "Java to VDM++" ) );
#endif // VDMPP
#else
tabWidget->insertTab( this->createTypeCheckerTab( tabWidget ), tr( "Type checker" ) );
tabWidget->insertTab( this->createPrettyPrinterTab( tabWidget ), tr( "Pretty printer" ) );
tabWidget->insertTab( this->createCppCodeGeneratorTab( tabWidget ), tr( "C++ code generator" ) );
#ifdef VDMPP
tabWidget->insertTab( this->createJavaCodeGeneratorTab( tabWidget ), tr( "Java code generator" ) );
tabWidget->insertTab( this->createJ2VTab( tabWidget ), tr( "Java to VDM++" ) );
#endif // VDMPP
#endif // QT_VERSION >= 0x040000
this->maintab = tabWidget;
return tabWidget;
}
QSpacerItem * optionsW::createSpacer()
{
return new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
}
QFrame * optionsW::createFrame( QWidget* parent )
{
QFrame* frame = new QFrame( parent );
frame->setFrameShape( QFrame::StyledPanel );
frame->setFrameShadow( QFrame::Raised );
return frame;
}
QGroupBox * optionsW::createVGroupBox( QWidget* parent )
{
#if QT_VERSION >= 0x040000
QGroupBox* gbox = new QGroupBox( parent );
QVBoxLayout* layout = this->createVBoxLayout( NULL );
gbox->setLayout(layout);
#else
QGroupBox* gbox = new QGroupBox( parent );
gbox->setOrientation( Qt::Vertical );
QLayout* layout = gbox->layout();
layout->setSpacing(6);
layout->setMargin(11);
#endif // QT_VERSION >= 0x040000
return gbox;
}
QVBoxLayout* optionsW::createVBoxLayout( QWidget* parent )
{
QVBoxLayout* layout = new QVBoxLayout( parent );
layout->setSpacing( 6 );
layout->setAlignment( Qt::AlignTop );
return layout;
}
QHBoxLayout* optionsW::createHBoxLayout( QWidget* parent )
{
QHBoxLayout* layout = new QHBoxLayout( parent );
layout->setSpacing( 6 );
return layout;
}
QVBoxLayout* optionsW::createVBoxFrameLayout( QFrame* frame )
{
QVBoxLayout* layout = this->createVBoxLayout( frame );
#if QT_VERSION >= 0x040000
#else
layout->setMargin( 6 );
#endif // QT_VERSION >= 0x040000
layout->setAlignment( Qt::AlignTop );
return layout;
}
QSpinBox* optionsW::createSpinBox( QWidget* parent, int min, int max, int value )
{
QSpinBox * sbox = new QSpinBox( parent );
#if QT_VERSION >= 0x040000
sbox->setMaximum( max );
sbox->setMinimum( min );
#else
sbox->setMaxValue( max );
sbox->setMinValue( min );
#endif // QT_VERSION >= 0x040000
sbox->setValue( value );
return sbox;
}
QComboBox* optionsW::createComboBox( QWidget* parent )
{
QComboBox * cbox = new QComboBox( parent );
#if QT_VERSION >= 0x040000
cbox->setMaxVisibleItems( 5 );
#else
cbox->setSizeLimit( 5 );
#endif // QT_VERSION >= 0x040000
// cbox->setMaxCount( 5 );
cbox->setAutoCompletion( true );
cbox->setDuplicatesEnabled( false );
return cbox;
}
QWidget* optionsW::createInterpreterTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createInterpreterFrame( tab ) );
return tab;
}
QWidget* optionsW::createInterpreterFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
QHBoxLayout* hlayout = this->createHBoxLayout( NULL );
hlayout->addItem( this->createInterpreterLayout1( frame ) );
hlayout->addItem( this->createInterpreterLayout2( frame ) );
layout->addItem(hlayout);
layout->addItem(this->createExpressionLayout( frame ));
return frame;
}
QLayout* optionsW::createInterpreterLayout1( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
layout->addWidget( this->createRuntimeCheckingGroupBox( parent ));
this->ip_ppValues = new QCheckBox( parent );
this->ip_ppValues->setText( mainW::mf(tr( "Pretty printing of &values" )) );
layout->addWidget( this->ip_ppValues );
this->ip_exception = new QCheckBox( parent );
this->ip_exception->setText( mainW::mf(tr( "Catch RunTime Error as &exception" )) );
layout->addWidget( this->ip_exception );
this->ip_oldreverse = new QCheckBox( parent );
this->ip_oldreverse->setText( mainW::mf( tr( "Old reverse in Sequence Loop Stmt" )) );
layout->addWidget( this->ip_oldreverse );
#ifdef VDMPP
layout->addItem( this->createSpacer() );
#endif //VDMPP
QObject::connect( this->ip_dynInvCheck, SIGNAL(clicked()), this, SLOT(invClicked()));
return layout;
}
QWidget* optionsW::createRuntimeCheckingGroupBox( QWidget * parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Runtime checking") );
QLayout* layout = gbox->layout();
this->ip_dynTypeCheck = new QCheckBox( parent );
this->ip_dynTypeCheck->setText( mainW::mf(tr( "&Dynamic type check" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_dynTypeCheck );
#else
layout->add( this->ip_dynTypeCheck );
#endif // QT_VERSION >= 0x040000
this->ip_dynInvCheck = new QCheckBox( parent );
this->ip_dynInvCheck->setText( mainW::mf(tr( "Dynamic checks of &invariants" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_dynInvCheck );
#else
layout->add( this->ip_dynInvCheck );
#endif // QT_VERSION >= 0x040000
this->ip_preCheck = new QCheckBox( parent );
this->ip_preCheck->setText( mainW::mf(tr( "Check of &pre-conditions" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_preCheck );
#else
layout->add( this->ip_preCheck );
#endif // QT_VERSION >= 0x040000
this->ip_postCheck = new QCheckBox( parent );
this->ip_postCheck->setText( mainW::mf(tr( "Check of p&ost-conditions" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_postCheck );
#else
layout->add( this->ip_postCheck );
#endif // QT_VERSION >= 0x040000
this->ip_measureCheck = new QCheckBox( parent );
this->ip_measureCheck->setText( mainW::mf(tr( "Check of &measures" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_measureCheck );
#else
layout->add( this->ip_measureCheck );
#endif // QT_VERSION >= 0x040000
return gbox;
}
QLayout* optionsW::createInterpreterLayout2( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
layout->addWidget( this->createRandomGeneratorGroupBox(parent) );
#ifdef VDMPP
layout->addWidget( this->createMultiThreadGroupBox( parent ) );
#endif // VDMPP
#ifdef VDMSL
layout->addItem( this->createSpacer() );
#endif // VDMSL
return layout;
}
QLayout* optionsW::createExpressionLayout( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
QHBoxLayout* hlayout = new QHBoxLayout();
QLabel* label = new QLabel( parent );
label->setText( tr( "Expression: " ) );
hlayout->addWidget( label );
QLineEdit * edit = new QLineEdit( parent );
hlayout->addWidget( edit );
this->ip_expression = edit;
layout->addItem(hlayout);
return layout;
}
QWidget* optionsW::createRandomGeneratorGroupBox( QWidget * parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Nondeterministic") );
QLayout* layout = gbox->layout();
layout->addItem( this->createRandomGeneratorSeedLayout( gbox ) );
layout->addItem( this->createRandomGeneratorMessageLayout( gbox ) );
return gbox;
}
QLayout* optionsW::createRandomGeneratorSeedLayout( QWidget * parent )
{
QHBoxLayout* layout = new QHBoxLayout();
QLabel* label = new QLabel( parent );
label->setText( tr( "Initialize random generator with:" ) );
layout->addWidget( label );
QSpinBox * sbox = this->createSpinBox( parent, -1, 999999, -1 );
layout->addWidget( sbox );
this->ip_rndGen = sbox;
return layout;
}
QLayout* optionsW::createRandomGeneratorMessageLayout( QWidget * parent )
{
QHBoxLayout* layout = new QHBoxLayout();
layout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Minimum) );
QLabel* label = new QLabel( parent );
label->setText( tr( "(-1 non random)" ) );
layout->addWidget( label );
return layout;
}
#ifdef VDMPP
QWidget* optionsW::createMultiThreadGroupBox( QWidget * parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Multi Thread") );
QLayout* layout = gbox->layout();
ip_prioritySchd = new QCheckBox( gbox );
ip_prioritySchd->setText( mainW::mf(tr( "Enable priority-based &scheduling" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( ip_prioritySchd );
#else
layout->add( ip_prioritySchd );
#endif // QT_VERSION >= 0x040000
layout->addItem( this->createPrimarySchdAlgorithmLayout( gbox ) );
layout->addItem( this->createMaxInstrLayout( gbox ) );
#ifdef VICE
layout->addItem( this->createMaxTimeLayout( gbox ) );
#endif // VICE
return gbox;
}
QLayout* optionsW::createMaxInstrLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Maximum instructions per slice:" ) );
layout->addWidget( label );
this->ip_maxInstrLabel = label;
QSpinBox * sbox = this->createSpinBox( parent, 1, 999999, 1000 );
layout->addWidget( sbox );
this->ip_maxInstr = sbox;
return layout;
}
#ifdef VICE
QLayout* optionsW::createMaxTimeLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Maximum time per slice:" ) );
layout->addWidget( label );
this->ip_maxTimeLabel = label;
QSpinBox * sbox = this->createSpinBox( parent, 1, 999999, 1000 );
layout->addWidget( sbox );
this->ip_maxTime = sbox;
return layout;
}
#endif // VICE
QLayout* optionsW::createPrimarySchdAlgorithmLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Primary Scheduling Algorithm" ) );
layout->addWidget( label );
QComboBox * cbox = this->createComboBox( parent );
#if QT_VERSION >= 0x040000
cbox->addItem(tr("pure_cooperative"));
#ifdef VICE
cbox->addItem(tr("timeslice"));
#endif // VISE
cbox->addItem(tr("instruction_number_slice"));
#else
cbox->insertItem(tr("pure_cooperative"));
#ifdef VICE
cbox->insertItem(tr("timeslice"));
#endif // VISE
cbox->insertItem(tr("instruction_number_slice"));
#endif // QT_VERSION >= 0x040000
layout->addWidget( cbox );
QObject::connect(cbox, SIGNAL(activated(int)), this, SLOT(algorithmChanged(int)));
this->ip_primaryAlg = cbox;
return layout;
}
#ifdef VICE
QLayout* optionsW::createStepSizeLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Step Size:" ) );
layout->addWidget( label );
QSpinBox * sbox = this->createSpinBox( parent, 0, 999999, 100 );
layout->addWidget( sbox );
this->ip_stepSize = sbox;
return layout;
}
QWidget* optionsW::createVirtualCPUCapacityGroupBox( QWidget * parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Virtual CPU") );
QLayout* layout = gbox->layout();
QCheckBox* checkbox = new QCheckBox( gbox );
checkbox->setText( tr( "Specify Virtual CPU Capacity" ) );
#if QT_VERSION >= 0x040000
layout->addWidget( checkbox );
#else
layout->add( checkbox );
#endif // QT_VERSION >= 0x040000
this->ip_vcpuCapacitycb = checkbox;
QLabel* label2 = new QLabel( gbox );
label2->setText( tr( "(Unchecking means INFINITE)" ) );
#if QT_VERSION >= 0x040000
layout->addWidget( label2 );
#else
layout->add( label2 );
#endif // QT_VERSION >= 0x040000
QLabel* label = new QLabel( gbox );
label->setText( tr( "Virtual CPU Capacity:" ) );
#if QT_VERSION >= 0x040000
layout->addWidget( label );
#else
layout->add( label );
#endif // QT_VERSION >= 0x040000
this->ip_vcpuCapacityLabel = label;
QSpinBox * sbox = this->createSpinBox( gbox, 1, 99999999, 1000000 );
#if QT_VERSION >= 0x040000
layout->addWidget( sbox );
#else
layout->add( sbox );
#endif // QT_VERSION >= 0x040000
this->ip_vcpuCapacity = sbox;
QObject::connect(this->ip_vcpuCapacitycb, SIGNAL(clicked()), this, SLOT(vcpuCapacityEnabled()));
return gbox;
}
QLayout* optionsW::createDefaultCapacityLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Default CPU Capacity:" ) );
layout->addWidget( label );
QSpinBox * sbox = this->createSpinBox( parent, 1, 99999999, 1000000 );
layout->addWidget( sbox );
this->ip_cpuCapacity = sbox;
return layout;
}
QLayout* optionsW::createJitterModeLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Jitter Mode:" ) );
layout->addWidget( label );
QComboBox * cbox = this->createComboBox( parent );
#if QT_VERSION >= 0x040000
cbox->addItem(tr("Early"));
cbox->addItem(tr("Random"));
cbox->addItem(tr("Late"));
#else
cbox->insertItem(tr("Early"));
cbox->insertItem(tr("Random"));
cbox->insertItem(tr("Late"));
#endif // QT_VERSION >= 0x040000
layout->addWidget( cbox );
this->ip_jitterMode = cbox;
return layout;
}
QWidget* optionsW::createTraceLogGroupBox( QWidget* parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Trace Logging") );
QLayout* layout = gbox->layout();
QCheckBox * cbox = new QCheckBox( gbox );
cbox->setText( tr( "Log All Operation's Arguments" ) );
#if QT_VERSION >= 0x040000
layout->addWidget( cbox );
#else
layout->add( cbox );
#endif // QT_VERSION >= 0x040000
this->ip_logArgsAllCheck = cbox;
QObject::connect(cbox, SIGNAL(clicked()), this, SLOT(logArgsAllEnabled()));
// QPushButton* button = new QPushButton( gbox, "OpSelectButton" );
// button->setText( tr( "Select operations" ) );
// layout->add( button );
// this->ip_opsSelectButton = button;
// QObject::connect(button,SIGNAL(clicked()),this,SLOT(interfaces()));
#if QT_VERSION >= 0x040000
QListWidget * lbox = new QListWidget( gbox );
layout->addWidget( lbox );
#else
QListBox * lbox = new QListBox( gbox );
layout->add( lbox );
#endif // QT_VERSION >= 0x040000
this->ip_selectedOpsList = lbox;
layout->addItem( this->createClassInputLayout( gbox ) );
layout->addItem( this->createOpInputLayout( gbox ) );
layout->addItem( this->createAddDelButtonLayout( gbox ) );
return gbox;
}
QLayout* optionsW::createClassInputLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Class Name:" ) );
layout->addWidget( label );
this->ip_classNameLabel = label;
QComboBox * cbox = this->createComboBox( parent );
QObject::connect(cbox, SIGNAL(activated(int)), this, SLOT(classChanged(int)));
layout->addWidget( cbox );
this->ip_className = cbox;
return layout;
}
QLayout* optionsW::createOpInputLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Operation Name:" ) );
layout->addWidget( label );
this->ip_opNameLabel = label;
QComboBox * cbox = this->createComboBox( parent );
layout->addWidget( cbox );
this->ip_opName = cbox;
return layout;
}
QLayout* optionsW::createAddDelButtonLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
layout->addWidget( this->createAddButton( parent ) );
layout->addWidget( this->createDeleteButton( parent ) );
return layout;
}
QPushButton * optionsW::createAddButton( QWidget * parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( tr( "Add Operation" ) );
this->ip_opAddButton = button;
QObject::connect(button,SIGNAL(clicked()),this,SLOT(addOperation()));
return button;
}
QPushButton * optionsW::createDeleteButton( QWidget * parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( tr( "Remove Operation" ) );
this->ip_opDelButton = button;
QObject::connect(button,SIGNAL(clicked()),this,SLOT(delOperation()));
return button;
}
#endif // VICE
#endif // VDMPP
QWidget* optionsW::createTypeCheckerTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createTypeCheckerFrame( tab ) );
return tab;
}
QWidget* optionsW::createTypeCheckerFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
layout->addWidget(this->createTypeCheckerButtonGroup( frame ));
layout->addWidget( this->createTypeCheckerExtCheckBox( frame ) );
layout->addWidget( this->createTypeCheckerMsgSepCheckBox( frame ) );
#ifdef VDMSL
layout->addWidget( this->createStandardVDMSLCheckBox( frame ) );
#endif // VDMSL
layout->addWidget( this->createVDM10CheckBox( frame ) );
layout->addItem( this->createSpacer() );
return frame;
}
QWidget* optionsW::createTypeCheckerButtonGroup( QWidget* parent )
{
#if QT_VERSION >= 0x040000
QGroupBox * bg = new QGroupBox( tr("Type Check Mode"), parent );
QRadioButton* radio1 = new QRadioButton( tr( "\"pos\" type check" ) );
this->tc_posTc = radio1;
QRadioButton* radio2 = new QRadioButton( tr( "\"def\" type check" ) );
this->tc_defTc = radio2;
QVBoxLayout * layout = new QVBoxLayout();
layout->addWidget(radio1);
layout->addWidget(radio2);
bg->setLayout(layout);
#else
QVButtonGroup* bg = new QVButtonGroup(tr("Type Check Mode"), parent, "tcButtons");
QRadioButton* radio1 = new QRadioButton(bg, "tcPos");
radio1->setText( tr( "\"pos\" type check" ) );
this->tc_posTc = radio1;
QRadioButton* radio2 = new QRadioButton(bg, "tcDef");
radio2->setText( tr( "\"def\" type check" ) );
this->tc_defTc = radio2;
#endif // QT_VERSION >= 0x040000
return bg;
}
QCheckBox* optionsW::createTypeCheckerExtCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Extended type check" ) );
this->tc_extTc = cbox;
return cbox;
}
QCheckBox* optionsW::createTypeCheckerMsgSepCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Warning/error message separation" ) );
this->tc_msgSeparation = cbox;
return cbox;
}
QCheckBox* optionsW::createStandardVDMSLCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Standard VDMSL" ) );
this->tc_standardVDMSL = cbox;
return cbox;
}
QCheckBox* optionsW::createVDM10CheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "VDM10 Compatible" ) );
this->tc_vdm10 = cbox;
return cbox;
}
QWidget* optionsW::createPrettyPrinterTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createPrettyPrinterFrame( tab ) );
return tab;
}
QWidget* optionsW::createPrettyPrinterFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
layout->addWidget( this->createPrettyPrinterIndex( frame ) );
layout->addWidget( this->createPrettyPrinterCloring( frame ) );
layout->addItem( this->createSpacer() );
return frame;
}
QWidget* optionsW::createPrettyPrinterIndex( QWidget* parent )
{
#if QT_VERSION >= 0x040000
QGroupBox * bg = new QGroupBox( tr("Output index"), parent );
QRadioButton* radio1 = new QRadioButton( tr( "No output index" ) );
this->pp_noIndex = radio1;
QRadioButton* radio2 = new QRadioButton( tr( "Output index of definitions" ) );
this->pp_defIndex = radio2;
QRadioButton* radio3 = new QRadioButton( tr( "Output index of definitions and uses" ) );
this->pp_useIndex = radio3;
QVBoxLayout * layout = new QVBoxLayout();
layout->addWidget(radio1);
layout->addWidget(radio2);
layout->addWidget(radio3);
bg->setLayout(layout);
#else
QVButtonGroup* bg = new QVButtonGroup(tr("Output index"), parent, "ppButtons");
QRadioButton* radio1 = new QRadioButton(bg, "pp_noIndex");
radio1->setText( tr( "No output index" ) );
this->pp_noIndex = radio1;
QRadioButton* radio2 = new QRadioButton(bg, "pp_defIndex");
radio2->setText( tr( "Output index of definitions" ) );
this->pp_defIndex = radio2;
QRadioButton* radio3 = new QRadioButton(bg, "pp_useIndex");
radio3->setText( tr( "Output index of definitions and uses" ) );
this->pp_useIndex = radio3;
#endif // QT_VERSION >= 0x040000
return bg;
}
QCheckBox* optionsW::createPrettyPrinterCloring( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Test coverage coloring" ) );
this->pp_tcovCol = cbox;
return cbox;
}
QWidget* optionsW::createCppCodeGeneratorTab( QWidget* parent )
{
QWidget* widget = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( widget );
layout->addWidget( this->createCppCodeGeneratorFrame( widget ) );
return widget;
}
QWidget* optionsW::createCppCodeGeneratorFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
layout->addWidget( this->createCppCodeGenPosInfCheckBox( frame ) );
#ifdef VDMPP
layout->addWidget( this->createCppCodeGenCheckCondsCheckBox( frame ) );
#endif // VDMPP
layout->addItem( this->createSpacer() );
return frame;
}
QCheckBox* optionsW::createCppCodeGenPosInfCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Output position information" ) );
this->cpp_posInfo = cbox;
return cbox;
}
QCheckBox* optionsW::createCppCodeGenCheckCondsCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Check pre and post conditions" ) );
this->cpp_checkConds = cbox;
return cbox;
}
#ifdef VDMPP
QWidget* optionsW::createJavaCodeGeneratorTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createJavaCodeGeneratorFrame( tab ) );
return tab;
}
QWidget* optionsW::createJavaInterfacesButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( tr( "Select interfaces" ) );
QObject::connect(button,SIGNAL(clicked()),this,SLOT(interfaces()));
return button;
}
QLayout* optionsW::createJavaPackageLayout( QWidget* parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Package:" ) );
layout->addWidget( label );
QLineEdit * edit = new QLineEdit( parent );
layout->addWidget( edit );
this->jcg_packageName = edit;
return layout;
}
QLayout* optionsW::createOutputDirCheckBox( QWidget* parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QCheckBox* checkbox = new QCheckBox( parent );
checkbox->setText( tr( "Specify Code Output Directory" ) );
this->jcg_useOutputDir = checkbox;
layout->addWidget( checkbox );
QPushButton* button = new QPushButton( parent );
button->setText( tr( "Select Code Output Directory" ) );
connect( button, SIGNAL(clicked()), this, SLOT(selectJCGDir()));
this->jcg_selectDir = button;
layout->addWidget( button );
return layout;
}
QLayout* optionsW::createOutputDirNamePart( QWidget* parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Output Directroy:" ) );
layout->addWidget( label );
this->jcg_outputDirLabel = label;
QLineEdit* le = new QLineEdit( parent );
layout->addWidget( le );
this->jcg_outputDirName = le;
return layout;
}
QWidget* optionsW::createJavaCodeGeneratorFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
QHBoxLayout* hlayout = this->createHBoxLayout( NULL );
QVBoxLayout* vlayout1 = this->createVBoxLayout( NULL );
QVBoxLayout* vlayout2 = this->createVBoxLayout( NULL );
this->jcg_skeletonsOnly = new QCheckBox( frame );
this->jcg_skeletonsOnly->setText( tr( "Generate only skeletons, except for types" ) );
vlayout1->addWidget( this->jcg_skeletonsOnly );
this->jcg_typesOnly = new QCheckBox( frame );
this->jcg_typesOnly->setText( tr( "Generate only types" ) );
vlayout1->addWidget( this->jcg_typesOnly );
this->jcg_useLongs = new QCheckBox( frame );
this->jcg_useLongs->setText( tr( "Generate integers as longs" ) );
vlayout1->addWidget( this->jcg_useLongs );
this->jcg_genConc = new QCheckBox( frame );
this->jcg_genConc->setText( tr( "Generate code with concurrency constructs" ) );
vlayout1->addWidget( this->jcg_genConc );
this->jcg_genConds = new QCheckBox( frame );
this->jcg_genConds->setText( tr( "Generate pre and post functions/operations" ) );
vlayout2->addWidget( this->jcg_genConds );
this->jcg_checkConds = new QCheckBox( frame );
this->jcg_checkConds->setText( tr( "Check pre and post conditions" ) );
vlayout2->addWidget( this->jcg_checkConds );
this->jcg_vdmPrefix = new QCheckBox( frame );
this->jcg_vdmPrefix->setText( tr( "Disable generate \"vdm_\" prefix" ) );
vlayout2->addWidget( this->jcg_vdmPrefix);
this->jcg_needBackup = new QCheckBox( frame );
this->jcg_needBackup->setText( tr( "Create backup file (*.bak)" ) );
vlayout2->addWidget( this->jcg_needBackup);
hlayout->addLayout(vlayout1);
hlayout->addLayout(vlayout2);
layout->addLayout(hlayout);
layout->addWidget( this->createJavaInterfacesButton( frame ) );
layout->addLayout( this->createJavaPackageLayout( frame ) );
layout->addItem( this->createOutputDirCheckBox( frame ) );
layout->addItem( this->createOutputDirNamePart( frame ) );
return frame;
}
QWidget* optionsW::createJ2VTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createJ2VFrame( tab ) );
return tab;
}
QWidget* optionsW::createJ2VFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
j2v_stubsOnly = new QCheckBox( frame );
j2v_stubsOnly->setText( mainW::mf(tr( "Generate &stubs only" )) );
layout->addWidget( j2v_stubsOnly );
// j2v_autoRenaming = new QCheckBox( frame );
// j2v_autoRenaming->setText( tr( "Automatic &renaming" ) );
// layout->addWidget( j2v_autoRenaming );
// j2v_genAccessors = new QCheckBox( frame );
// j2v_genAccessors->setText( tr( "&Generate acessor functions" ) );
// layout->addWidget( j2v_genAccessors );
j2v_transforms = new QCheckBox( frame );
j2v_transforms->setText( mainW::mf(tr( "Apply VDM++ &transformations" )) );
layout->addWidget( j2v_transforms );
layout->addItem( this->createSpacer() );
return frame;
}
#ifdef VICE
QWidget* optionsW::createVICETab( QWidget* parent )
{
QWidget* widget = new QWidget( parent );
QHBoxLayout* layout = this->createHBoxLayout( widget );
layout->addItem( this->createVICELayout1( widget ) );
layout->addItem( this->createVICELayout2( widget ) );
return widget;
}
QLayout* optionsW::createVICELayout1( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
layout->addLayout( this->createStepSizeLayout(parent) );
layout->addLayout( this->createJitterModeLayout(parent) );
layout->addLayout( this->createDefaultCapacityLayout(parent) );
layout->addWidget( this->createVirtualCPUCapacityGroupBox(parent) );
layout->addItem( this->createSpacer() );
return layout;
}
QLayout* optionsW::createVICELayout2( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
layout->addWidget( this->createTraceLogGroupBox( parent ) );
return layout;
}
#endif // VICE
#endif // VDMPP
QLayout* optionsW::createButtonPart( QWidget* parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
layout->addWidget( this->createSaveOptionsCheckbox( parent ) );
layout->addItem( this->createSpacer() );
layout->addWidget( this->createCancelButton( parent ) );
layout->addWidget( this->createApplyButton( parent ) );
layout->addWidget( this->createOkButton( parent ) );
return layout;
}
QWidget* optionsW::createHelpButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( mainW::mf(tr( "&Help" )) );
button->setAutoDefault( true );
return button;
}
QWidget* optionsW::createSaveOptionsCheckbox( QWidget* parent )
{
QCheckBox* checkbox = new QCheckBox( parent );
checkbox->setText( tr( "Save Options" ) );
checkbox->setChecked(true);
this->saveOptionsFlag = checkbox;
return checkbox;
}
QWidget* optionsW::createOkButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( mainW::mf(tr( "&OK" )) );
button->setAutoDefault( true );
button->setDefault( true );
connect( button, SIGNAL( clicked() ), this, SLOT( okPressed() ) );
return button;
}
QWidget* optionsW::createCancelButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( mainW::mf(tr( "&Cancel" )) );
button->setAutoDefault( true );
connect( button, SIGNAL( clicked() ), this, SLOT( reject() ) );
return button;
}
QWidget* optionsW::createApplyButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( mainW::mf(tr( "&Apply" )) );
button->setAutoDefault( true );
connect( button, SIGNAL( clicked() ), this, SLOT( putOptions() ));
return button;
}
/*
* Destroys the object and frees any allocated resources
*/
optionsW::~optionsW()
{
// no need to delete child widgets, Qt does it all for us
}
void optionsW::interfaces()
{
interfacesW * interfacesF = new interfacesW(this, "", true, 0);
#if QT_VERSION >= 0x040000
interfacesF->setWindowIcon(windowIcon());
#else
interfacesF->setIcon(*icon());
#endif // QT_VERSION >= 0x040000
interfacesF->show();
interfacesF->exec();
if (interfacesF->result() == QDialog::Accepted)
{
QStringList interfaces (interfacesF->getInterfaces());
Qt2TB::setSelectedInterfacesI(interfaces);
}
}
void optionsW::show()
{
// this->loadOptions();
this->setOptions();
QDialog::show();
}
void optionsW::okPressed()
{
this->putOptions();
accept();
this->saveOptions();
}
void optionsW::setOptions()
{
QMap<QString, QString> optionMap (Qt2TB::GetOptions());
this->ip_dynTypeCheck->setChecked(String2Bool(optionMap[ "DTC" ]));
this->ip_dynInvCheck->setChecked(String2Bool(optionMap[ "INV" ]));
this->ip_preCheck->setChecked(String2Bool(optionMap[ "PRE" ]));
this->ip_postCheck->setChecked(String2Bool(optionMap[ "POST" ]));
this->ip_measureCheck->setChecked(String2Bool(optionMap[ "MEASURE" ]));
#ifdef VDMPP
this->ip_prioritySchd->setChecked(String2Bool(optionMap[ "PRIORITY" ]));
QString alg (optionMap[ "PRIMARYALGORITHM" ]);
for(int i = 0; i < this->ip_primaryAlg->count(); i++) {
#if QT_VERSION >= 0x040000
this->ip_primaryAlg->setCurrentIndex(i);
#else
this->ip_primaryAlg->setCurrentItem(i);
#endif // QT_VERSION >= 0x040000
if(alg == this->ip_primaryAlg->currentText()) {
this->algorithmChanged(i);
break;
}
}
this->ip_maxInstr->setValue(optionMap[ "MAXINSTR" ].toInt());
#ifdef VICE
this->ip_maxTime->setValue(optionMap[ "MAXTIME" ].toInt());
this->ip_stepSize->setValue(optionMap[ "STEPSIZE" ].toInt());
this->ip_cpuCapacity->setValue(optionMap[ "DEFAULTCPUCAPACITY" ].toInt());
if(optionMap[ "DEFAULTVCPUCAPACITY" ] == "<INFINITE>") {
this->ip_vcpuCapacitycb->setChecked(false);
}
else {
this->ip_vcpuCapacitycb->setChecked(true);
this->ip_vcpuCapacity->setValue(optionMap[ "DEFAULTVCPUCAPACITY" ].toInt());
}
this->vcpuCapacityEnabled();
QString jmode (optionMap[ "JITTERMODE" ]);
for(int j = 0; j < this->ip_jitterMode->count(); j++) {
#if QT_VERSION >= 0x040000
this->ip_jitterMode->setCurrentIndex(j);
#else
this->ip_jitterMode->setCurrentItem(j);
#endif // QT_VERSION >= 0x040000
if(jmode == this->ip_jitterMode->currentText()) {
break;
}
}
this->ip_selectedOpsList->clear();
QString logargs (optionMap[ "LOGARGS" ]);
if (logargs == "<ALL>") {
this->ip_logArgsAllCheck->setChecked(true);
}
else {
this->ip_logArgsAllCheck->setChecked(false);
#if QT_VERSION >= 0x040000
QStringList list (logargs.split( ',' ));
#else
QStringList list (QStringList::split( ',', logargs ));
#endif // QT_VERSION >= 0x040000
for( QStringList::const_iterator it = list.begin(); it != list.end(); ++it ) {
#if QT_VERSION >= 0x040000
this->ip_selectedOpsList->addItem(*it);
#else
this->ip_selectedOpsList->insertItem(*it);
#endif // QT_VERSION >= 0x040000
}
}
this->loadClassName();
#endif // VICE
#endif //VDMPP
this->ip_ppValues->setChecked(String2Bool(optionMap[ "PRINT_FORMAT" ]));
this->ip_exception->setChecked(String2Bool(optionMap[ "RTERR_EXCEPTION" ]));
this->ip_rndGen->setValue(optionMap[ "Seed_nondetstmt" ].toInt());
this->ip_expression->setText(optionMap[ "EXPRESSION" ]);
this->ip_oldreverse->setChecked(String2Bool(optionMap[ "OLD_REVERSE" ]));
// Type checker options
this->tc_posTc->setChecked(optionMap[ "DEF" ] != "def");
this->tc_defTc->setChecked(optionMap[ "DEF" ] == "def");
this->tc_extTc->setChecked(String2Bool(optionMap[ "errlevel" ]));
this->tc_msgSeparation->setChecked(String2Bool(optionMap[ "SEP" ]));
#ifdef VDMSL
this->tc_standardVDMSL->setChecked(String2Bool(optionMap[ "VDMSLMOD" ]));
#endif // VDMSL
this->tc_vdm10->setChecked(String2Bool(optionMap[ "VDM10" ]));
// Pretty printer options
int index = optionMap[ "INDEX" ].toInt();
this->pp_noIndex->setChecked(index == 0);
this->pp_defIndex->setChecked(index == 1);
this->pp_useIndex->setChecked(index == 2);
this->pp_tcovCol->setChecked(String2Bool(optionMap[ "PrettyPrint_RTI" ]));
// C++ Code generator options
this->cpp_posInfo->setChecked(String2Bool(optionMap[ "CG_RTI" ]));
#ifdef VDMPP
this->cpp_checkConds->setChecked(String2Bool(optionMap[ "CG_CHECKPREPOST" ]));
#endif // VDMPP
#ifdef VDMPP
// Java code generator options
this->jcg_skeletonsOnly->setChecked(String2Bool(optionMap[ "JCG_SKEL" ]));
this->jcg_typesOnly->setChecked(String2Bool(optionMap[ "JCG_TYPES" ]));
this->jcg_useLongs->setChecked(String2Bool(optionMap[ "JCG_LONGS" ]));
this->jcg_genConc->setChecked(String2Bool(optionMap[ "JCG_CONCUR" ]));
this->jcg_genConds->setChecked(String2Bool(optionMap[ "JCG_GENPREPOST" ]));
this->jcg_checkConds->setChecked(String2Bool(optionMap[ "JCG_CHECKPREPOST" ]));
this->jcg_packageName->setText(optionMap[ "JCG_PACKAGE" ]);
this->jcg_vdmPrefix->setChecked(!String2Bool(optionMap[ "JCG_VDMPREFIX" ]));
this->jcg_useOutputDir->setChecked(String2Bool(optionMap[ "JCG_USEDIRNAME" ]));
this->jcg_outputDirName->setText(optionMap[ "JCG_DIRNAME" ]);
this->jcg_needBackup->setChecked(String2Bool(optionMap[ "JCG_NEEDBACKUP" ]));
if (this->jcg_useOutputDir->isChecked()) {
QDir dir (this->jcg_outputDirName->text());
if (!dir.exists()) {
this->jcg_useOutputDir->setChecked(false);
this->jcg_outputDirName->setText("");
}
}
#endif //VDMPP
// Java2VDM options
// j2v_stubsOnly->setChecked();
// j2v_autoRenaming->setChecked();
// j2v_genAccessors->setChecked();
this->invClicked();
}
void optionsW::putOptions()
{
QMap<QString, QString> optionMap;
optionMap[ "DTC" ] = (this->ip_dynTypeCheck->isChecked() ? "1" : "0");
optionMap[ "INV" ] = (this->ip_dynInvCheck->isChecked() ? "1" : "0");
optionMap[ "PRE" ] = (this->ip_preCheck->isChecked() ? "1" : "0");
optionMap[ "POST" ] = (this->ip_postCheck->isChecked() ? "1" : "0");
optionMap[ "MEASURE" ] = (this->ip_measureCheck->isChecked() ? "1" : "0");
#ifdef VDMPP
optionMap[ "PRIORITY" ] = (this->ip_prioritySchd->isChecked() ? "1" : "0");
optionMap[ "PRIMARYALGORITHM" ] = this->ip_primaryAlg->currentText();
optionMap[ "MAXINSTR" ] = QString::number(this->ip_maxInstr->value());
#ifdef VICE
optionMap[ "MAXTIME" ] = QString::number(this->ip_maxTime->value());
optionMap[ "STEPSIZE" ] = QString::number(this->ip_stepSize->value());
optionMap[ "DEFAULTCPUCAPACITY" ] = QString::number(this->ip_cpuCapacity->value());
if( this->ip_vcpuCapacitycb->isChecked() ) {
optionMap[ "DEFAULTVCPUCAPACITY" ] = QString::number(this->ip_vcpuCapacity->value());
}
else {
optionMap[ "DEFAULTVCPUCAPACITY" ] = "<INFINITE>";
}
optionMap[ "JITTERMODE" ] = this->ip_jitterMode->currentText();
if( this->ip_logArgsAllCheck->isChecked() ) {
optionMap[ "LOGARGS" ] = "<ALL>";
}
else {
int len = this->ip_selectedOpsList->count();
QString str;
for(int i = 0; i < len; i++) {
if( i > 0 ) str += ",";
#if QT_VERSION >= 0x040000
QListWidgetItem * item = this->ip_selectedOpsList->item(i);
str += item->text();
#else
str += this->ip_selectedOpsList->text(i);
#endif // QT_VERSION >= 0x040000
}
optionMap[ "LOGARGS" ] = str;
}
#endif // VICE
#endif //VDMPP
optionMap[ "PRINT_FORMAT" ] = (this->ip_ppValues->isChecked() ? "1" : "0");
optionMap[ "RTERR_EXCEPTION" ] = (this->ip_exception->isChecked() ? "1" : "0");
optionMap[ "EXPRESSION" ] = this->ip_expression->text();
optionMap[ "Seed_nondetstmt" ] = QString::number(this->ip_rndGen->value());
optionMap[ "OLD_REVERSE" ] = (this->ip_oldreverse->isChecked() ? "1" : "0");
optionMap[ "DEF" ] = (this->tc_defTc->isChecked() ? "def" : "pos");
optionMap[ "errlevel" ] = (this->tc_extTc->isChecked() ? "1" : "0");
optionMap[ "SEP" ] = (this->tc_msgSeparation->isChecked() ? "1" : "0");
#ifdef VDMSL
optionMap[ "VDMSLMOD" ] = (this->tc_standardVDMSL->isChecked() ? "1" : "0");
#endif // VDMSL
optionMap[ "VDM10" ] = (this->tc_vdm10->isChecked() ? "1" : "0");
// Pretty printer options
if (this->pp_useIndex->isChecked()) {
optionMap[ "INDEX" ] = "2";
}
else if (this->pp_defIndex->isChecked()) {
optionMap[ "INDEX" ] = "1";
}
else {
optionMap[ "INDEX" ] = "0";
}
optionMap[ "PrettyPrint_RTI" ] = (this->pp_tcovCol->isChecked() ? "1" : "0");
// C++ Code generator options
optionMap[ "CG_RTI" ] = (this->cpp_posInfo->isChecked() ? "1" : "0");
#ifdef VDMPP
optionMap[ "CG_CHECKPREPOST" ] = (this->cpp_checkConds->isChecked() ? "1" : "0");
#endif // VDMPP
#ifdef VDMPP
// Java code generator options
optionMap[ "JCG_SKEL" ] = (this->jcg_skeletonsOnly->isChecked() ? "1" : "0");
optionMap[ "JCG_TYPES" ] = (this->jcg_typesOnly->isChecked() ? "1" : "0");
optionMap[ "JCG_LONGS" ] = (this->jcg_useLongs->isChecked() ? "1" : "0");
optionMap[ "JCG_CONCUR" ] = (this->jcg_genConc->isChecked() ? "1" : "0");
optionMap[ "JCG_GENPREPOST" ] = (this->jcg_genConds->isChecked() ? "1" : "0");
optionMap[ "JCG_CHECKPREPOST" ] = (this->jcg_checkConds->isChecked() ? "1" : "0");
optionMap[ "JCG_PACKAGE" ] = this->jcg_packageName->text();
optionMap[ "JCG_VDMPREFIX" ] = (!this->jcg_vdmPrefix->isChecked() ? "1" : "0");
optionMap[ "JCG_USEDIRNAME" ] = (this->jcg_useOutputDir->isChecked() ? "1" : "0");
optionMap[ "JCG_DIRNAME" ] = this->jcg_outputDirName->text();
optionMap[ "JCG_NEEDBACKUP" ] = (this->jcg_needBackup->isChecked() ? "1" : "0");
#endif //VDMPP
Qt2TB::SetOptions(optionMap);
// Java2VDM options
// j2v_stubsOnly->setChecked();
// j2v_autoRenaming->setChecked();
// j2v_genAccessors->setChecked();
}
#ifdef VDMPP
bool optionsW::get_j2v_stubsOnly()
{
return j2v_stubsOnly->isChecked();
}
/*
bool optionsW::get_j2v_autoRenaming()
{
return j2v_autoRenaming->isChecked();
}
*/
bool optionsW::get_j2v_transforms()
{
return j2v_transforms->isChecked();
}
void optionsW::clearJ2VOptions()
{
this->j2v_stubsOnly->setChecked(false);
this->j2v_transforms->setChecked(false);
}
#endif //VDMPP
QString optionsW::getOptionFileName(const QString & prj)
{
QString nm = prj;
if (nm.right(4) != ".prj") return QString();
nm.replace( ".prj", ".opt" );
return nm;
}
void optionsW::loadOptions()
{
#ifdef VDMPP
this->clearJ2VOptions();
#endif // VDMPP
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
this->mainw->logWrite(QString("loadOptions for ") + filenm);
QFile optionFile( filenm );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::ReadOnly) ) {
#else
if( optionFile.open(IO_ReadOnly) ) {
#endif // QT_VERSION >= 0x040000
QTextStream optionStream(&optionFile);
QString version = optionStream.readLine();
optionFile.close();
if( version == "FormatVersion:2" ) {
this->loadOptionsV2();
}
else {
this->loadOptionsV1();
}
#if QT_VERSION >= 0x040000
this->maintab->setCurrentIndex(0);
#else
this->maintab->setCurrentPage(0);
#endif // QT_VERSION >= 0x040000
return;
}
}
Qt2TB::InitOptions();
}
bool optionsW::String2Bool(const QString & str)
{
if( str == "0" || str == "false" || str == "off" ) {
return false;
}
else if( str == "1" || str == "true" || str == "on" ) {
return true;
}
return false;
}
bool optionsW::optionFileExists()
{
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QFile optionFile( filenm );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::ReadOnly) ) {
#else
if( optionFile.open(IO_ReadOnly) ) {
#endif // QT_VERSION >= 0x040000
optionFile.close();
return true;
}
}
return false;
}
void optionsW::loadOptionsV1()
{
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QFile optionFile( filenm );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::ReadOnly) ) {
#else
if( optionFile.open(IO_ReadOnly) ) {
#endif // QT_VERSION >= 0x040000
QTextStream optionStream(&optionFile);
QMap<QString, QString> optionMap;
optionMap[ "DTC" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "PRE" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "POST" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "INV" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "SEP" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "CONTEXT" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
#ifdef VDMPP
optionMap[ "MAXINSTR" ] = (optionStream.readLine());
optionMap[ "PRIORITY" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
#ifdef VICE
optionMap[ "PRIMARYALGORITHM" ] = (optionStream.readLine());
optionMap[ "TASKSWITCH" ] = (optionStream.readLine());
optionMap[ "MAXTIME" ] = (optionStream.readLine());
optionMap[ "TIMEFACTOR" ] = (optionStream.readLine());
#endif //VICE
#endif //VDMPP
optionMap[ "VDMSLMODE" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "errlevel" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "PRINT_FORMAT" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "RTERR_EXCEPTION" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "CG_RTI" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "CG_CHECKPREPOST" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
QString tmp;
tmp = optionStream.readLine();
optionMap[ "DEF" ] = ((tmp == "1" || tmp == "def") ? "def" : "pos");
optionMap[ "INDEX" ] = (optionStream.readLine());
optionMap[ "PrettyPrint_RTI" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "C_flag" ] = (optionStream.readLine());
optionMap[ "JCG_SKEL" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_GENPREPOST" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_TYPES" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_SMALLTYPES" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_LONGS" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_PACKAGE" ] = (optionStream.readLine());
optionMap[ "JCG_CONCUR" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_CHECKPREPOST" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_INTERFACES" ] = (optionStream.readLine());
optionMap[ "Seed_nondetstmt" ] = (optionStream.readLine());
Qt2TB::SetOptions(optionMap);
#ifdef VDMPP
j2v_stubsOnly->setChecked(String2Bool(optionStream.readLine()));
j2v_transforms->setChecked(String2Bool(optionStream.readLine()));
#endif // VDMPP
optionFile.close();
}
}
}
void optionsW::loadOptionsV2()
{
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QMap<QString, QString> optionMap (readOption2(filenm));;
#if QT_VERSION >= 0x040000
if (!optionMap.empty()) {
#else
if (!optionMap.isEmpty()) {
#endif // QT_VERSION >= 0x040000
#ifdef VDMPP
if( optionMap.contains( "FVStatic" ) && !optionMap.contains( "VDM10" ) ) {
optionMap["VDM10"] == optionMap["FVStatic"];
}
#endif // VDMPP
Qt2TB::SetOptions(optionMap);
#ifdef VDMPP
if( optionMap.contains( "j2v_stubsOnly" ) ) {
j2v_stubsOnly->setChecked(optionMap["j2v_stubsOnly"] == "1");
}
if( optionMap.contains( "j2v_transforms" ) ) {
j2v_transforms->setChecked(optionMap["j2v_transforms"] == "1");
}
#endif // VDMPP
}
}
}
QMap<QString, QString> optionsW::readOption2(const QString & filename)
{
QMap<QString, QString> optionMap;
QFile optionFile( filename );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::ReadOnly) ) {
#else
if( optionFile.open(IO_ReadOnly) ) {
#endif // QT_VERSION >= 0x040000
QTextStream optionStream(&optionFile);
while( !optionStream.atEnd() ) {
QString tmp = optionStream.readLine();
if( !tmp.isEmpty() ) {
#if QT_VERSION >= 0x040000
int index = tmp.indexOf( ':' );
if( index != -1 ) {
QString key = tmp.left( index ).simplified();
QString value = tmp.right( tmp.length() - index - 1 ).simplified();
optionMap[ key ] = value;
}
#else
int index = tmp.find( ':' );
if( index != -1 ) {
QString key = tmp.left( index ).stripWhiteSpace();
QString value = tmp.right( tmp.length() - index - 1 ).stripWhiteSpace();
optionMap[ key ] = value;
}
#endif // QT_VERSION >= 0x040000
}
}
optionFile.close();
}
return optionMap;
}
void optionsW::saveOptions()
{
if( this->saveOptionsFlag->isChecked() ) {
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QFile optionFile( filenm );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::WriteOnly) ) {
#else
if( optionFile.open(IO_WriteOnly) ) {
#endif // QT_VERSION >= 0x040000
QTextStream optionStream(&optionFile);
optionStream << "FormatVersion:2" << endl;
QMap<QString, QString> optionMap (Qt2TB::GetOptions());
#if QT_VERSION >= 0x040000
QList<QString> keys (optionMap.keys());
for (QList<QString>::const_iterator it = keys.begin();it != keys.end();++it) {
#else
QValueList<QString> keys (optionMap.keys());
for (QValueList<QString>::const_iterator it = keys.begin();it != keys.end();++it) {
#endif // QT_VERSION >= 0x040000
optionStream << *it << ":" << optionMap[*it] << endl;
}
#ifdef VDMPP
optionStream << "j2v_stubsOnly:" << ( j2v_stubsOnly->isChecked() ? "1" : "0" ) << endl;
optionStream << "j2v_transforms:" << ( j2v_transforms->isChecked() ? "1" : "0" ) << endl;
#endif // VDMPP
optionStream << "TextCodecName:" << this->currentCodecName << endl;
optionFile.close();
}
}
}
}
void optionsW::algorithmChanged(int)
{
#ifdef VDMPP
QString alg (this->ip_primaryAlg->currentText());
if( alg == "instruction_number_slice" ) {
this->ip_maxInstr->setEnabled(true);
this->ip_maxInstrLabel->setEnabled(true);
#ifdef VICE
this->ip_maxTime->setEnabled(false);
this->ip_maxTimeLabel->setEnabled(false);
#endif // VICE
}
#ifdef VICE
else if( alg == "timeslice" ) {
this->ip_maxInstr->setEnabled(false);
this->ip_maxInstrLabel->setEnabled(false);
this->ip_maxTime->setEnabled(true);
this->ip_maxTimeLabel->setEnabled(true);
}
#endif // VICE
else {
this->ip_maxInstr->setEnabled(false);
this->ip_maxInstrLabel->setEnabled(false);
#ifdef VICE
this->ip_maxTime->setEnabled(false);
this->ip_maxTimeLabel->setEnabled(false);
#endif // VICE
}
#endif // VDMPP
}
void optionsW::vcpuCapacityEnabled()
{
#ifdef VICE
if (this->ip_vcpuCapacitycb->isChecked()) {
this->ip_vcpuCapacityLabel->setEnabled(true);
this->ip_vcpuCapacity->setEnabled(true);
}
else {
this->ip_vcpuCapacityLabel->setEnabled(false);
this->ip_vcpuCapacity->setEnabled(false);
}
#endif // VICE
}
#ifdef VICE
void optionsW::loadClassName()
{
QStringList clist (Qt2TB::getModulesI());
this->ip_className->clear();
for (QStringList::const_iterator it= clist.begin();it != clist.end();++it) {
#if QT_VERSION >= 0x040000
this->ip_className->addItem(*it);
#else
this->ip_className->insertItem(*it);
#endif // QT_VERSION >= 0x040000
}
#if QT_VERSION >= 0x040000
this->ip_className->setCurrentIndex(0);
#else
this->ip_className->setCurrentItem(0);
#endif // QT_VERSION >= 0x040000
this->classChanged(0);
}
#endif // VICE
void optionsW::logArgsAllEnabled()
{
#ifdef VICE
if(this->ip_logArgsAllCheck->isChecked()) {
this->ip_selectedOpsList->setEnabled(false);
this->ip_classNameLabel->setEnabled(false);
this->ip_className->setEnabled(false);
this->ip_opNameLabel->setEnabled(false);
this->ip_opName->setEnabled(false);
this->ip_opAddButton->setEnabled(false);
this->ip_opDelButton->setEnabled(false);
}
else {
this->ip_selectedOpsList->setEnabled(true);
this->ip_classNameLabel->setEnabled(true);
this->ip_className->setEnabled(true);
this->ip_opNameLabel->setEnabled(true);
this->ip_opName->setEnabled(true);
this->ip_opAddButton->setEnabled(true);
this->ip_opDelButton->setEnabled(true);
}
#endif // VICE
}
void optionsW::classChanged(int i)
{
#ifdef VICE
this->ip_opName->clear();
QString clsnm (this->ip_className->currentText());
if( !clsnm.isEmpty() ) {
QStringList oplist;
Qt2TB::setBlock(false);
int res = Qt2TB::getOperationsI(clsnm, oplist);
Qt2TB::setBlock(true);
if( res == INT_OK ) {
for (QStringList::const_iterator it= oplist.begin();it != oplist.end();++it) {
#if QT_VERSION >= 0x040000
this->ip_opName->addItem(*it);
#else
this->ip_opName->insertItem(*it);
#endif // QT_VERSION >= 0x040000
}
#if QT_VERSION >= 0x040000
this->ip_opName->setCurrentIndex(0);
#else
this->ip_opName->setCurrentItem(0);
#endif// QT_VERSION >= 0x040000
}
else {
this->mainw->logWrite("Specification is not initialized.");
}
}
#endif // VICE
}
void optionsW::addOperation()
{
#ifdef VICE
QString clsnm (this->ip_className->currentText());
QString opnm (this->ip_opName->currentText());
if( !clsnm.isEmpty() && !opnm.isEmpty() ) {
QString fullnm (clsnm + "`" + opnm);
#if QT_VERSION >= 0x040000
if( (this->ip_selectedOpsList->findItems(fullnm, 0)).empty() ) {
this->ip_selectedOpsList->addItem(fullnm);
}
#else
if( this->ip_selectedOpsList->findItem(fullnm) == 0 ) {
this->ip_selectedOpsList->insertItem(fullnm);
}
#endif // QT_VERSION >= 0x040000
}
#endif // VICE
}
void optionsW::delOperation()
{
#ifdef VICE
#if QT_VERSION >= 0x040000
int ci = this->ip_selectedOpsList->currentRow();
QListWidgetItem * item = this->ip_selectedOpsList->item(ci);
if( item->isSelected() ) {
this->ip_selectedOpsList->removeItemWidget(item);
}
#else
int ci = this->ip_selectedOpsList->currentItem();
if( this->ip_selectedOpsList->isSelected( ci ) ) {
this->ip_selectedOpsList->removeItem(ci);
}
#endif // QT_VERSION >= 0x040000
#endif // VICE
}
void optionsW::invClicked()
{
if(this->ip_dynInvCheck->isChecked()) {
this->ip_dynTypeCheck->setChecked(true);
this->ip_dynTypeCheck->setEnabled(false);
}
else {
this->ip_dynTypeCheck->setEnabled(true);
}
}
void optionsW::selectJCGDir()
{
#ifdef VDMPP
QString res (QtPort::QtGetExistingDirectory( this, tr("Choose a java code directory"), QString()));
if( !res.isNull() ) {
this->jcg_outputDirName->setText(res);
}
#endif // VDMPP
}
void optionsW::initTab()
{
#if QT_VERSION >= 0x040000
this->maintab->setCurrentIndex(0);
#else
this->maintab->setCurrentPage(0);
#endif // QT_VERSION >= 0x040000
}
QString optionsW::getCodecName(const QString & prj)
{
QString ofn (getOptionFileName(prj));
QMap<QString, QString> optionMap (readOption2(ofn));
if( optionMap.contains( "TextCodecName" ) ) {
return optionMap["TextCodecName"];
}
else {
return QString("");
}
}
QString optionsW::getExpression()
{
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QMap<QString, QString> optionMap (readOption2(filenm));;
if( optionMap.contains( "EXPRESSION" ) ) {
return optionMap["EXPRESSION"];
}
}
return QString("");
}
| vdmtools/vdmtools | code/qtgui/optionsF.cc | C++ | gpl-3.0 | 56,557 |
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Mail;
use Nette;
/**
* Sends emails via the SMTP server.
*/
class SmtpMailer implements IMailer
{
use Nette\SmartObject;
/** @var resource */
private $connection;
/** @var string */
private $host;
/** @var int */
private $port;
/** @var string */
private $username;
/** @var string */
private $password;
/** @var string ssl | tls | (empty) */
private $secure;
/** @var int */
private $timeout;
/** @var resource */
private $context;
/** @var bool */
private $persistent;
public function __construct(array $options = [])
{
if (isset($options['host'])) {
$this->host = $options['host'];
$this->port = isset($options['port']) ? (int) $options['port'] : null;
} else {
$this->host = ini_get('SMTP');
$this->port = (int) ini_get('smtp_port');
}
$this->username = isset($options['username']) ? $options['username'] : '';
$this->password = isset($options['password']) ? $options['password'] : '';
$this->secure = isset($options['secure']) ? $options['secure'] : '';
$this->timeout = isset($options['timeout']) ? (int) $options['timeout'] : 20;
$this->context = isset($options['context']) ? stream_context_create($options['context']) : stream_context_get_default();
if (!$this->port) {
$this->port = $this->secure === 'ssl' ? 465 : 25;
}
$this->persistent = !empty($options['persistent']);
}
/**
* Sends email.
* @return void
* @throws SmtpException
*/
public function send(Message $mail)
{
$mail = clone $mail;
try {
if (!$this->connection) {
$this->connect();
}
if (($from = $mail->getHeader('Return-Path'))
|| ($from = key($mail->getHeader('From')))
) {
$this->write("MAIL FROM:<$from>", 250);
}
foreach (array_merge(
(array) $mail->getHeader('To'),
(array) $mail->getHeader('Cc'),
(array) $mail->getHeader('Bcc')
) as $email => $name) {
$this->write("RCPT TO:<$email>", [250, 251]);
}
$mail->setHeader('Bcc', null);
$data = $mail->generateMessage();
$this->write('DATA', 354);
$data = preg_replace('#^\.#m', '..', $data);
$this->write($data);
$this->write('.', 250);
if (!$this->persistent) {
$this->write('QUIT', 221);
$this->disconnect();
}
} catch (SmtpException $e) {
if ($this->connection) {
$this->disconnect();
}
throw $e;
}
}
/**
* Connects and authenticates to SMTP server.
* @return void
*/
protected function connect()
{
$this->connection = @stream_socket_client(// @ is escalated to exception
($this->secure === 'ssl' ? 'ssl://' : '') . $this->host . ':' . $this->port,
$errno, $error, $this->timeout, STREAM_CLIENT_CONNECT, $this->context
);
if (!$this->connection) {
throw new SmtpException($error, $errno);
}
stream_set_timeout($this->connection, $this->timeout, 0);
$this->read(); // greeting
$self = isset($_SERVER['HTTP_HOST']) && preg_match('#^[\w.-]+\z#', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
$this->write("EHLO $self");
$ehloResponse = $this->read();
if ((int) $ehloResponse !== 250) {
$this->write("HELO $self", 250);
}
if ($this->secure === 'tls') {
$this->write('STARTTLS', 220);
if (!stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
throw new SmtpException('Unable to connect via TLS.');
}
$this->write("EHLO $self", 250);
}
if ($this->username != null && $this->password != null) {
$authMechanisms = [];
if (preg_match('~^250[ -]AUTH (.*)$~im', $ehloResponse, $matches)) {
$authMechanisms = explode(' ', trim($matches[1]));
}
if (in_array('PLAIN', $authMechanisms, true)) {
$credentials = $this->username . "\0" . $this->username . "\0" . $this->password;
$this->write('AUTH PLAIN ' . base64_encode($credentials), 235, 'PLAIN credentials');
} else {
$this->write('AUTH LOGIN', 334);
$this->write(base64_encode($this->username), 334, 'username');
$this->write(base64_encode($this->password), 235, 'password');
}
}
}
/**
* Disconnects from SMTP server.
* @return void
*/
protected function disconnect()
{
fclose($this->connection);
$this->connection = null;
}
/**
* Writes data to server and checks response against expected code if some provided.
* @param string
* @param int|int[] response code
* @param string error message
* @return void
*/
protected function write($line, $expectedCode = null, $message = null)
{
fwrite($this->connection, $line . Message::EOL);
if ($expectedCode) {
$response = $this->read();
if (!in_array((int) $response, (array) $expectedCode, true)) {
throw new SmtpException('SMTP server did not accept ' . ($message ? $message : $line) . ' with error: ' . trim($response));
}
}
}
/**
* Reads response from server.
* @return string
*/
protected function read()
{
$s = '';
while (($line = fgets($this->connection, 1000)) != null) { // intentionally ==
$s .= $line;
if (substr($line, 3, 1) === ' ') {
break;
}
}
return $s;
}
}
| Kajry/Kajry-PersonalWeb | vendor/nette/mail/src/Mail/SmtpMailer.php | PHP | gpl-3.0 | 5,197 |
namespace WindowsFormsApplication1
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button7 = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.ti_reload = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.ti_screen = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.ti_toggle = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.i_toggle = new System.Windows.Forms.Label();
this.i_screen = new System.Windows.Forms.Label();
this.i_reload = new System.Windows.Forms.Label();
this.smaaSetting = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.checkBox1);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.smaaSetting);
this.groupBox1.Controls.Add(this.button7);
this.groupBox1.Controls.Add(this.groupBox2);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(260, 312);
this.groupBox1.TabIndex = 10;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Injector settings";
//
// button7
//
this.button7.Location = new System.Drawing.Point(6, 276);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(245, 30);
this.button7.TabIndex = 2;
this.button7.Text = "Save settings";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click_1);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.i_reload);
this.groupBox2.Controls.Add(this.i_screen);
this.groupBox2.Controls.Add(this.i_toggle);
this.groupBox2.Controls.Add(this.ti_reload);
this.groupBox2.Controls.Add(this.label9);
this.groupBox2.Controls.Add(this.ti_screen);
this.groupBox2.Controls.Add(this.label8);
this.groupBox2.Controls.Add(this.ti_toggle);
this.groupBox2.Controls.Add(this.label7);
this.groupBox2.Location = new System.Drawing.Point(6, 19);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(248, 100);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Key bindings";
//
// ti_reload
//
this.ti_reload.Location = new System.Drawing.Point(125, 71);
this.ti_reload.Name = "ti_reload";
this.ti_reload.Size = new System.Drawing.Size(36, 20);
this.ti_reload.TabIndex = 5;
this.ti_reload.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ti_reload_KeyDown);
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(6, 74);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(80, 13);
this.label9.TabIndex = 4;
this.label9.Text = "Reload settings";
//
// ti_screen
//
this.ti_screen.Location = new System.Drawing.Point(125, 47);
this.ti_screen.Name = "ti_screen";
this.ti_screen.Size = new System.Drawing.Size(36, 20);
this.ti_screen.TabIndex = 3;
this.ti_screen.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ti_screen_KeyDown);
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(6, 50);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(87, 13);
this.label8.TabIndex = 2;
this.label8.Text = "Save screenshot";
this.toolTip1.SetToolTip(this.label8, "Will save a .bmp image in the game\'s folder");
//
// ti_toggle
//
this.ti_toggle.Location = new System.Drawing.Point(125, 20);
this.ti_toggle.Name = "ti_toggle";
this.ti_toggle.Size = new System.Drawing.Size(36, 20);
this.ti_toggle.TabIndex = 1;
this.ti_toggle.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ti_toggle_KeyDown);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(6, 23);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(113, 13);
this.label7.TabIndex = 0;
this.label7.Text = "Toggle effects on / off";
//
// i_toggle
//
this.i_toggle.AutoSize = true;
this.i_toggle.Location = new System.Drawing.Point(167, 23);
this.i_toggle.Name = "i_toggle";
this.i_toggle.Size = new System.Drawing.Size(35, 13);
this.i_toggle.TabIndex = 6;
this.i_toggle.Text = "label1";
//
// i_screen
//
this.i_screen.AutoSize = true;
this.i_screen.Location = new System.Drawing.Point(167, 50);
this.i_screen.Name = "i_screen";
this.i_screen.Size = new System.Drawing.Size(35, 13);
this.i_screen.TabIndex = 7;
this.i_screen.Text = "label1";
//
// i_reload
//
this.i_reload.AutoSize = true;
this.i_reload.Location = new System.Drawing.Point(167, 74);
this.i_reload.Name = "i_reload";
this.i_reload.Size = new System.Drawing.Size(35, 13);
this.i_reload.TabIndex = 8;
this.i_reload.Text = "label1";
//
// smaaSetting
//
this.smaaSetting.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.smaaSetting.FormattingEnabled = true;
this.smaaSetting.Location = new System.Drawing.Point(88, 158);
this.smaaSetting.Name = "smaaSetting";
this.smaaSetting.Size = new System.Drawing.Size(157, 21);
this.smaaSetting.TabIndex = 3;
this.smaaSetting.SelectedIndexChanged += new System.EventHandler(this.smaaSetting_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 161);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(76, 13);
this.label1.TabIndex = 4;
this.label1.Text = "SMAA Preset :";
this.toolTip1.SetToolTip(this.label1, "SMAA preset to use. Default is \"SMAA_PRESET_CUSTOM\" - which allows for custom set" +
"tings");
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(9, 185);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(216, 17);
this.checkBox1.TabIndex = 5;
this.checkBox1.Text = "Enable Steam overlay compatibility hack";
this.checkBox1.UseVisualStyleBackColor = true;
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
//
// label2
//
this.label2.Location = new System.Drawing.Point(6, 236);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(245, 37);
this.label2.TabIndex = 6;
this.label2.Text = "Note: For changes done in here to take effect, the game usually needs to be resta" +
"rted.";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 336);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "Form2";
this.Text = "Form2";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TextBox ti_reload;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox ti_screen;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox ti_toggle;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label i_reload;
private System.Windows.Forms.Label i_screen;
private System.Windows.Forms.Label i_toggle;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox smaaSetting;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ToolTip toolTip1;
}
} | terrasque/sweetfxui | Form2.Designer.cs | C# | gpl-3.0 | 11,458 |
const Log = require("../util/log.js");
const common = require("../util/common.js");
const setting_global = require("../settings.json");
const setting_color = setting_global.commands.user.guilds.color;
const setting_mute = setting_global.commands.admin.mute;
const setting = setting_global.events.memberAdd;
module.exports = (client, member) => {
Log.memberAdd(member.user);
if (setting.welcomeMessage.enabled)
common.getChannel(client, setting.welcomeMessage.channel)
.send(setting.welcomeMessage.template[
common.getRandom(0, setting.welcomeMessage.template.length)]
.replace("{user}", member.user));
if (setting.autoRole.role)
setting.autoRole.role.forEach((role) =>
member.addRole(member.guild.roles
.find("name", role)));
if (setting.autoRole.random_color)
member.addRole(member.guild.roles
.find("name", setting_color.colors[common.getRandom(0, setting_color.colors.length)].role));
if (client.muted && setting.auto_mute)
{
let time = client.muted[member.id];
if (time)
member.addRole(member.guild.find("name", setting_mute.role));
}
}; | AndreyLysenkov/LausyWalpy | events/guildMemberAdd.js | JavaScript | gpl-3.0 | 1,206 |
<?php // $Id: pop.php,v 1.4 2004/10/31 11:37:35 ns Exp $
// Nikol S <ns@eyo.com.au> May 2004
// A more than simple pop class
class pop {
var $username = '';
var $password = '';
var $host = '';
var $port = '';
var $pop_connect = '';
var $log = '';
var $delete = '0';
function prepare_connection( $user, $pass, $host = "127.0.0.1", $port = "110" )
{
if ($user == '') {
return 0;
}
if ($pass == '') {
return 0;
}
if ($host == '') {
return 0;
}
$this->port = $port;
$this->username = $user;
$this->password = $pass;
$this->host = $host;
return 1;
}
// Connect to your pop server, return how many messages, or an error code
function connect()
{
$this->pop_connect = fsockopen($this->host, $this->port, $error_number, $error_string, 30);
if (!$this->pop_connect)
{
echo "$error_string ($error_number)\r\n";
return -1;
}
$results = $this->_gets();
$this->log .= $results;
if ( $this->_check($results) )
{
$this->_write("USER $this->username");
$results = $this->_gets();
$this->log .= $results;
if ( $this->_check($results) )
{
$this->_write("PASS $this->password");
$results = $this->_gets();
$this->log .= $results;
if ( $this->_check($results) )
{
return 1;
}
else
return -4;
} else
return -3;
}
return -2;
}
//How many emails avaiable
function howmany()
{
return $this->_howmany();
}
function _howmany()
{
$this->_write("STAT");
$results = $this->_gets();
$this->log .= $results;
list ($results, $messages, $bytes) = split(' ', $results);
return $messages;
}
//See if we get +OK from the server
function _check ($results)
{
if (preg_match("/\+OK/", $results))
return 1;
else
return 0;
}
// Read a line from the resource
function _gets( $bytes = 512 )
{
$results = '';
$results = fgets($this->pop_connect, $bytes);
return $results;
}
// Send to the resource
function _write($message)
{
$this->log .= $message . "\n";
fwrite($this->pop_connect, $message . "\r\n");
}
//Return the logs we have so far
function showlog()
{
return $this->log;
}
//Delete email after retrieval if this is called
function delete()
{
$this->delete = "1";
}
//Retrieve the entire email
function getemail ( $id )
{
$this->_write("RETR $id");
$results = $this->_gets();
$this->log .= $results;
if ($this->_check($results)) {
$email = '';
$line = $this->_gets();
while ( !ereg("^\.\r\n", $line)) {
$email .= $line;
$line = $this->_gets();
if(empty($line)) {
break;
}
}
}
return $email;
}
//delete the email from the server
function delete_mail ( $id )
{
$this->_write("DELE $id");
$results = $this->_gets();
}
//disconnect from the server
function disconnect ()
{
$this->_write("QUIT");
$this->log .= $this->_gets();
}
}
| chrisplough/otmfaq | otmfaq.com/htdocs/forums/includes/pop.php | PHP | gpl-3.0 | 2,974 |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CThrowable : CProjectileTrajectory
{
[Ordinal(1)] [RED("ownerHandle")] public EntityHandle OwnerHandle { get; set;}
[Ordinal(2)] [RED("wasThrown")] public CBool WasThrown { get; set;}
[Ordinal(3)] [RED("itemId")] public SItemUniqueId ItemId { get; set;}
[Ordinal(4)] [RED("isFromAimThrow")] public CBool IsFromAimThrow { get; set;}
public CThrowable(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CThrowable(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | Traderain/Wolven-kit | WolvenKit.CR2W/Types/W3/RTTIConvert/CThrowable.cs | C# | gpl-3.0 | 969 |
<?php
/**
* Section blocks
*
* @author WolfThemes
* @category Core
* @package WolfPageBuilder/Admin/Elements
* @version 2.8.9
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
wpb_add_element(
array(
'name' => esc_html__( 'Section with Blocks', 'wolf-page-builder' ),
'base' => 'section_blocks',
'icon' => 'wpb-icon wpb-section-blocks',
'params' => array(
array(
'type' => 'hidden',
'param_name' => 'section_type',
'value' => 'blocks',
),
array(
'type' => 'hidden',
'param_name' => 'layout',
'value' => '2-cols',
),
array(
'type' => 'text',
'label' => esc_html__( 'Margin', 'wolf-page-builder' ),
'param_name' => 'margin',
'placeholder' => '0',
'description' => esc_html__( 'Empty space around the content', 'wolf-page-builder' ),
),
array(
'type' => 'select',
'label' => esc_html__( 'Section Visibility', 'wolf-page-builder' ),
'param_name' => 'hide_class',
'choices' => array(
'' => esc_html__( 'Always visible', 'wolf-page-builder' ),
'wpb-hide-tablet' => esc_html__( 'Hide on tablet and mobile', 'wolf-page-builder' ),
'wpb-hide-mobile' => esc_html__( 'Hide on mobile', 'wolf-page-builder' ),
'wpb-show-tablet' => esc_html__( 'Show on tablet and mobile only', 'wolf-page-builder' ),
'wpb-show-mobile' => esc_html__( 'Show on mobile only', 'wolf-page-builder' ),
'wpb-hide' => esc_html__( 'Always hidden', 'wolf-page-builder' ),
),
),
array(
'type' => 'slug',
'label' => esc_html__( 'Anchor', 'wolf-page-builder' ),
'param_name' => 'anchor',
'placeholder' => 'my-section',
'description' => esc_html__( 'An unique identifier for your section.', 'wolf-page-builder' ),
),
array(
'type' => 'slug',
'label' => esc_html__( 'Extra Class', 'wolf-page-builder' ),
'param_name' => 'extra_class',
'placeholder' => '.my-class',
'description' => esc_html__( 'Optional additional CSS class to add to the section', 'wolf-page-builder' ),
),
array(
'type' => 'text',
'label' => esc_html__( 'Inline Style', 'wolf-page-builder' ),
'param_name' => 'inline_style',
'placeholder' => 'margin-top:15px;',
'description' => esc_html__( 'Additional inline CSS style', 'wolf-page-builder' ),
),
)
)
); | wolfthemes/wpb-test | inc/admin/elements/section-blocks.php | PHP | gpl-3.0 | 2,301 |
<?php
/**
* @package Joomla.Platform
* @subpackage Image
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Image Filter class to make an image appear "sketchy".
*
* @since 11.3
*/
class JImageFilterSketchy extends JImageFilter
{
/**
* Method to apply a filter to an image resource.
*
* @param array $options An array of options for the filter.
*
* @return void
*
* @since 11.3
*/
public function execute(array $options = array())
{
// Perform the sketchy filter.
imagefilter($this->handle, IMG_FILTER_MEAN_REMOVAL);
}
}
| MasiaArmato/coplux | libraries/joomla/image/filter/sketchy.php | PHP | gpl-3.0 | 759 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016/11/23 16:15
# @Author : xycfree
# @Link : http://example.org
# @Version : $
import os | xycfree/py_spider | baidu/__init__.py | Python | gpl-3.0 | 154 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using ICSharpCode.Decompiler.Ast.Transforms;
using ICSharpCode.Decompiler.ILAst;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.PatternMatching;
namespace ICSharpCode.Decompiler.Ast {
using dnSpy.Decompiler.Shared;
using Ast = ICSharpCode.NRefactory.CSharp;
public class AstMethodBodyBuilder
{
MethodDef methodDef;
ICorLibTypes corLib;
DecompilerContext context;
HashSet<ILVariable> localVariablesToDefine = new HashSet<ILVariable>(); // local variables that are missing a definition
/// <summary>
/// Creates the body for the method definition.
/// </summary>
/// <param name="methodDef">Method definition to decompile.</param>
/// <param name="context">Decompilation context.</param>
/// <param name="parameters">Parameter declarations of the method being decompiled.
/// These are used to update the parameter names when the decompiler generates names for the parameters.</param>
/// <returns>Block for the method body</returns>
public static BlockStatement CreateMethodBody(MethodDef methodDef,
DecompilerContext context,
IEnumerable<ParameterDeclaration> parameters,
out MemberMapping mm)
{
MethodDef oldCurrentMethod = context.CurrentMethod;
Debug.Assert(oldCurrentMethod == null || oldCurrentMethod == methodDef);
context.CurrentMethod = methodDef;
context.CurrentMethodIsAsync = false;
try {
AstMethodBodyBuilder builder = new AstMethodBodyBuilder();
builder.methodDef = methodDef;
builder.context = context;
builder.corLib = methodDef.Module.CorLibTypes;
if (Debugger.IsAttached) {
return builder.CreateMethodBody(parameters, out mm);
} else {
try {
return builder.CreateMethodBody(parameters, out mm);
} catch (OperationCanceledException) {
throw;
} catch (Exception ex) {
throw new ICSharpCode.Decompiler.DecompilerException(methodDef, ex);
}
}
} finally {
context.CurrentMethod = oldCurrentMethod;
}
}
BlockStatement CreateMethodBody(IEnumerable<ParameterDeclaration> parameters, out MemberMapping mm)
{
if (methodDef.Body == null) {
mm = null;
return null;
}
context.CancellationToken.ThrowIfCancellationRequested();
ILBlock ilMethod = new ILBlock();
ILAstBuilder astBuilder = new ILAstBuilder();
ilMethod.Body = astBuilder.Build(methodDef, true, context);
context.CancellationToken.ThrowIfCancellationRequested();
ILAstOptimizer bodyGraph = new ILAstOptimizer();
bodyGraph.Optimize(context, ilMethod);
context.CancellationToken.ThrowIfCancellationRequested();
var localVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable)
.Where(v => v != null && !v.IsParameter).Distinct();
Debug.Assert(context.CurrentMethod == methodDef);
NameVariables.AssignNamesToVariables(context, astBuilder.Parameters, localVariables, ilMethod);
if (parameters != null) {
foreach (var pair in (from p in parameters
join v in astBuilder.Parameters on p.Annotation<Parameter>() equals v.OriginalParameter
select new { p, v.Name }))
{
pair.p.NameToken = Identifier.Create(pair.Name).WithAnnotation(TextTokenKind.Parameter);
}
}
context.CancellationToken.ThrowIfCancellationRequested();
Ast.BlockStatement astBlock = TransformBlock(ilMethod);
CommentStatement.ReplaceAll(astBlock); // convert CommentStatements to Comments
Statement insertionPoint = astBlock.Statements.FirstOrDefault();
foreach (ILVariable v in localVariablesToDefine) {
AstType type;
if (v.Type.ContainsAnonymousType())
type = new SimpleType("var").WithAnnotation(TextTokenKind.Keyword);
else
type = AstBuilder.ConvertType(v.Type);
var newVarDecl = new VariableDeclarationStatement(v.IsParameter ? TextTokenKind.Parameter : TextTokenKind.Local, type, v.Name);
newVarDecl.Variables.Single().AddAnnotation(v);
astBlock.Statements.InsertBefore(insertionPoint, newVarDecl);
}
mm = new MemberMapping(methodDef, localVariables.ToList());
return astBlock;
}
Ast.BlockStatement TransformBlock(ILBlock block)
{
Ast.BlockStatement astBlock = new BlockStatement();
if (block != null) {
astBlock.HiddenStart = NRefactoryExtensions.CreateHidden(block.ILRanges, astBlock.HiddenStart);
astBlock.HiddenEnd = NRefactoryExtensions.CreateHidden(block.EndILRanges, astBlock.HiddenEnd);
foreach(ILNode node in block.GetChildren()) {
astBlock.Statements.AddRange(TransformNode(node));
}
}
return astBlock;
}
IEnumerable<Statement> TransformNode(ILNode node)
{
if (node is ILLabel) {
yield return new Ast.LabelStatement { Label = ((ILLabel)node).Name }.WithAnnotation(node.ILRanges);
} else if (node is ILExpression) {
AstNode codeExpr = TransformExpression((ILExpression)node);
if (codeExpr != null) {
if (codeExpr is Ast.Expression) {
yield return new Ast.ExpressionStatement { Expression = (Ast.Expression)codeExpr };
} else if (codeExpr is Ast.Statement) {
yield return (Ast.Statement)codeExpr;
} else {
throw new Exception();
}
}
} else if (node is ILWhileLoop) {
ILWhileLoop ilLoop = (ILWhileLoop)node;
Expression expr;
WhileStatement whileStmt = new WhileStatement() {
Condition = expr = ilLoop.Condition != null ? (Expression)TransformExpression(ilLoop.Condition) : new PrimitiveExpression(true),
EmbeddedStatement = TransformBlock(ilLoop.BodyBlock)
};
expr.AddAnnotation(ilLoop.ILRanges);
yield return whileStmt;
} else if (node is ILCondition) {
ILCondition conditionalNode = (ILCondition)node;
bool hasFalseBlock = conditionalNode.FalseBlock.EntryGoto != null || conditionalNode.FalseBlock.Body.Count > 0;
BlockStatement trueStmt;
var ifElseStmt = new Ast.IfElseStatement {
Condition = (Expression)TransformExpression(conditionalNode.Condition),
TrueStatement = trueStmt = TransformBlock(conditionalNode.TrueBlock),
FalseStatement = hasFalseBlock ? TransformBlock(conditionalNode.FalseBlock) : null
};
ifElseStmt.Condition.AddAnnotation(conditionalNode.ILRanges);
if (ifElseStmt.FalseStatement == null)
trueStmt.HiddenEnd = NRefactoryExtensions.CreateHidden(conditionalNode.FalseBlock.GetSelfAndChildrenRecursiveILRanges(), trueStmt.HiddenEnd);
yield return ifElseStmt;
} else if (node is ILSwitch) {
ILSwitch ilSwitch = (ILSwitch)node;
if (ilSwitch.Condition.InferredType.GetElementType() == ElementType.Boolean && (
from cb in ilSwitch.CaseBlocks
where cb.Values != null
from val in cb.Values
select val
).Any(val => val != 0 && val != 1))
{
// If switch cases contain values other then 0 and 1, force the condition to be non-boolean
ilSwitch.Condition.ExpectedType = corLib.Int32;
}
SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) };
switchStmt.Expression.AddAnnotation(ilSwitch.ILRanges);
switchStmt.HiddenEnd = NRefactoryExtensions.CreateHidden(ilSwitch.EndILRanges, switchStmt.HiddenEnd);
foreach (var caseBlock in ilSwitch.CaseBlocks) {
SwitchSection section = new SwitchSection();
if (caseBlock.Values != null) {
section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, (ilSwitch.Condition.ExpectedType ?? ilSwitch.Condition.InferredType).ToTypeDefOrRef()) }));
} else {
section.CaseLabels.Add(new CaseLabel());
}
section.Statements.Add(TransformBlock(caseBlock));
switchStmt.SwitchSections.Add(section);
}
yield return switchStmt;
} else if (node is ILTryCatchBlock) {
ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node);
var tryCatchStmt = new Ast.TryCatchStatement();
tryCatchStmt.TryBlock = TransformBlock(tryCatchNode.TryBlock);
tryCatchStmt.TryBlock.HiddenStart = NRefactoryExtensions.CreateHidden(tryCatchNode.ILRanges, tryCatchStmt.TryBlock.HiddenStart);
foreach (var catchClause in tryCatchNode.CatchBlocks) {
if (catchClause.ExceptionVariable == null
&& (catchClause.ExceptionType == null || catchClause.ExceptionType.GetElementType() == ElementType.Object))
{
tryCatchStmt.CatchClauses.Add(new Ast.CatchClause { Body = TransformBlock(catchClause) }.WithAnnotation(catchClause.StlocILRanges));
} else {
tryCatchStmt.CatchClauses.Add(
new Ast.CatchClause {
Type = AstBuilder.ConvertType(catchClause.ExceptionType),
VariableNameToken = catchClause.ExceptionVariable == null ? null : Identifier.Create(catchClause.ExceptionVariable.Name).WithAnnotation(catchClause.ExceptionVariable.IsParameter ? TextTokenKind.Parameter : TextTokenKind.Local),
Body = TransformBlock(catchClause)
}.WithAnnotation(catchClause.ExceptionVariable).WithAnnotation(catchClause.StlocILRanges));
}
}
if (tryCatchNode.FinallyBlock != null)
tryCatchStmt.FinallyBlock = TransformBlock(tryCatchNode.FinallyBlock);
if (tryCatchNode.FaultBlock != null) {
CatchClause cc = new CatchClause();
cc.Body = TransformBlock(tryCatchNode.FaultBlock);
cc.Body.Add(new ThrowStatement()); // rethrow
tryCatchStmt.CatchClauses.Add(cc);
}
yield return tryCatchStmt;
} else if (node is ILFixedStatement) {
ILFixedStatement fixedNode = (ILFixedStatement)node;
FixedStatement fixedStatement = new FixedStatement();
for (int i = 0; i < fixedNode.Initializers.Count; i++) {
var initializer = fixedNode.Initializers[i];
Debug.Assert(initializer.Code == ILCode.Stloc);
ILVariable v = (ILVariable)initializer.Operand;
VariableInitializer vi;
fixedStatement.Variables.Add(vi =
new VariableInitializer {
NameToken = Identifier.Create(v.Name).WithAnnotation(v.IsParameter ? TextTokenKind.Parameter : TextTokenKind.Local),
Initializer = (Expression)TransformExpression(initializer.Arguments[0])
}.WithAnnotation(v));
vi.AddAnnotation(ILRange.OrderAndJoin(initializer.GetSelfAndChildrenRecursiveILRanges()));
if (i == 0)
vi.AddAnnotation(ILRange.OrderAndJoin(fixedNode.ILRanges));
}
fixedStatement.Type = AstBuilder.ConvertType(((ILVariable)fixedNode.Initializers[0].Operand).Type);
fixedStatement.EmbeddedStatement = TransformBlock(fixedNode.BodyBlock);
yield return fixedStatement;
} else if (node is ILBlock) {
yield return TransformBlock((ILBlock)node);
} else {
throw new Exception("Unknown node type");
}
}
AstNode TransformExpression(ILExpression expr)
{
List<ILRange> ilRanges = ILRange.OrderAndJoin(expr.GetSelfAndChildrenRecursiveILRanges());
AstNode node = TransformByteCode(expr);
Expression astExpr = node as Expression;
AstNode result;
if (astExpr != null)
result = Convert(astExpr, expr.InferredType, expr.ExpectedType);
else
result = node;
if (result != null)
result = result.WithAnnotation(new TypeInformation(expr.InferredType, expr.ExpectedType));
if (result != null)
return result.WithAnnotation(ilRanges);
return result;
}
IMDTokenProvider Create_SystemArray_get_Length()
{
if (Create_SystemArray_get_Length_result_initd)
return Create_SystemArray_get_Length_result;
Create_SystemArray_get_Length_result_initd = true;
const string propName = "Length";
var type = corLib.GetTypeRef("System", "Array");
var retType = corLib.Int32;
var mr = new MemberRefUser(methodDef.Module, "get_" + propName, MethodSig.CreateInstance(retType), type);
Create_SystemArray_get_Length_result = mr;
var md = mr.ResolveMethod();
if (md == null || md.DeclaringType == null)
return mr;
var prop = md.DeclaringType.FindProperty(propName);
if (prop == null)
return mr;
Create_SystemArray_get_Length_result = prop;
return prop;
}
IMDTokenProvider Create_SystemArray_get_Length_result;
bool Create_SystemArray_get_Length_result_initd;
IMDTokenProvider Create_SystemType_get_TypeHandle()
{
if (Create_SystemType_get_TypeHandle_initd)
return Create_SystemType_get_TypeHandle_result;
Create_SystemType_get_TypeHandle_initd = true;
const string propName = "TypeHandle";
var type = corLib.GetTypeRef("System", "Type");
var retType = new ValueTypeSig(corLib.GetTypeRef("System", "RuntimeTypeHandle"));
var mr = new MemberRefUser(methodDef.Module, "get_" + propName, MethodSig.CreateInstance(retType), type);
Create_SystemType_get_TypeHandle_result = mr;
var md = mr.ResolveMethod();
if (md == null || md.DeclaringType == null)
return mr;
var prop = md.DeclaringType.FindProperty(propName);
if (prop == null)
return mr;
Create_SystemType_get_TypeHandle_result = prop;
return prop;
}
IMDTokenProvider Create_SystemType_get_TypeHandle_result;
bool Create_SystemType_get_TypeHandle_initd;
AstNode TransformByteCode(ILExpression byteCode)
{
object operand = byteCode.Operand;
AstType operandAsTypeRef = AstBuilder.ConvertType(operand as ITypeDefOrRef);
List<Ast.Expression> args = new List<Expression>();
foreach(ILExpression arg in byteCode.Arguments) {
args.Add((Ast.Expression)TransformExpression(arg));
}
Ast.Expression arg1 = args.Count >= 1 ? args[0] : null;
Ast.Expression arg2 = args.Count >= 2 ? args[1] : null;
Ast.Expression arg3 = args.Count >= 3 ? args[2] : null;
switch (byteCode.Code) {
#region Arithmetic
case ILCode.Add:
case ILCode.Add_Ovf:
case ILCode.Add_Ovf_Un:
{
BinaryOperatorExpression boe;
if (byteCode.InferredType is PtrSig) {
boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2);
if (byteCode.Arguments[0].ExpectedType is PtrSig ||
byteCode.Arguments[1].ExpectedType is PtrSig) {
boe.AddAnnotation(IntroduceUnsafeModifier.PointerArithmeticAnnotation);
}
} else {
boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2);
}
boe.AddAnnotation(byteCode.Code == ILCode.Add ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation);
return boe;
}
case ILCode.Sub:
case ILCode.Sub_Ovf:
case ILCode.Sub_Ovf_Un:
{
BinaryOperatorExpression boe;
if (byteCode.InferredType is PtrSig) {
boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2);
if (byteCode.Arguments[0].ExpectedType is PtrSig) {
boe.WithAnnotation(IntroduceUnsafeModifier.PointerArithmeticAnnotation);
}
} else {
boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2);
}
boe.AddAnnotation(byteCode.Code == ILCode.Sub ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation);
return boe;
}
case ILCode.Div: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2);
case ILCode.Div_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2);
case ILCode.Mul: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.UncheckedAnnotation);
case ILCode.Mul_Ovf: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.CheckedAnnotation);
case ILCode.Mul_Ovf_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.CheckedAnnotation);
case ILCode.Rem: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2);
case ILCode.Rem_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2);
case ILCode.And: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseAnd, arg2);
case ILCode.Or: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseOr, arg2);
case ILCode.Xor: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ExclusiveOr, arg2);
case ILCode.Shl: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftLeft, arg2);
case ILCode.Shr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2);
case ILCode.Shr_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2);
case ILCode.Neg: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Minus, arg1).WithAnnotation(AddCheckedBlocks.UncheckedAnnotation);
case ILCode.Not: return new Ast.UnaryOperatorExpression(UnaryOperatorType.BitNot, arg1);
case ILCode.PostIncrement:
case ILCode.PostIncrement_Ovf:
case ILCode.PostIncrement_Ovf_Un:
{
if (arg1 is DirectionExpression)
arg1 = ((DirectionExpression)arg1).Expression.Detach();
var uoe = new Ast.UnaryOperatorExpression(
(int)byteCode.Operand > 0 ? UnaryOperatorType.PostIncrement : UnaryOperatorType.PostDecrement, arg1);
uoe.AddAnnotation((byteCode.Code == ILCode.PostIncrement) ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation);
return uoe;
}
#endregion
#region Arrays
case ILCode.Newarr: {
var ace = new Ast.ArrayCreateExpression();
ace.Type = operandAsTypeRef;
ComposedType ct = operandAsTypeRef as ComposedType;
if (ct != null) {
// change "new (int[,])[10] to new int[10][,]"
ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers);
}
if (byteCode.Code == ILCode.InitArray) {
ace.Initializer = new ArrayInitializerExpression();
ace.Initializer.Elements.AddRange(args);
} else {
ace.Arguments.Add(arg1);
}
return ace;
}
case ILCode.InitArray: {
var ace = new Ast.ArrayCreateExpression();
ace.Type = operandAsTypeRef;
ComposedType ct = operandAsTypeRef as ComposedType;
if (ct != null)
{
// change "new (int[,])[10] to new int[10][,]"
ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers);
ace.Initializer = new ArrayInitializerExpression();
}
var arySig = ((TypeSpec)operand).TypeSig.RemovePinnedAndModifiers() as ArraySigBase;
if (arySig == null) {
}
else if (arySig.IsSingleDimensional)
{
ace.Initializer.Elements.AddRange(args);
}
else
{
var newArgs = new List<Expression>();
foreach (var length in arySig.GetLengths().Skip(1).Reverse())
{
for (int j = 0; j < args.Count; j += length)
{
var child = new ArrayInitializerExpression();
child.Elements.AddRange(args.GetRange(j, length));
newArgs.Add(child);
}
var temp = args;
args = newArgs;
newArgs = temp;
newArgs.Clear();
}
ace.Initializer.Elements.AddRange(args);
}
return ace;
}
case ILCode.Ldlen: return arg1.Member("Length", TextTokenKind.InstanceProperty).WithAnnotation(Create_SystemArray_get_Length());
case ILCode.Ldelem_I:
case ILCode.Ldelem_I1:
case ILCode.Ldelem_I2:
case ILCode.Ldelem_I4:
case ILCode.Ldelem_I8:
case ILCode.Ldelem_U1:
case ILCode.Ldelem_U2:
case ILCode.Ldelem_U4:
case ILCode.Ldelem_R4:
case ILCode.Ldelem_R8:
case ILCode.Ldelem_Ref:
case ILCode.Ldelem:
return arg1.Indexer(arg2);
case ILCode.Ldelema:
return MakeRef(arg1.Indexer(arg2));
case ILCode.Stelem_I:
case ILCode.Stelem_I1:
case ILCode.Stelem_I2:
case ILCode.Stelem_I4:
case ILCode.Stelem_I8:
case ILCode.Stelem_R4:
case ILCode.Stelem_R8:
case ILCode.Stelem_Ref:
case ILCode.Stelem:
return new Ast.AssignmentExpression(arg1.Indexer(arg2), arg3);
case ILCode.CompoundAssignment:
{
CastExpression cast = arg1 as CastExpression;
var boe = cast != null ? (BinaryOperatorExpression)cast.Expression : arg1 as BinaryOperatorExpression;
// AssignmentExpression doesn't support overloaded operators so they have to be processed to BinaryOperatorExpression
if (boe == null) {
var tmp = new ParenthesizedExpression(arg1);
ReplaceMethodCallsWithOperators.ProcessInvocationExpression((InvocationExpression)arg1);
boe = (BinaryOperatorExpression)tmp.Expression;
}
var assignment = new Ast.AssignmentExpression {
Left = boe.Left.Detach(),
Operator = ReplaceMethodCallsWithOperators.GetAssignmentOperatorForBinaryOperator(boe.Operator),
Right = boe.Right.Detach()
}.CopyAnnotationsFrom(boe);
// We do not mark the resulting assignment as RestoreOriginalAssignOperatorAnnotation, because
// the operator cannot be translated back to the expanded form (as the left-hand expression
// would be evaluated twice, and might have side-effects)
if (cast != null) {
cast.Expression = assignment;
return cast;
} else {
return assignment;
}
}
#endregion
#region Comparison
case ILCode.Ceq: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Equality, arg2);
case ILCode.Cne: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.InEquality, arg2);
case ILCode.Cgt: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2);
case ILCode.Cgt_Un: {
// can also mean Inequality, when used with object references
TypeSig arg1Type = byteCode.Arguments[0].InferredType;
if (arg1Type != null && !DnlibExtensions.IsValueType(arg1Type)) goto case ILCode.Cne;
// when comparing signed integral values using Cgt_Un with 0
// the Ast should actually contain InEquality since "(uint)a > 0u" is identical to "a != 0"
if (arg1Type.IsSignedIntegralType())
{
var p = arg2 as Ast.PrimitiveExpression;
if (p != null && p.Value.IsZero()) goto case ILCode.Cne;
}
goto case ILCode.Cgt;
}
case ILCode.Cle_Un: {
// can also mean Equality, when used with object references
TypeSig arg1Type = byteCode.Arguments[0].InferredType;
if (arg1Type != null && !DnlibExtensions.IsValueType(arg1Type)) goto case ILCode.Ceq;
// when comparing signed integral values using Cle_Un with 0
// the Ast should actually contain Equality since "(uint)a <= 0u" is identical to "a == 0"
if (arg1Type.IsSignedIntegralType())
{
var p = arg2 as Ast.PrimitiveExpression;
if (p != null && p.Value.IsZero()) goto case ILCode.Ceq;
}
goto case ILCode.Cle;
}
case ILCode.Cle: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThanOrEqual, arg2);
case ILCode.Cge_Un:
case ILCode.Cge: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThanOrEqual, arg2);
case ILCode.Clt_Un:
case ILCode.Clt: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2);
#endregion
#region Logical
case ILCode.LogicNot: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Not, arg1);
case ILCode.LogicAnd: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalAnd, arg2);
case ILCode.LogicOr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalOr, arg2);
case ILCode.TernaryOp: return new Ast.ConditionalExpression() { Condition = arg1, TrueExpression = arg2, FalseExpression = arg3 };
case ILCode.NullCoalescing: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.NullCoalescing, arg2);
#endregion
#region Branch
case ILCode.Br: return new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name);
case ILCode.Brtrue:
return new Ast.IfElseStatement() {
Condition = arg1,
TrueStatement = new BlockStatement() {
new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name)
}
};
case ILCode.LoopOrSwitchBreak: return new Ast.BreakStatement();
case ILCode.LoopContinue: return new Ast.ContinueStatement();
#endregion
#region Conversions
case ILCode.Conv_I1:
case ILCode.Conv_I2:
case ILCode.Conv_I4:
case ILCode.Conv_I8:
case ILCode.Conv_U1:
case ILCode.Conv_U2:
case ILCode.Conv_U4:
case ILCode.Conv_U8:
case ILCode.Conv_I:
case ILCode.Conv_U:
{
// conversion was handled by Convert() function using the info from type analysis
CastExpression cast = arg1 as CastExpression;
if (cast != null) {
cast.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation);
}
return arg1;
}
case ILCode.Conv_R4:
case ILCode.Conv_R8:
case ILCode.Conv_R_Un: // TODO
return arg1;
case ILCode.Conv_Ovf_I1:
case ILCode.Conv_Ovf_I2:
case ILCode.Conv_Ovf_I4:
case ILCode.Conv_Ovf_I8:
case ILCode.Conv_Ovf_U1:
case ILCode.Conv_Ovf_U2:
case ILCode.Conv_Ovf_U4:
case ILCode.Conv_Ovf_U8:
case ILCode.Conv_Ovf_I1_Un:
case ILCode.Conv_Ovf_I2_Un:
case ILCode.Conv_Ovf_I4_Un:
case ILCode.Conv_Ovf_I8_Un:
case ILCode.Conv_Ovf_U1_Un:
case ILCode.Conv_Ovf_U2_Un:
case ILCode.Conv_Ovf_U4_Un:
case ILCode.Conv_Ovf_U8_Un:
case ILCode.Conv_Ovf_I:
case ILCode.Conv_Ovf_U:
case ILCode.Conv_Ovf_I_Un:
case ILCode.Conv_Ovf_U_Un:
{
// conversion was handled by Convert() function using the info from type analysis
CastExpression cast = arg1 as CastExpression;
if (cast != null) {
cast.AddAnnotation(AddCheckedBlocks.CheckedAnnotation);
}
return arg1;
}
case ILCode.Unbox_Any:
// unboxing does not require a cast if the argument was an isinst instruction
if (arg1 is AsExpression && byteCode.Arguments[0].Code == ILCode.Isinst && TypeAnalysis.IsSameType(operand as ITypeDefOrRef, byteCode.Arguments[0].Operand as ITypeDefOrRef))
return arg1;
else
goto case ILCode.Castclass;
case ILCode.Castclass:
if ((byteCode.Arguments[0].InferredType != null && byteCode.Arguments[0].InferredType.IsGenericParameter) || (operand as ITypeDefOrRef).TryGetGenericSig() != null)
return arg1.CastTo(new PrimitiveType("object")).CastTo(operandAsTypeRef);
else
return arg1.CastTo(operandAsTypeRef);
case ILCode.Isinst:
return arg1.CastAs(operandAsTypeRef);
case ILCode.Box:
return arg1;
case ILCode.Unbox:
return MakeRef(arg1.CastTo(operandAsTypeRef));
#endregion
#region Indirect
case ILCode.Ldind_Ref:
case ILCode.Ldobj:
if (arg1 is DirectionExpression)
return ((DirectionExpression)arg1).Expression.Detach();
else
return new UnaryOperatorExpression(UnaryOperatorType.Dereference, arg1);
case ILCode.Stind_Ref:
case ILCode.Stobj:
if (arg1 is DirectionExpression)
return new AssignmentExpression(((DirectionExpression)arg1).Expression.Detach(), arg2);
else
return new AssignmentExpression(new UnaryOperatorExpression(UnaryOperatorType.Dereference, arg1), arg2);
#endregion
case ILCode.Arglist:
return new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.ArgListAccess };
case ILCode.Break: return InlineAssembly(byteCode, args);
case ILCode.Call:
case ILCode.CallGetter:
case ILCode.CallSetter:
return TransformCall(false, byteCode, args);
case ILCode.Callvirt:
case ILCode.CallvirtGetter:
case ILCode.CallvirtSetter:
return TransformCall(true, byteCode, args);
case ILCode.Ldftn: {
IMethod method = (IMethod)operand;
var expr = Ast.IdentifierExpression.Create(method.Name, method);
expr.TypeArguments.AddRange(ConvertTypeArguments(method));
expr.AddAnnotation(method);
return IdentifierExpression.Create("ldftn", TextTokenKind.OpCode).Invoke(expr)
.WithAnnotation(new Transforms.DelegateConstruction.Annotation(false));
}
case ILCode.Ldvirtftn: {
IMethod method = (IMethod)operand;
var expr = Ast.IdentifierExpression.Create(method.Name, method);
expr.TypeArguments.AddRange(ConvertTypeArguments(method));
expr.AddAnnotation(method);
return IdentifierExpression.Create("ldvirtftn", TextTokenKind.OpCode).Invoke(expr)
.WithAnnotation(new Transforms.DelegateConstruction.Annotation(true));
}
case ILCode.Calli: return InlineAssembly(byteCode, args);
case ILCode.Ckfinite: return InlineAssembly(byteCode, args);
case ILCode.Constrained: return InlineAssembly(byteCode, args);
case ILCode.Cpblk: return InlineAssembly(byteCode, args);
case ILCode.Cpobj: return InlineAssembly(byteCode, args);
case ILCode.Dup: return arg1;
case ILCode.Endfilter: return InlineAssembly(byteCode, args);
case ILCode.Endfinally: return null;
case ILCode.Initblk: return InlineAssembly(byteCode, args);
case ILCode.Initobj: return InlineAssembly(byteCode, args);
case ILCode.DefaultValue:
return MakeDefaultValue((operand as ITypeDefOrRef).ToTypeSig());
case ILCode.Jmp: return InlineAssembly(byteCode, args);
case ILCode.Ldc_I4:
return AstBuilder.MakePrimitive((int)operand, byteCode.InferredType.ToTypeDefOrRef());
case ILCode.Ldc_I8:
return AstBuilder.MakePrimitive((long)operand, byteCode.InferredType.ToTypeDefOrRef());
case ILCode.Ldc_R4:
case ILCode.Ldc_R8:
case ILCode.Ldc_Decimal:
return new Ast.PrimitiveExpression(operand);
case ILCode.Ldfld:
if (arg1 is DirectionExpression)
arg1 = ((DirectionExpression)arg1).Expression.Detach();
return arg1.Member(((IField) operand).Name, operand).WithAnnotation(operand);
case ILCode.Ldsfld:
return AstBuilder.ConvertType(((IField)operand).DeclaringType)
.Member(((IField)operand).Name, operand).WithAnnotation(operand);
case ILCode.Stfld:
if (arg1 is DirectionExpression)
arg1 = ((DirectionExpression)arg1).Expression.Detach();
return new AssignmentExpression(arg1.Member(((IField) operand).Name, operand).WithAnnotation(operand), arg2);
case ILCode.Stsfld:
return new AssignmentExpression(
AstBuilder.ConvertType(((IField)operand).DeclaringType)
.Member(((IField)operand).Name, operand).WithAnnotation(operand),
arg1);
case ILCode.Ldflda:
if (arg1 is DirectionExpression)
arg1 = ((DirectionExpression)arg1).Expression.Detach();
return MakeRef(arg1.Member(((IField) operand).Name, operand).WithAnnotation(operand));
case ILCode.Ldsflda:
return MakeRef(
AstBuilder.ConvertType(((IField)operand).DeclaringType)
.Member(((IField)operand).Name, operand).WithAnnotation(operand));
case ILCode.Ldloc: {
ILVariable v = (ILVariable)operand;
if (!v.IsParameter)
localVariablesToDefine.Add((ILVariable)operand);
Expression expr;
if (v.IsParameter && v.OriginalParameter.IsHiddenThisParameter)
expr = new ThisReferenceExpression().WithAnnotation(methodDef.DeclaringType);
else
expr = Ast.IdentifierExpression.Create(((ILVariable)operand).Name, ((ILVariable)operand).IsParameter ? TextTokenKind.Parameter : TextTokenKind.Local).WithAnnotation(operand);
return v.IsParameter && v.Type is ByRefSig ? MakeRef(expr) : expr;
}
case ILCode.Ldloca: {
ILVariable v = (ILVariable)operand;
if (v.IsParameter && v.OriginalParameter.IsHiddenThisParameter)
return MakeRef(new ThisReferenceExpression().WithAnnotation(methodDef.DeclaringType));
if (!v.IsParameter)
localVariablesToDefine.Add((ILVariable)operand);
return MakeRef(Ast.IdentifierExpression.Create(((ILVariable)operand).Name, ((ILVariable)operand).IsParameter ? TextTokenKind.Parameter : TextTokenKind.Local).WithAnnotation(operand));
}
case ILCode.Ldnull: return new Ast.NullReferenceExpression();
case ILCode.Ldstr: return new Ast.PrimitiveExpression(operand);
case ILCode.Ldtoken:
if (operand is ITypeDefOrRef) {
var th = Create_SystemType_get_TypeHandle();
return AstBuilder.CreateTypeOfExpression((ITypeDefOrRef)operand).Member("TypeHandle", TextTokenKind.InstanceProperty).WithAnnotation(th);
} else {
Expression referencedEntity;
string loadName;
string handleName;
if (operand is IField && ((IField)operand).FieldSig != null) {
loadName = "fieldof";
handleName = "FieldHandle";
IField fr = (IField)operand;
referencedEntity = AstBuilder.ConvertType(fr.DeclaringType).Member(fr.Name, fr).WithAnnotation(fr);
} else if (operand is IMethod) {
loadName = "methodof";
handleName = "MethodHandle";
IMethod mr = (IMethod)operand;
var methodParameters = mr.MethodSig.GetParameters().Select(p => new TypeReferenceExpression(AstBuilder.ConvertType(p)));
referencedEntity = AstBuilder.ConvertType(mr.DeclaringType).Invoke(mr, mr.Name, methodParameters).WithAnnotation(mr);
} else {
loadName = "ldtoken";
handleName = "Handle";
var ie = IdentifierExpression.Create(FormatByteCodeOperand(byteCode.Operand), byteCode.Operand);
ie.IdentifierToken.AddAnnotation(IdentifierFormatted.Instance);
referencedEntity = ie;
}
return IdentifierExpression.Create(loadName, TextTokenKind.Keyword).Invoke(referencedEntity).WithAnnotation(new LdTokenAnnotation()).Member(handleName, TextTokenKind.InstanceProperty);
}
case ILCode.Leave: return new GotoStatement() { Label = ((ILLabel)operand).Name };
case ILCode.Localloc:
{
PtrSig ptrType = byteCode.InferredType as PtrSig;
TypeSig type;
if (ptrType != null) {
type = ptrType.Next;
} else {
type = corLib.Byte;
}
return new StackAllocExpression {
Type = AstBuilder.ConvertType(type),
CountExpression = arg1
};
}
case ILCode.Mkrefany:
{
DirectionExpression dir = arg1 as DirectionExpression;
if (dir != null) {
return new UndocumentedExpression {
UndocumentedExpressionType = UndocumentedExpressionType.MakeRef,
Arguments = { dir.Expression.Detach() }
};
} else {
return InlineAssembly(byteCode, args);
}
}
case ILCode.Refanytype:
return new UndocumentedExpression {
UndocumentedExpressionType = UndocumentedExpressionType.RefType,
Arguments = { arg1 }
}.Member("TypeHandle", TextTokenKind.InstanceProperty).WithAnnotation(Create_SystemType_get_TypeHandle());
case ILCode.Refanyval:
return MakeRef(
new UndocumentedExpression {
UndocumentedExpressionType = UndocumentedExpressionType.RefValue,
Arguments = { arg1, new TypeReferenceExpression(operandAsTypeRef) }
});
case ILCode.Newobj: {
ITypeDefOrRef declaringType = ((IMethod)operand).DeclaringType;
if (declaringType.TryGetSZArraySig() != null || declaringType.TryGetArraySig() != null) {
ComposedType ct = AstBuilder.ConvertType(declaringType) as ComposedType;
if (ct != null && ct.ArraySpecifiers.Count >= 1) {
var ace = new Ast.ArrayCreateExpression();
ct.ArraySpecifiers.First().Remove();
ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers);
ace.Type = ct;
ace.Arguments.AddRange(args);
return ace;
}
}
if (declaringType.IsAnonymousType()) {
MethodDef ctor = ((IMethod)operand).Resolve();
if (methodDef != null) {
AnonymousTypeCreateExpression atce = new AnonymousTypeCreateExpression();
if (CanInferAnonymousTypePropertyNamesFromArguments(args, ctor.Parameters)) {
atce.Initializers.AddRange(args);
} else {
int skip = ctor.Parameters.GetParametersSkip();
for (int i = 0; i < args.Count; i++) {
atce.Initializers.Add(
new NamedExpression {
NameToken = Identifier.Create(ctor.Parameters[i + skip].Name).WithAnnotation(ctor.Parameters[i + skip]),
Expression = args[i]
});
}
}
return atce;
}
}
var oce = new Ast.ObjectCreateExpression();
oce.Type = AstBuilder.ConvertType(declaringType);
oce.Arguments.AddRange(args);
return oce.WithAnnotation(operand);
}
case ILCode.No: return InlineAssembly(byteCode, args);
case ILCode.Nop: return null;
case ILCode.Pop: return arg1;
case ILCode.Readonly: return InlineAssembly(byteCode, args);
case ILCode.Ret:
if (methodDef.ReturnType.GetFullName() != "System.Void") {
return new Ast.ReturnStatement { Expression = arg1 };
} else {
return new Ast.ReturnStatement();
}
case ILCode.Rethrow: return new Ast.ThrowStatement();
case ILCode.Sizeof: return new Ast.SizeOfExpression { Type = operandAsTypeRef };
case ILCode.Stloc: {
ILVariable locVar = (ILVariable)operand;
if (!locVar.IsParameter)
localVariablesToDefine.Add(locVar);
return new Ast.AssignmentExpression(Ast.IdentifierExpression.Create(locVar.Name, locVar.IsParameter ? TextTokenKind.Parameter : TextTokenKind.Local).WithAnnotation(locVar), arg1);
}
case ILCode.Switch: return InlineAssembly(byteCode, args);
case ILCode.Tailcall: return InlineAssembly(byteCode, args);
case ILCode.Throw: return new Ast.ThrowStatement { Expression = arg1 };
case ILCode.Unaligned: return InlineAssembly(byteCode, args);
case ILCode.Volatile: return InlineAssembly(byteCode, args);
case ILCode.YieldBreak:
return new Ast.YieldBreakStatement();
case ILCode.YieldReturn:
return new Ast.YieldReturnStatement { Expression = arg1 };
case ILCode.InitObject:
case ILCode.InitCollection:
{
ArrayInitializerExpression initializer = new ArrayInitializerExpression();
for (int i = 1; i < args.Count; i++) {
Match m = objectInitializerPattern.Match(args[i]);
if (m.Success) {
MemberReferenceExpression mre = m.Get<MemberReferenceExpression>("left").Single();
initializer.Elements.Add(
new NamedExpression {
NameToken = (Identifier)mre.MemberNameToken.Clone(),
Expression = m.Get<Expression>("right").Single().Detach()
}.CopyAnnotationsFrom(mre));
} else {
m = collectionInitializerPattern.Match(args[i]);
if (m.Success) {
if (m.Get("arg").Count() == 1) {
initializer.Elements.Add(m.Get<Expression>("arg").Single().Detach());
} else {
ArrayInitializerExpression argList = new ArrayInitializerExpression();
foreach (var expr in m.Get<Expression>("arg")) {
argList.Elements.Add(expr.Detach());
}
initializer.Elements.Add(argList);
}
} else {
initializer.Elements.Add(args[i]);
}
}
}
ObjectCreateExpression oce = arg1 as ObjectCreateExpression;
DefaultValueExpression dve = arg1 as DefaultValueExpression;
if (oce != null) {
oce.Initializer = initializer;
return oce;
} else if (dve != null) {
oce = new ObjectCreateExpression(dve.Type.Detach());
oce.CopyAnnotationsFrom(dve);
oce.Initializer = initializer;
return oce;
} else {
return new AssignmentExpression(arg1, initializer);
}
}
case ILCode.InitializedObject:
return new InitializedObjectExpression();
case ILCode.Wrap:
return arg1.WithAnnotation(PushNegation.LiftedOperatorAnnotation);
case ILCode.AddressOf:
return MakeRef(arg1);
case ILCode.ExpressionTreeParameterDeclarations:
args[args.Count - 1].AddAnnotation(new ParameterDeclarationAnnotation(byteCode));
return args[args.Count - 1];
case ILCode.Await:
return new UnaryOperatorExpression(UnaryOperatorType.Await, UnpackDirectionExpression(arg1));
case ILCode.NullableOf:
case ILCode.ValueOf:
return arg1;
default:
throw new Exception("Unknown OpCode: " + byteCode.Code);
}
}
internal static bool CanInferAnonymousTypePropertyNamesFromArguments(IList<Expression> args, IList<Parameter> parameters)
{
int skip = parameters.GetParametersSkip();
for (int i = 0; i < args.Count; i++) {
string inferredName;
if (args[i] is IdentifierExpression)
inferredName = ((IdentifierExpression)args[i]).Identifier;
else if (args[i] is MemberReferenceExpression)
inferredName = ((MemberReferenceExpression)args[i]).MemberName;
else
inferredName = null;
if (i + skip >= parameters.Count || inferredName != parameters[i + skip].Name) {
return false;
}
}
return true;
}
static readonly AstNode objectInitializerPattern = new AssignmentExpression(
new MemberReferenceExpression {
Target = new InitializedObjectExpression(),
MemberName = Pattern.AnyString
}.WithName("left"),
new AnyNode("right")
);
static readonly AstNode collectionInitializerPattern = new InvocationExpression {
Target = new MemberReferenceExpression {
Target = new InitializedObjectExpression(),
MemberName = "Add"
},
Arguments = { new Repeat(new AnyNode("arg")) }
};
sealed class InitializedObjectExpression : IdentifierExpression
{
public InitializedObjectExpression() : base("__initialized_object__") {}
protected override bool DoMatch(AstNode other, Match match)
{
return other is InitializedObjectExpression;
}
}
Expression MakeDefaultValue(TypeSig type)
{
TypeDef typeDef = type.Resolve();
if (typeDef != null) {
if (TypeAnalysis.IsIntegerOrEnum(type))
return AstBuilder.MakePrimitive(0, typeDef);
else if (!DnlibExtensions.IsValueType(typeDef))
return new NullReferenceExpression();
switch (typeDef.FullName) {
case "System.Nullable`1":
return new NullReferenceExpression();
case "System.Single":
return new PrimitiveExpression(0f);
case "System.Double":
return new PrimitiveExpression(0.0);
case "System.Decimal":
return new PrimitiveExpression(0m);
}
}
return new DefaultValueExpression { Type = AstBuilder.ConvertType(type) };
}
AstNode TransformCall(bool isVirtual, ILExpression byteCode, List<Ast.Expression> args)
{
IMethod method = (IMethod)byteCode.Operand;
MethodDef methodDef = method.Resolve();
Ast.Expression target;
List<Ast.Expression> methodArgs = new List<Ast.Expression>(args);
if (method.MethodSig != null && method.MethodSig.HasThis) {
target = methodArgs[0];
methodArgs.RemoveAt(0);
// Unpack any DirectionExpression that is used as target for the call
// (calling methods on value types implicitly passes the first argument by reference)
target = UnpackDirectionExpression(target);
if (methodDef != null) {
// convert null.ToLower() to ((string)null).ToLower()
if (target is NullReferenceExpression)
target = target.CastTo(AstBuilder.ConvertType(method.DeclaringType));
if (methodDef.DeclaringType.IsInterface) {
TypeSig tr = byteCode.Arguments[0].InferredType;
if (tr != null) {
TypeDef td = tr.Resolve();
if (td != null && !td.IsInterface) {
// Calling an interface method on a non-interface object:
// we need to introduce an explicit cast
target = target.CastTo(AstBuilder.ConvertType(method.DeclaringType));
}
}
}
}
} else {
target = new TypeReferenceExpression { Type = AstBuilder.ConvertType(method.DeclaringType) };
}
if (target is ThisReferenceExpression && !isVirtual) {
// a non-virtual call on "this" might be a "base"-call.
if (method.DeclaringType != null && method.DeclaringType.ScopeType.ResolveTypeDef() != this.methodDef.DeclaringType) {
// If we're not calling a method in the current class; we must be calling one in the base class.
target = new BaseReferenceExpression();
target.AddAnnotation(method.DeclaringType);
}
}
if (method.Name == ".ctor" && DnlibExtensions.IsValueType(method.DeclaringType)) {
// On value types, the constructor can be called.
// This is equivalent to 'target = new ValueType(args);'.
ObjectCreateExpression oce = new ObjectCreateExpression();
oce.Type = AstBuilder.ConvertType(method.DeclaringType);
oce.AddAnnotation(method);
AdjustArgumentsForMethodCall(method, methodArgs);
oce.Arguments.AddRange(methodArgs);
return new AssignmentExpression(target, oce);
}
if (method.Name == "Get" && (method.DeclaringType.TryGetArraySig() != null || method.DeclaringType.TryGetSZArraySig() != null) && methodArgs.Count > 1) {
return target.Indexer(methodArgs);
} else if (method.Name == "Set" && (method.DeclaringType.TryGetArraySig() != null || method.DeclaringType.TryGetSZArraySig() != null) && methodArgs.Count > 2) {
return new AssignmentExpression(target.Indexer(methodArgs.GetRange(0, methodArgs.Count - 1)), methodArgs.Last());
}
// Test whether the method is an accessor:
if (methodDef != null) {
if (methodArgs.Count == 0 && methodDef.IsGetter) {
foreach (var prop in methodDef.DeclaringType.Properties) {
if (prop.GetMethod == methodDef)
return target.Member(prop.Name, prop).WithAnnotation(prop).WithAnnotation(method);
}
} else if (methodDef.IsGetter) { // with parameters
PropertyDef indexer = GetIndexer(methodDef);
if (indexer != null)
return target.Indexer(methodArgs).WithAnnotation(indexer).WithAnnotation(method);
} else if (methodArgs.Count == 1 && methodDef.IsSetter) {
foreach (var prop in methodDef.DeclaringType.Properties) {
if (prop.SetMethod == methodDef)
return new Ast.AssignmentExpression(target.Member(prop.Name, prop).WithAnnotation(prop).WithAnnotation(method), methodArgs[0]);
}
} else if (methodArgs.Count > 1 && methodDef.IsSetter) {
PropertyDef indexer = GetIndexer(methodDef);
if (indexer != null)
return new AssignmentExpression(
target.Indexer(methodArgs.GetRange(0, methodArgs.Count - 1)).WithAnnotation(indexer).WithAnnotation(method),
methodArgs[methodArgs.Count - 1]
);
} else if (methodArgs.Count == 1 && methodDef.IsAddOn) {
foreach (var ev in methodDef.DeclaringType.Events) {
if (ev.AddMethod == methodDef) {
return new Ast.AssignmentExpression {
Left = target.Member(ev.Name, ev).WithAnnotation(ev).WithAnnotation(method),
Operator = AssignmentOperatorType.Add,
Right = methodArgs[0]
};
}
}
} else if (methodArgs.Count == 1 && methodDef.IsRemoveOn) {
foreach (var ev in methodDef.DeclaringType.Events) {
if (ev.RemoveMethod == methodDef) {
return new Ast.AssignmentExpression {
Left = target.Member(ev.Name, ev).WithAnnotation(ev).WithAnnotation(method),
Operator = AssignmentOperatorType.Subtract,
Right = methodArgs[0]
};
}
}
} else if (methodDef.Name == "Invoke" && methodDef.DeclaringType.BaseType != null && methodDef.DeclaringType.BaseType.FullName == "System.MulticastDelegate") {
AdjustArgumentsForMethodCall(method, methodArgs);
return target.Invoke(methodArgs).WithAnnotation(method);
}
}
// Default invocation
AdjustArgumentsForMethodCall(methodDef ?? method, methodArgs);
return target.Invoke(methodDef ?? method, method.Name, ConvertTypeArguments(method), methodArgs).WithAnnotation(method);
}
static Expression UnpackDirectionExpression(Expression target)
{
if (target is DirectionExpression) {
return ((DirectionExpression)target).Expression.Detach();
} else {
return target;
}
}
static void AdjustArgumentsForMethodCall(IMethod method, List<Expression> methodArgs)
{
MethodDef methodDef = method.Resolve();
if (methodDef == null)
return;
int skip = methodDef.Parameters.GetParametersSkip();
// Convert 'ref' into 'out' where necessary
for (int i = 0; i < methodArgs.Count && i < methodDef.Parameters.Count - skip; i++) {
DirectionExpression dir = methodArgs[i] as DirectionExpression;
Parameter p = methodDef.Parameters[i + skip];
if (dir != null && p.HasParamDef && p.ParamDef.IsOut && !p.ParamDef.IsIn)
dir.FieldDirection = FieldDirection.Out;
}
}
internal static PropertyDef GetIndexer(MethodDef method)
{
TypeDef typeDef = method.DeclaringType;
string indexerName = null;
foreach (CustomAttribute ca in typeDef.CustomAttributes) {
if (ca.Constructor != null && ca.Constructor.FullName == "System.Void System.Reflection.DefaultMemberAttribute::.ctor(System.String)") {
indexerName = ca.ConstructorArguments.Single().Value as UTF8String;
if (indexerName != null)
break;
}
}
if (indexerName == null)
return null;
foreach (PropertyDef prop in typeDef.Properties) {
if (prop.Name == indexerName) {
if (prop.GetMethod == method || prop.SetMethod == method)
return prop;
}
}
return null;
}
#if DEBUG
static readonly ConcurrentDictionary<ILCode, int> unhandledOpcodes = new ConcurrentDictionary<ILCode, int>();
#endif
[Conditional("DEBUG")]
public static void ClearUnhandledOpcodes()
{
#if DEBUG
unhandledOpcodes.Clear();
#endif
}
[Conditional("DEBUG")]
public static void PrintNumberOfUnhandledOpcodes()
{
#if DEBUG
foreach (var pair in unhandledOpcodes) {
Debug.WriteLine("AddMethodBodyBuilder unhandled opcode: {1}x {0}", pair.Key, pair.Value);
}
#endif
}
static Expression InlineAssembly(ILExpression byteCode, List<Ast.Expression> args)
{
#if DEBUG
unhandledOpcodes.AddOrUpdate(byteCode.Code, c => 1, (c, n) => n+1);
#endif
// Output the operand of the unknown IL code as well
if (byteCode.Operand != null) {
var ie = IdentifierExpression.Create(FormatByteCodeOperand(byteCode.Operand), byteCode.Operand);
ie.IdentifierToken.AddAnnotation(IdentifierFormatted.Instance);
args.Insert(0, ie);
}
return IdentifierExpression.Create(byteCode.Code.GetName(), TextTokenKind.OpCode).Invoke(args);
}
static string FormatByteCodeOperand(object operand)
{
if (operand == null) {
return string.Empty;
//} else if (operand is ILExpression) {
// return string.Format("IL_{0:X2}", ((ILExpression)operand).Offset);
} else if (operand is IMethod && ((IMethod)operand).MethodSig != null) {
return IdentifierEscaper.Escape(((IMethod)operand).Name) + "()";
} else if (operand is ITypeDefOrRef) {
return IdentifierEscaper.Escape(((ITypeDefOrRef)operand).FullName);
} else if (operand is Local) {
return IdentifierEscaper.Escape(((Local)operand).Name);
} else if (operand is Parameter) {
return IdentifierEscaper.Escape(((Parameter)operand).Name);
} else if (operand is IField) {
return IdentifierEscaper.Escape(((IField)operand).Name);
} else if (operand is string) {
return "\"" + Escape((string)operand) + "\"";
} else if (operand is int) {
return operand.ToString();
} else if (operand is MethodSig) {
var msig = (MethodSig)operand;
return Escape(DnlibExtensions.GetMethodSigFullName(msig));
} else {
return Escape(operand.ToString());
}
}
static string Escape(string s)
{
s = s.Replace("\n", @"\u000A");
s = s.Replace("\r", @"\u000D");
return s;
}
IEnumerable<AstType> ConvertTypeArguments(IMethod method)
{
MethodSpec g = method as MethodSpec;
if (g == null || g.GenericInstMethodSig == null)
return null;
if (g.GenericInstMethodSig.GenericArguments.Any(ta => ta.ContainsAnonymousType()))
return null;
return g.GenericInstMethodSig.GenericArguments.Select(t => AstBuilder.ConvertType(t));
}
static Ast.DirectionExpression MakeRef(Ast.Expression expr)
{
return new DirectionExpression { Expression = expr, FieldDirection = FieldDirection.Ref };
}
Ast.Expression Convert(Ast.Expression expr, TypeSig actualType, TypeSig reqType)
{
if (actualType == null || reqType == null || TypeAnalysis.IsSameType(actualType, reqType)) {
return expr;
} else if (actualType is ByRefSig && reqType is PtrSig && expr is DirectionExpression) {
return Convert(
new UnaryOperatorExpression(UnaryOperatorType.AddressOf, ((DirectionExpression)expr).Expression.Detach()),
new PtrSig(((ByRefSig)actualType).Next),
reqType);
} else if (actualType is PtrSig && reqType is ByRefSig) {
expr = Convert(expr, actualType, new PtrSig(((ByRefSig)reqType).Next));
return new DirectionExpression {
FieldDirection = FieldDirection.Ref,
Expression = new UnaryOperatorExpression(UnaryOperatorType.Dereference, expr)
};
} else if (actualType is PtrSig && reqType is PtrSig) {
if (actualType.FullName != reqType.FullName)
return expr.CastTo(AstBuilder.ConvertType(reqType));
else
return expr;
} else {
bool actualIsIntegerOrEnum = TypeAnalysis.IsIntegerOrEnum(actualType);
bool requiredIsIntegerOrEnum = TypeAnalysis.IsIntegerOrEnum(reqType);
if (reqType.GetElementType() == ElementType.Boolean) {
if (actualType.GetElementType() == ElementType.Boolean)
return expr;
if (actualIsIntegerOrEnum) {
return new BinaryOperatorExpression(expr, BinaryOperatorType.InEquality, AstBuilder.MakePrimitive(0, actualType.ToTypeDefOrRef()));
} else {
return new BinaryOperatorExpression(expr, BinaryOperatorType.InEquality, new NullReferenceExpression());
}
}
if (actualType.GetElementType() == ElementType.Boolean && requiredIsIntegerOrEnum) {
return new ConditionalExpression {
Condition = expr,
TrueExpression = AstBuilder.MakePrimitive(1, reqType.ToTypeDefOrRef()),
FalseExpression = AstBuilder.MakePrimitive(0, reqType.ToTypeDefOrRef())
};
}
if (expr is PrimitiveExpression && !requiredIsIntegerOrEnum && TypeAnalysis.IsEnum(actualType))
{
return expr.CastTo(AstBuilder.ConvertType(actualType));
}
bool actualIsPrimitiveType = actualIsIntegerOrEnum
|| actualType.GetElementType() == ElementType.R4 || actualType.GetElementType() == ElementType.R8;
bool requiredIsPrimitiveType = requiredIsIntegerOrEnum
|| reqType.GetElementType() == ElementType.R4 || reqType.GetElementType() == ElementType.R8;
if (actualIsPrimitiveType && requiredIsPrimitiveType) {
return expr.CastTo(AstBuilder.ConvertType(reqType));
}
return expr;
}
}
}
}
| yck1509/dnSpy | ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs | C# | gpl-3.0 | 56,273 |
</div><!-- close .main-content -->
<footer id="colophon" class="site-footer" role="contentinfo" style="padding-top: 20pt; padding-bottom: 40pt;">
<div class="container">
<div class="row">
<div class="col-xs-0 col-sm-3">
</div>
<div class="col-xs-6 col-sm-3">
<h5><a href="https://www.facebook.com/thyspaoxford/">Facebook</a></h5>
<h5><a href="https://www.instagram.com/thy.spa/">Instagram</a></h5>
<h5><a href="https://twitter.com/thyspaoxford">Twitter</a></h5>
<h5>To receive latest news and offers, please <a href="http://eepurl.com/bS2S8j">subscribe</a> to our mailing list.</h5>
</div>
<div class="col-xs-6 col-sm-3">
<h4 class="ts-logo-font ts-capitalize">
<span>Thy</span>
<span>Spa</span>
</h4>
<h5>Original Thai Massage</h5>
<h5><a href="https://www.google.co.uk/maps/place/Thy+Spa/@51.74923,-1.2445757,17z/data=!3m1!4b1!4m5!3m4!1s0x4876c14da21a6c03:0x67617b09ef70e45e!8m2!3d51.74923!4d-1.242387?hl=en" target="_blank">34 Cowley Road, Oxford, OX4 1HZ</a></h5>
<h5>E-mail: <a href="mailto:oxford@thyspa.com">oxford@thyspa.com</a></h5>
<h5>Phone: +44 1865 497999</h5>
<h5>Opening Hours</h5>
<h5>Monday - Saturday | 9:00am - 9:00pm</h5>
<h5>Sunday | 9:00am - 7:00pm</h5>
</div>
<div class="col-xs-0 col-sm-3">
</div>
</div>
</div>
</footer>
<script>
function resizeShedulWidget() {
var height = window.innerHeight - 90;
if (height < 200) height = 200;
d3.select("#shedulWidget").style("height", height + "px");
}
resizeShedulWidget();
window.addEventListener('resize', function(event){
resizeShedulWidget();
});
</script>
<?php wp_footer(); ?>
</body>
</html>
| akuz/thyspa_tk | footer.php | PHP | gpl-3.0 | 1,721 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ultima.Spy.Application
{
/// <summary>
/// Value getter delegate.
/// </summary>
/// <param name="key">Key type.</param>
/// <param name="value">Return value type.</param>
/// <returns>Value.</returns>
public delegate Value SimpleCacheGetter<Key, Value>( Key key );
/// <summary>
/// Describes simple cache.
/// </summary>
/// <typeparam name="Key">Cache key type.</typeparam>
/// <typeparam name="Value">Cache value type.</typeparam>
public class SimpleCache<Key,Value>
{
#region Properties
private Dictionary<Key, Value> _Cache;
private Dictionary<Key, DateTime> _Usage;
private int _CacheSize;
#endregion
#region Events
/// <summary>
/// Value getter for values not in cache.
/// </summary>
public event SimpleCacheGetter<Key,Value> Getter;
#endregion
#region Constructors
/// <summary>
/// Constructs a new instance of SimpleCache.
/// </summary>
/// <param name="cacheSize">Maximum cache size.</param>
public SimpleCache( int cacheSize )
{
_CacheSize = cacheSize;
_Cache = new Dictionary<Key, Value>( cacheSize );
_Usage = new Dictionary<Key, DateTime>( cacheSize );
}
#endregion
#region Methods
/// <summary>
/// Gets value from cache.
/// </summary>
/// <param name="key">Value from cache.</param>
/// <returns>Value.</returns>
public Value Get( Key key )
{
if ( _Cache.ContainsKey( key ) )
{
_Usage[ key ] = DateTime.Now;
return _Cache[ key ];
}
if ( Getter == null )
return default( Value );
if ( _Usage.Count + 1 > _CacheSize )
{
Key minKey = default( Key );
DateTime minTime = DateTime.Now;
foreach ( KeyValuePair<Key, DateTime> kvp in _Usage )
{
if ( kvp.Value < minTime )
{
minKey = kvp.Key;
minTime = kvp.Value;
}
}
_Usage.Remove( minKey );
_Cache.Remove( minKey );
}
Value value = Getter( key );
_Usage.Add( key, DateTime.Now );
_Cache.Add( key, value );
return value;
}
/// <summary>
/// Clears cache.
/// </summary>
public void Clear()
{
_Cache.Clear();
_Usage.Clear();
}
#endregion
}
}
| Vorspire/SpyUO | Ultima.Spy.Application/Helpers/SimpleCache.cs | C# | gpl-3.0 | 2,322 |
<?php
/**
* Ce fichier est développé pour la gestion de la librairie Mélanie2
* Cette Librairie permet d'accèder aux données sans avoir à implémenter de couche SQL
* Des objets génériques vont permettre d'accèder et de mettre à jour les données
*
* ORM M2 Copyright © 2017 PNE Annuaire et Messagerie/MEDDE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace LibMelanie\Ldap;
/**
* Singleton de connexion à l'annuaire
* TODO: n'est plus utile, on la conserve en attendant que les applis passe à la nouvelle utilisation de l'appli ldap
*
* @author PNE Messagerie/Apitech
* @package Librairie Mélanie2
* @subpackage LDAP
*
*/
class LDAPMelanie {
/**
* Constructeur privé pour ne pas instancier la classe
*/
private function __construct() { }
/**
* Athentification sur le serveur LDAP
* @param string $username
* @param string $password
* @return boolean
*/
public static function Authentification ($username, $password) {
return Ldap::Authentification($username, $password);
}
/**
* Return les boites partagées accessible pour un utilisateur depuis le LDAP
* @param string $username
* @return mixed cn mineqmelmailemission uid
*/
public static function GetInformations($username) {
return Ldap::GetUserInfos($username);
}
/**
* Return les informations sur un utilisateur depuis le LDAP
* @param string $username
* @return dn cn mail
*/
public static function GetBalp($username) {
return Ldap::GetUserBalPartagees($username);
}
/**
* Return les informations sur un utilisateur depuis le LDAP
* @param string $username
* @return dn cn mail
*/
public static function GetEmissionBal($username) {
return Ldap::GetUserBalEmission($username);
}
/**
* Return les informations sur un utilisateur depuis son adresse email depuis le LDAP
* @param string $email
* @return dn cn uid
*/
public static function GetInformationsFromMail ($email) {
return Ldap::GetUserInfosFromEmail($email);
}
/**
* Return l'uid de l'utilisateur depuis son adresse email depuis le LDAP
* @param string $email
* @return string $uid
*/
public static function GetUidFromMail($email) {
$infos = Ldap::GetUserInfosFromEmail($email);
if (is_null($infos)) return null;
$ldap = Ldap::GetInstance(\LibMelanie\Config\Ldap::$SEARCH_LDAP);
return isset($infos[$ldap->getMapping('uid')]) ? $infos[$ldap->getMapping('uid')][0] : null;
}
/**
* Return l'email de l'utilisateur depuis son uid depuis le LDAP
* @param string $uid
* @return string $email
*/
public static function GetMailFromUid ($uid) {
$infos = Ldap::GetUserInfos($uid);
if (is_null($infos)) return null;
$ldap = Ldap::GetInstance(\LibMelanie\Config\Ldap::$SEARCH_LDAP);
return $infos[$ldap->getMapping('mail', 'mineqmelmailemission')][0];
}
/**
* Return le nom de l'utilisateur depuis son uid depuis le LDAP
* @param string $uid
* @return string $email
*/
public static function GetNameFromUid ($uid) {
$infos = Ldap::GetUserInfos($uid);
if (is_null($infos)) return null;
$ldap = Ldap::GetInstance(\LibMelanie\Config\Ldap::$SEARCH_LDAP);
return $infos[$ldap->getMapping('cn')][0];
}
}
?> | messagerie-melanie2/ORM-M2 | src/Ldap/LDAPMelanie.php | PHP | gpl-3.0 | 3,788 |
module.exports = {
talkTo: function(player, npc){
// TODO: Dialogues
this.trade(player, npc);
},
trade: function(player, npc){
vendor("Obli's General Store");
}
} | netherfoam/Titan | javascripts/interaction/npc/obli.js | JavaScript | gpl-3.0 | 203 |
#include "MyForm.h"
int main(){
} | jmlb23/desenvolvementoInterfaces | Project1/Project1/MyForm.cpp | C++ | gpl-3.0 | 35 |
<?php
/**
* Piwik - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Tests\Fixtures;
use Piwik\Date;
use Piwik\Tests\Framework\Fixture;
/**
* Adds one site and tracks one visit with several pageviews.
*/
class OneVisitSeveralPageViews extends Fixture
{
public $dateTime = '2010-03-06 11:22:33';
public $idSite = 1;
public function setUp()
{
$this->setUpWebsitesAndGoals();
$this->trackVisits();
}
public function tearDown()
{
// empty
}
private function setUpWebsitesAndGoals()
{
if (!self::siteCreated($idSite = 1)) {
self::createWebsite($this->dateTime);
}
}
private function trackVisits()
{
$dateTime = $this->dateTime;
$idSite = $this->idSite;
$t = self::getTracker($idSite, $dateTime, $defaultInit = true);
$t->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja');
$t->setUrl('http://example.org/%C3%A9%C3%A9%C3%A9%22%27...%20%3Cthis%20is%20cool%3E!');
$t->setGenerationTime(523);
self::checkResponse($t->doTrackPageView('incredible title! <>,;'));
$t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar');
$t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.2)->getDatetime());
$t->setGenerationTime(123);
self::checkResponse($t->doTrackPageView('incredible title! <>,;'));
$t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar2');
$t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.3)->getDatetime());
$t->setGenerationTime(153);
self::checkResponse($t->doTrackPageView('incredible parent title! <>,; / subtitle <>,;'));
$t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar2');
$t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.31)->getDatetime());
$t->setGenerationTime(153);
self::checkResponse($t->doTrackEvent('Category', 'Action', 'Name', 11111));
$t->setUrl('http://example.org/dir2/file.php?foo=bar&foo2=bar');
$t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.4)->getDatetime());
$t->setGenerationTime(1233);
self::checkResponse($t->doTrackPageView('incredible title! <>,;'));
$t->setUrl('http://example.org/dir2/sub/0/file.php');
$t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.4)->getDatetime());
// Very high Generation time should be ignored
$t->setGenerationTime(6350000);
self::checkResponse($t->doTrackPageView('incredible title! <>,;'));
// visit terminal & branch pages w/ the same name so we can test the ! label filter query operator
$t->setUrl('http://example.org/dir/subdir/');
$t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.41)->getDatetime());
$t->setGenerationTime(233);
self::checkResponse($t->doTrackPageView('check <> / @one@ / two'));
$t->setUrl('http://example.org/dir/subdir');
$t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.42)->getDatetime());
$t->setGenerationTime(333);
self::checkResponse($t->doTrackPageView('check <> / @one@'));
$t->setUrl('http://example.org/0');
$t->setForceVisitDateTime(Date::factory($dateTime)->addHour(0.4)->getDatetime());
$t->setGenerationTime(635);
self::checkResponse($t->doTrackPageView('I am URL zero!'));
}
} | piwik/piwik | tests/PHPUnit/Fixtures/OneVisitSeveralPageViews.php | PHP | gpl-3.0 | 3,795 |
using DAL.Interface.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Interface.Repository
{
public interface IRepository<TEntity> where TEntity : IEntity
{
IEnumerable<TEntity> GetAll();
TEntity GetById(int key);
TEntity GetByPredicate(Expression<Func<TEntity, bool>> f);
void Create(TEntity e);
void Delete(TEntity e);
void Update(TEntity entity);
}
}
| p21816/Dasha | EPAM .NET Training/BankSystem/DAL.Interface/Repository/IRepository.cs | C# | gpl-3.0 | 534 |
# -*- coding: utf-8 -*-
#
# This file is part of bd808's stashbot application
# Copyright (C) 2015 Bryan Davis and contributors
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
from .bot import Stashbot
__all__ = (
'Stashbot',
)
any((
Stashbot,
))
| bd808/tools-stashbot | stashbot/__init__.py | Python | gpl-3.0 | 845 |
<?php
namespace VSocial\Google\Auth;
/**
* Signs data.
*
* @author Brian Eaton <beaton@google.com>
*/
abstract class Signer {
/**
* Signs data, returns the signature as binary data.
*/
abstract public function sign ($data);
}
| vikaschaudhary/VSocial | vik-test/vendor/src/VSocial/Google/Auth/Signer.php | PHP | gpl-3.0 | 250 |
#!/usr/bin/env python
import os, sys
sys.path.insert( 0, os.path.dirname( __file__ ) )
from common import delete
try:
assert sys.argv[2]
except IndexError:
print 'usage: %s key url [purge (true/false)] ' % os.path.basename( sys.argv[0] )
sys.exit( 1 )
try:
data = {}
data[ 'purge' ] = sys.argv[3]
except IndexError:
pass
delete( sys.argv[1], sys.argv[2], data )
| mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/scripts/api/history_delete_history.py | Python | gpl-3.0 | 389 |
<?php
require_once 'inc/dbconfig.php';
require_once 'inc/config.php';
require_once 'inc/helper_user.php';
require_once 'inc/user_class.php';
require_once 'inc/eventlog_class.php';
#--------------------------------
function parse_signed_request($signed_request, $secret) {
#--------------------------------
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
#---------------------------------
function base64_url_decode($input) {
#---------------------------------
return base64_decode(strtr($input, '-_', '+/'));
}
#---------------------------------
# M A I N
#---------------------------------
if ($_REQUEST) {
$dbh = dbStart();
$log = new EventLog( );
$response = parse_signed_request($_REQUEST['signed_request'], $GLOBALS['fb_api_secret']);
$log->logSystemDebugEvent( 0, 'RegReq: [' . print_r( $response, TRUE ) . ']' );
$log->logSystemDebugEvent( 0, 'RegReq: Searching for match:['. $response['registration']['email'] . ']' );
$uid = userFindEmail( $response['registration']['email'] );
$log->logSystemDebugEvent( 0, 'found UID:[' . $uid . ']' );
if( $uid ) { # link to an existing user
$user = new User( $dbh, $uid );
#echo '<pre>response:['. print_r($response, true) . ']</pre>';
$user->active( 'Y' );
$user->fb_uid( $response['user_id'] );
$user->fb_auth( $response['oauth_token'] );
$user->fb_auth_expire( $response['expires'] );
$user->save();
$msg = 'Your Facebook login has been linked to an existing FrameAlbum account with the same email address.';
$log->logSystemInfoEvent( $uid, 'FA user:[' . $uid . '] linked to FB UID:[' . $response['user_id'] . ']');
} else {
$user = new User( $dbh, 0, $response['registration']['name'], $response['registration']['email'] );
$user->active( 'Y' );;
$user->fb_uid( $response['user_id'] );
$user->fb_auth( $response['oauth_token'] );
$user->fb_auth_expire( $response['expires'] );
$user->save();
$msg = 'Your FrameAlbum account has been created. Your username is "' . $user->username . "'.";;
$log->logSystemInfoEvent( $uid, 'FB UID:[' . $user->fb_uid() . '] added to FA as [' . $user->username . ']');
}
if (session_id() == '') { session_start(); }
$_SESSION['username'] = $user->username();
$_SESSION['uid'] = $user->iduser();
$_SESSION['useremail'] = $user->email();
$_SESSION['isadmin'] = $user->isAdmin();
$_SESSION['loggedin'] = 'Y';
header('Location:/usermain.php?msg=' . $msg);
} else {
header('Location:/?msg=An error occured during registration.');
}
?>
| StreamingMeeMee/FrameAlbum | html/www/fb/regreq.php | PHP | gpl-3.0 | 3,126 |
/*
Apery, a USI shogi playing engine derived from Stockfish, a UCI chess playing engine.
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2015-2018 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
Copyright (C) 2011-2018 Hiraoka Takuya
Apery is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Apery is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mt64bit.hpp"
//MT64bit g_mt64bit(std::chrono::system_clock::now().time_since_epoch().count());
MT64bit g_mt64bit; // seed が固定値である必要は特に無い。
| HiraokaTakuya/apery | src/mt64bit.cpp | C++ | gpl-3.0 | 1,144 |
import rospy
import time
from collections import deque
class Publisher(object):
def __init__(self):
self.publishers = {}
self.queue = deque()
def add_publisher(self, alias, publisher):
self.publishers[alias] = publisher
def publish(self):
while len(self.queue) > 0:
alias, msg = self.queue.popleft()
print "publishing " + alias + ":" + str(msg)
self.publishers[alias].publish(msg)
def append(self, alias, msg):
self.queue.append((alias, msg))
| jgrizou/robot_omniwheel | catkin_ws/src/roslego/scripts/publisher.py | Python | gpl-3.0 | 541 |
import os, h5py, numpy
from scipy.sparse import csc_matrix
import ml2h5.task
from ml2h5 import VERSION_MLDATA
from ml2h5.converter import ALLOWED_SEPERATORS
class BaseHandler(object):
"""Base handler class.
It is the base for classes to handle different data formats.
It implicitely handles HDF5.
@cvar str_type: string type to be used for variable length strings in h5py
@type str_type: numpy.dtype
@ivar fname: name of file to handle
@type fname: string
@ivar seperator: seperator to seperate variables in examples
@type seperator: string
"""
str_type = h5py.new_vlen(numpy.str)
def __init__(self, fname, seperator=None, compression=None, merge=False):
"""
@param fname: name of in-file
@type fname: string
@param seperator: seperator used to seperate examples
@type seperator: string
"""
self.fname = fname
self.compression = compression
self.set_seperator(seperator)
self.merge = merge
def set_seperator(self, seperator):
"""Set the seperator to seperate variables in examples.
@param seperator: seperator to use
@type seperator: string
"""
if seperator in ALLOWED_SEPERATORS:
self.seperator = seperator
else:
raise AttributeError(_("Seperator '%s' not allowed!" % seperator))
def warn(self, msg):
"""Print a warning message.
@param msg: message to print
@type msg: string
"""
return
print('WARNING: ' + msg)
def _convert_to_ndarray(self,path,val):
"""converts a attribut to a set of ndarrays depending on the datatype
@param path: path of the attribute in the h5 file
@type path: string
@param val: data of the attribute
@type val: csc_matrix/ndarray
@rtype: list of (string,ndarray) tuples
"""
A=val
out=[]
dt = h5py.special_dtype(vlen=str)
if type(A)==csc_matrix: # sparse
out.append((path+'_indices', A.indices))
out.append((path+'_indptr', A.indptr))
out.append((path, A.data))
elif type(A)==list and len(A)>0 and type(A[0])==str:
out.append((path, numpy.array(A, dtype=dt)))
else: # dense
out.append((path, numpy.array(A)))
return out
def get_data_as_list(self,data):
""" this needs to `transpose' the data """
dl=[]
group=self.get_data_group(data)
lengths=dict()
for o in data['ordering']:
x=data[group][o]
#if numpy.issubdtype(x.dtype, numpy.int):
# data[group][o]=x.astype(numpy.float64)
try:
lengths[o]=data[group][o].shape[1]
except (AttributeError, IndexError):
lengths[o]=len(data[group][o])
l=set(lengths.values())
assert(len(l)==1)
l=l.pop()
for i in range(l):
line=[]
for o in data['ordering']:
try:
line.extend(data[group][o][:,i])
except:
line.append(data[group][o][i])
dl.append(line)
return dl
def get_name(self):
"""Get dataset name from non-HDF5 file
@return: comment
@rtype: string
"""
# without str() it might barf
return str(os.path.basename(self.fname).split('.')[0])
def get_data_group(self, data):
if data and 'group' in data:
return data['group']
else:
return 'data'
def get_descr_group(self, data):
if data and 'group' in data:
return data['group'] + '_descr'
else:
return 'data_descr'
def get_datatype(self, values):
"""Get data type of given values.
@param values: list of values to check
@type values: list
@return: data type to use for conversion
@rtype: numpy.int32/numpy.double/self.str_type
"""
dtype = None
for v in values:
if isinstance(v, int):
dtype = numpy.int32
elif isinstance(v, float):
dtype = numpy.double
else: # maybe int/double in string
try:
tmp = int(v)
if not dtype: # a previous nan might set it to double
dtype = numpy.int32
except ValueError:
try:
tmp = float(v)
dtype = numpy.double
except ValueError:
return self.str_type
return dtype
def read(self):
"""Get data and description in-memory
Retrieve contents from file.
@return: example names, ordering and the examples
@rtype: dict of: list of names, list of ordering and dict of examples
"""
# we want the exception handled elsewhere
if not h5py.is_hdf5(self.fname):
return
h5 = h5py.File(self.fname, 'r')
contents = {
'name': h5.attrs['name'],
'comment': h5.attrs['comment'],
'mldata': h5.attrs['mldata'],
}
if contents['comment']=='Task file':
contents['task']=dict()
contents['ordering']=list()
group='task'
for field in ml2h5.task.task_data_fields:
if field in h5[group]:
contents['ordering'].append(field)
else:
contents['data']=dict()
contents['ordering']=h5['/data_descr/ordering'][...].tolist()
group='data'
contents['group']=group
if '/%s_descr/names' % group in h5:
contents['names']=h5['/%s_descr/names' % group][...].tolist()
if '/%s_descr/types' % group in h5:
contents['types'] = h5['/%s_descr/types' % group ][...]
for name in contents['ordering']:
vname='/%s/%s' % (group, name)
sp_indices=vname+'_indices'
sp_indptr=vname+'_indptr'
if sp_indices in h5['/%s' % group] and sp_indptr in h5['/%s' % group]:
contents[group][name] = csc_matrix((h5[vname], h5[sp_indices], h5[sp_indptr])
)
else:
d = numpy.array(h5[vname],order='F')
try:
d=d['vlen']
except:
pass
contents[group][name] = d
h5.close()
return contents
def read_data_as_array(self):
"""Read data from file, and return an array
@return: an array with all data
@rtype: numpy ndarray
"""
contents = self.read()
#group = self.get_data_group(data)
data = contents['data']
ordering = contents['ordering']
if len(data[ordering[0]].shape)>1:
num_examples = data[ordering[0]].shape[1]
else:
num_examples = len(data[ordering[0]])
data_array = numpy.zeros((0, num_examples))
for cur_feat in ordering:
data_array = numpy.vstack([data_array, data[cur_feat]])
return data_array.T
def _get_merged(self, data):
"""Merge given data where appropriate.
String arrays are not merged, but all int and all double are merged
into one matrix.
@param data: data structure as returned by read()
@type data: dict
@return: merged data structure
@rtype: dict
"""
merged = {}
ordering = []
path = ''
idx = 0
merging = None
group = self.get_data_group(data)
for name in data['ordering']:
val = data[group][name]
if type(val) == csc_matrix:
merging = None
path = name
merged[path] = val
ordering.append(path)
continue
if name.endswith('_indices') or name.endswith('_indptr'):
merging = None
path = name
merged[path] = val
continue
if len(val) < 1: continue
t = type(val[0])
if t in [numpy.int32, numpy.int64]:
if merging == 'int':
merged[path].append(val)
else:
merging = 'int'
path = 'int' + str(idx)
ordering.append(path)
merged[path] = [val]
idx += 1
elif t == numpy.double:
if merging == 'double':
merged[path].append(val)
else:
merging = 'double'
path = 'double' + str(idx)
ordering.append(path)
merged[path] = [val]
idx += 1
else: # string or matrix
merging = None
if name.find('/') != -1: # / sep belongs to hdf5 path
path = name.replace('/', '+')
data['ordering'][data['ordering'].index(name)] = path
else:
path = name
ordering.append(path)
merged[path] = val
data[group] = {}
for k in merged:
if len(merged[k])==1:
merged[k] = merged[k][0]
data[group][k] = numpy.array(merged[k])
data['ordering'] = ordering
return data
def write(self, data):
"""Write given data to HDF5 file.
@param data: data to write to HDF5 file.
@type data: dict of lists
"""
# we want the exception handled elsewhere
h5 = h5py.File(self.fname, 'w')
h5.attrs['name'] = data['name']
h5.attrs['mldata'] = VERSION_MLDATA
h5.attrs['comment'] = data['comment']
data_group = self.get_data_group(data)
descr_group = self.get_descr_group(data)
try:
group = h5.create_group('/%s' % data_group)
for path, val in data[data_group].items():
for path, val in self._convert_to_ndarray(path,val):
group.create_dataset(path, data=val, compression=self.compression)
group = h5.create_group('/%s' % descr_group)
names = numpy.array(data['names']).astype(self.str_type)
if names.size > 0: # simple 'if names' throws exception if array
group.create_dataset('names', data=names, compression=self.compression)
ordering = numpy.array(data['ordering']).astype(self.str_type)
if ordering.size > 0:
group.create_dataset('ordering', data=ordering, compression=self.compression)
if 'types' in data:
types = numpy.array(data['types']).astype(self.str_type)
group.create_dataset('types', data=types, compression=self.compression)
except: # just do some clean-up
h5.close()
os.remove(self.fname)
raise
else:
h5.close()
| open-machine-learning/mldata-utils | ml2h5/converter/basehandler.py | Python | gpl-3.0 | 11,241 |
/* Copyright (C) 2013-2014 Alexander Sedov <imp@schat.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QApplication>
#include <QClipboard>
#include <QKeyEvent>
#include <QLineEdit>
#include <QMenu>
#include <QPainter>
#include <QWidgetAction>
#include "ItemColorButton.h"
#include "ItemColorSelector.h"
#include "ItemWidthSelector.h"
#include "WebColorWidget.h"
ItemColorButton::ItemColorButton(QWidget *parent)
: QToolButton(parent)
{
m_selector = new ItemColorSelector(this);
m_webColor = new WebColorWidget(this);
m_widthSelector = new ItemWidthSelector(this);
m_widthSelector->setAdvanced(false);
m_advWidthSelector = new ItemWidthSelector(this);
m_advWidthSelector->setAdvanced(true);
setMenu(new QMenu(this));
menu()->setFocusPolicy(Qt::WheelFocus);
menu()->installEventFilter(this);
add(m_selector);
m_webColorAction = add(m_webColor);
m_widthAction = add(m_widthSelector);
m_advWidthAction = add(m_advWidthSelector);
setPopupMode(InstantPopup);
setColor(0xffd60808);
connect(m_selector, SIGNAL(changed(QRgb)), SLOT(onChanged(QRgb)));
connect(m_selector, SIGNAL(dropperClicked()), SIGNAL(dropperClicked()));
connect(m_selector, SIGNAL(changed(QRgb)), m_webColor, SLOT(setRgb(QRgb)));
connect(m_webColor, SIGNAL(changed(QColor)), SLOT(setColor(QColor)));
connect(m_widthSelector, SIGNAL(changed(int)), SIGNAL(changed(int)));
connect(m_advWidthSelector, SIGNAL(changed(int)), SIGNAL(changed(int)));
connect(menu(), SIGNAL(aboutToShow()), SLOT(onAboutToShow()));
}
bool ItemColorButton::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::KeyPress && static_cast<QKeyEvent*>(event)->matches(QKeySequence::Copy))
QApplication::clipboard()->setText(QColor(m_color).name());
return QToolButton::eventFilter(watched, event);
}
QColor ItemColorButton::customColor() const
{
return m_selector->customColor();
}
void ItemColorButton::setTempColor(const QColor &color)
{
setIcon(pixmap(color));
}
void ItemColorButton::setWidth(int width)
{
m_widthSelector->setWidth(width);
m_widthSelector->setEnabled(width);
m_advWidthSelector->setWidth(width);
m_advWidthSelector->setEnabled(width);
}
void ItemColorButton::setColor(const QColor &color)
{
if (!color.isValid())
return;
setIcon(pixmap(color));
const QRgb rgb = color.rgba();
m_color = rgb;
m_selector->setColor(rgb);
m_widthSelector->setColor(rgb);
m_advWidthSelector->setColor(rgb);
m_webColor->setRgb(rgb);
}
void ItemColorButton::onAboutToShow()
{
const bool advanced = QApplication::keyboardModifiers() == Qt::ShiftModifier;
m_webColorAction->setVisible(advanced);
m_webColor->setVisible(advanced);
m_widthSelector->setVisible(!advanced);
m_widthAction->setVisible(!advanced);
m_advWidthAction->setVisible(advanced);
m_advWidthSelector->setVisible(advanced);
}
void ItemColorButton::onChanged(QRgb color)
{
if (m_color == color)
return;
setColor(color);
emit changed(color);
}
QPixmap ItemColorButton::pixmap(const QColor &color) const
{
QPen pen(color.darker(120));
pen.setWidth(2);
QPainter painter;
QPixmap pix(24, 24);
pix.fill(Qt::transparent);
painter.begin(&pix);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(pen);
painter.setBrush(color);
painter.drawEllipse(QPoint(12, 12), 8, 8);
painter.end();
return pix;
}
QWidgetAction *ItemColorButton::add(QWidget *widget)
{
QWidgetAction *action = new QWidgetAction(this);
action->setDefaultWidget(widget);
menu()->addAction(action);
return action;
}
| impomezia/screenpic | src/editor/ItemColorButton.cpp | C++ | gpl-3.0 | 4,233 |
/*
* A small crossplatform set of file manipulation functions.
* All input/output strings are UTF-8 encoded, even on Windows!
*
* Copyright (c) 2017-2020 Vitaly Novichkov <admin@wohlnet.ru>
*
* 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.
*/
#include "files.h"
#include <stdio.h>
#include <locale>
#ifdef _WIN32
#include <windows.h>
#include <shlwapi.h>
static std::wstring Str2WStr(const std::string &path)
{
std::wstring wpath;
wpath.resize(path.size());
int newlen = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), static_cast<int>(path.length()), &wpath[0], static_cast<int>(path.length()));
wpath.resize(newlen);
return wpath;
}
#else
#include <unistd.h>
#include <fcntl.h> // open
#include <string.h>
#include <sys/stat.h> // fstat
#include <sys/types.h> // fstat
#include <cstdio> // BUFSIZ
#endif
#if defined(__CYGWIN__) || defined(__DJGPP__) || defined(__MINGW32__)
#define IS_PATH_SEPARATOR(c) (((c) == '/') || ((c) == '\\'))
#else
#define IS_PATH_SEPARATOR(c) ((c) == '/')
#endif
static char fi_path_dot[] = ".";
static char fi_path_root[] = "/";
static char *fi_basename(char *s)
{
char *rv;
if(!s || !*s)
return fi_path_dot;
rv = s + strlen(s) - 1;
do
{
if(IS_PATH_SEPARATOR(*rv))
return rv + 1;
--rv;
}
while(rv >= s);
return s;
}
static char *fi_dirname(char *path)
{
char *p;
if(path == NULL || *path == '\0')
return fi_path_dot;
p = path + strlen(path) - 1;
while(IS_PATH_SEPARATOR(*p))
{
if(p == path)
return path;
*p-- = '\0';
}
while(p >= path && !IS_PATH_SEPARATOR(*p))
p--;
if(p < path)
return fi_path_dot;
if(p == path)
return fi_path_root;
*p = '\0';
return path;
}
FILE *Files::utf8_fopen(const char *filePath, const char *modes)
{
#ifndef _WIN32
return ::fopen(filePath, modes);
#else
wchar_t wfile[MAX_PATH + 1];
wchar_t wmode[21];
int wfile_len = (int)strlen(filePath);
int wmode_len = (int)strlen(modes);
wfile_len = MultiByteToWideChar(CP_UTF8, 0, filePath, wfile_len, wfile, MAX_PATH);
wmode_len = MultiByteToWideChar(CP_UTF8, 0, modes, wmode_len, wmode, 20);
wfile[wfile_len] = L'\0';
wmode[wmode_len] = L'\0';
return ::_wfopen(wfile, wmode);
#endif
}
bool Files::fileExists(const std::string &path)
{
#ifdef _WIN32
std::wstring wpath = Str2WStr(path);
return PathFileExistsW(wpath.c_str()) == TRUE;
#else
FILE *ops = fopen(path.c_str(), "rb");
if(ops)
{
fclose(ops);
return true;
}
return false;
#endif
}
bool Files::deleteFile(const std::string &path)
{
#ifdef _WIN32
std::wstring wpath = Str2WStr(path);
return (DeleteFileW(wpath.c_str()) == TRUE);
#else
return ::unlink(path.c_str()) == 0;
#endif
}
bool Files::copyFile(const std::string &to, const std::string &from, bool override)
{
if(!override && fileExists(to))
return false;// Don't override exist target if not requested
bool ret = true;
#ifdef _WIN32
std::wstring wfrom = Str2WStr(from);
std::wstring wto = Str2WStr(to);
ret = (bool)CopyFileW(wfrom.c_str(), wto.c_str(), !override);
#else
char buf[BUFSIZ];
ssize_t size;
ssize_t sizeOut;
int source = open(from.c_str(), O_RDONLY, 0);
if(source == -1)
return false;
int dest = open(to.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0640);
if(dest == -1)
{
close(source);
return false;
}
while((size = read(source, buf, BUFSIZ)) > 0)
{
sizeOut = write(dest, buf, static_cast<size_t>(size));
if(sizeOut != size)
{
ret = false;
break;
}
}
close(source);
close(dest);
#endif
return ret;
}
bool Files::moveFile(const std::string& to, const std::string& from, bool override)
{
bool ret = copyFile(to, from, override);
if(ret)
ret &= deleteFile(from);
return ret;
}
std::string Files::dirname(std::string path)
{
char *p = strdup(path.c_str());
char *d = ::fi_dirname(p);
path = d;
free(p);
return path;
}
std::string Files::basename(std::string path)
{
char *p = strdup(path.c_str());
char *d = ::fi_basename(p);
path = d;
free(p);
return path;
}
std::string Files::basenameNoSuffix(std::string path)
{
char *p = strdup(path.c_str());
char *d = ::fi_basename(p);
path = d;
free(p);
std::string::size_type dot = path.find_last_of('.');
if(dot != std::string::npos)
path.resize(dot);
return path;
}
std::string Files::changeSuffix(std::string path, const std::string &suffix)
{
size_t pos = path.find_last_of('.');// Find dot
if((path.size() < suffix.size()) || (pos == std::string::npos))
path.append(suffix);
else
path.replace(pos, suffix.size(), suffix);
return path;
}
bool Files::hasSuffix(const std::string &path, const std::string &suffix)
{
if(suffix.size() > path.size())
return false;
std::locale loc;
std::string f = path.substr(path.size() - suffix.size(), suffix.size());
for(char &c : f)
c = std::tolower(c, loc);
return (f.compare(suffix) == 0);
}
bool Files::isAbsolute(const std::string& path)
{
bool firstCharIsSlash = (path.size() > 0) ? path[0] == '/' : false;
#ifdef _WIN32
bool containsWinChars = (path.size() > 2) ? (path[1] == ':') && ((path[2] == '\\') || (path[2] == '/')) : false;
if(firstCharIsSlash || containsWinChars)
{
return true;
}
return false;
#else
return firstCharIsSlash;
#endif
}
void Files::getGifMask(std::string& mask, const std::string& front)
{
mask = front;
//Make mask filename
size_t dotPos = mask.find_last_of('.');
if(dotPos == std::string::npos)
mask.push_back('m');
else
mask.insert(mask.begin() + dotPos, 'm');
}
| Wohlstand/PGE-Project | _common/Utils/files.cpp | C++ | gpl-3.0 | 7,052 |
package me.zji.dao;
import me.zji.entity.AdminInfo;
/**
* 管理员信息 Dao
* Created by imyu on 2017/2/23.
*/
public interface AdminInfoDao {
/**
* 创建一条记录
* @param adminInfo
*/
void create(AdminInfo adminInfo);
/**
* 通过用户名删除
* @param username
*/
void deleteByUsername(String username);
/**
* 更新一条记录
* @param adminInfo
*/
void update(AdminInfo adminInfo);
/**
* 通过用户名查找
* @param username
*/
AdminInfo queryByUsername(String username);
}
| gittozji/FundTrade | src/main/java/me/zji/dao/AdminInfoDao.java | Java | gpl-3.0 | 591 |
# coding: utf-8
from __future__ import unicode_literals
import re
from hashlib import sha1
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
ExtractorError,
determine_ext,
float_or_none,
int_or_none,
unified_strdate,
)
class ProSiebenSat1BaseIE(InfoExtractor):
def _extract_video_info(self, url, clip_id):
client_location = url
video = self._download_json(
'http://vas.sim-technik.de/vas/live/v2/videos',
clip_id, 'Downloading videos JSON', query={
'access_token': self._TOKEN,
'client_location': client_location,
'client_name': self._CLIENT_NAME,
'ids': clip_id,
})[0]
if video.get('is_protected') is True:
raise ExtractorError('This video is DRM protected.', expected=True)
duration = float_or_none(video.get('duration'))
source_ids = [compat_str(source['id']) for source in video['sources']]
client_id = self._SALT[:2] + sha1(''.join([clip_id, self._SALT, self._TOKEN, client_location, self._SALT, self._CLIENT_NAME]).encode('utf-8')).hexdigest()
sources = self._download_json(
'http://vas.sim-technik.de/vas/live/v2/videos/%s/sources' % clip_id,
clip_id, 'Downloading sources JSON', query={
'access_token': self._TOKEN,
'client_id': client_id,
'client_location': client_location,
'client_name': self._CLIENT_NAME,
})
server_id = sources['server_id']
def fix_bitrate(bitrate):
bitrate = int_or_none(bitrate)
if not bitrate:
return None
return (bitrate // 1000) if bitrate % 1000 == 0 else bitrate
formats = []
for source_id in source_ids:
client_id = self._SALT[:2] + sha1(''.join([self._SALT, clip_id, self._TOKEN, server_id, client_location, source_id, self._SALT, self._CLIENT_NAME]).encode('utf-8')).hexdigest()
urls = self._download_json(
'http://vas.sim-technik.de/vas/live/v2/videos/%s/sources/url' % clip_id,
clip_id, 'Downloading urls JSON', fatal=False, query={
'access_token': self._TOKEN,
'client_id': client_id,
'client_location': client_location,
'client_name': self._CLIENT_NAME,
'server_id': server_id,
'source_ids': source_id,
})
if not urls:
continue
if urls.get('status_code') != 0:
raise ExtractorError('This video is unavailable', expected=True)
urls_sources = urls['sources']
if isinstance(urls_sources, dict):
urls_sources = urls_sources.values()
for source in urls_sources:
source_url = source.get('url')
if not source_url:
continue
protocol = source.get('protocol')
mimetype = source.get('mimetype')
if mimetype == 'application/f4m+xml' or 'f4mgenerator' in source_url or determine_ext(source_url) == 'f4m':
formats.extend(self._extract_f4m_formats(
source_url, clip_id, f4m_id='hds', fatal=False))
elif mimetype == 'application/x-mpegURL':
formats.extend(self._extract_m3u8_formats(
source_url, clip_id, 'mp4', 'm3u8_native',
m3u8_id='hls', fatal=False))
elif mimetype == 'application/dash+xml':
formats.extend(self._extract_mpd_formats(
source_url, clip_id, mpd_id='dash', fatal=False))
else:
tbr = fix_bitrate(source['bitrate'])
if protocol in ('rtmp', 'rtmpe'):
mobj = re.search(r'^(?P<url>rtmpe?://[^/]+)/(?P<path>.+)$', source_url)
if not mobj:
continue
path = mobj.group('path')
mp4colon_index = path.rfind('mp4:')
app = path[:mp4colon_index]
play_path = path[mp4colon_index:]
formats.append({
'url': '%s/%s' % (mobj.group('url'), app),
'app': app,
'play_path': play_path,
'player_url': 'http://livepassdl.conviva.com/hf/ver/2.79.0.17083/LivePassModuleMain.swf',
'page_url': 'http://www.prosieben.de',
'tbr': tbr,
'ext': 'flv',
'format_id': 'rtmp%s' % ('-%d' % tbr if tbr else ''),
})
else:
formats.append({
'url': source_url,
'tbr': tbr,
'format_id': 'http%s' % ('-%d' % tbr if tbr else ''),
})
self._sort_formats(formats)
return {
'duration': duration,
'formats': formats,
}
class ProSiebenSat1IE(ProSiebenSat1BaseIE):
IE_NAME = 'prosiebensat1'
IE_DESC = 'ProSiebenSat.1 Digital'
_VALID_URL = r'''(?x)
https?://
(?:www\.)?
(?:
(?:
prosieben(?:maxx)?|sixx|sat1(?:gold)?|kabeleins(?:doku)?|the-voice-of-germany|7tv|advopedia
)\.(?:de|at|ch)|
ran\.de|fem\.com|advopedia\.de
)
/(?P<id>.+)
'''
_TESTS = [
{
# Tests changes introduced in https://github.com/rg3/youtube-dl/pull/6242
# in response to fixing https://github.com/rg3/youtube-dl/issues/6215:
# - malformed f4m manifest support
# - proper handling of URLs starting with `https?://` in 2.0 manifests
# - recursive child f4m manifests extraction
'url': 'http://www.prosieben.de/tv/circus-halligalli/videos/218-staffel-2-episode-18-jahresrueckblick-ganze-folge',
'info_dict': {
'id': '2104602',
'ext': 'mp4',
'title': 'Episode 18 - Staffel 2',
'description': 'md5:8733c81b702ea472e069bc48bb658fc1',
'upload_date': '20131231',
'duration': 5845.04,
},
},
{
'url': 'http://www.prosieben.de/videokatalog/Gesellschaft/Leben/Trends/video-Lady-Umstyling-f%C3%BCr-Audrina-Rebekka-Audrina-Fergen-billig-aussehen-Battal-Modica-700544.html',
'info_dict': {
'id': '2570327',
'ext': 'mp4',
'title': 'Lady-Umstyling für Audrina',
'description': 'md5:4c16d0c17a3461a0d43ea4084e96319d',
'upload_date': '20131014',
'duration': 606.76,
},
'params': {
# rtmp download
'skip_download': True,
},
'skip': 'Seems to be broken',
},
{
'url': 'http://www.prosiebenmaxx.de/tv/experience/video/144-countdown-fuer-die-autowerkstatt-ganze-folge',
'info_dict': {
'id': '2429369',
'ext': 'mp4',
'title': 'Countdown für die Autowerkstatt',
'description': 'md5:809fc051a457b5d8666013bc40698817',
'upload_date': '20140223',
'duration': 2595.04,
},
'params': {
# rtmp download
'skip_download': True,
},
'skip': 'This video is unavailable',
},
{
'url': 'http://www.sixx.de/stars-style/video/sexy-laufen-in-ugg-boots-clip',
'info_dict': {
'id': '2904997',
'ext': 'mp4',
'title': 'Sexy laufen in Ugg Boots',
'description': 'md5:edf42b8bd5bc4e5da4db4222c5acb7d6',
'upload_date': '20140122',
'duration': 245.32,
},
'params': {
# rtmp download
'skip_download': True,
},
'skip': 'This video is unavailable',
},
{
'url': 'http://www.sat1.de/film/der-ruecktritt/video/im-interview-kai-wiesinger-clip',
'info_dict': {
'id': '2906572',
'ext': 'mp4',
'title': 'Im Interview: Kai Wiesinger',
'description': 'md5:e4e5370652ec63b95023e914190b4eb9',
'upload_date': '20140203',
'duration': 522.56,
},
'params': {
# rtmp download
'skip_download': True,
},
'skip': 'This video is unavailable',
},
{
'url': 'http://www.kabeleins.de/tv/rosins-restaurants/videos/jagd-auf-fertigkost-im-elsthal-teil-2-ganze-folge',
'info_dict': {
'id': '2992323',
'ext': 'mp4',
'title': 'Jagd auf Fertigkost im Elsthal - Teil 2',
'description': 'md5:2669cde3febe9bce13904f701e774eb6',
'upload_date': '20141014',
'duration': 2410.44,
},
'params': {
# rtmp download
'skip_download': True,
},
'skip': 'This video is unavailable',
},
{
'url': 'http://www.ran.de/fussball/bundesliga/video/schalke-toennies-moechte-raul-zurueck-ganze-folge',
'info_dict': {
'id': '3004256',
'ext': 'mp4',
'title': 'Schalke: Tönnies möchte Raul zurück',
'description': 'md5:4b5b271d9bcde223b54390754c8ece3f',
'upload_date': '20140226',
'duration': 228.96,
},
'params': {
# rtmp download
'skip_download': True,
},
'skip': 'This video is unavailable',
},
{
'url': 'http://www.the-voice-of-germany.de/video/31-andreas-kuemmert-rocket-man-clip',
'info_dict': {
'id': '2572814',
'ext': 'mp4',
'title': 'Andreas Kümmert: Rocket Man',
'description': 'md5:6ddb02b0781c6adf778afea606652e38',
'upload_date': '20131017',
'duration': 469.88,
},
'params': {
'skip_download': True,
},
},
{
'url': 'http://www.fem.com/wellness/videos/wellness-video-clip-kurztripps-zum-valentinstag.html',
'info_dict': {
'id': '2156342',
'ext': 'mp4',
'title': 'Kurztrips zum Valentinstag',
'description': 'Romantischer Kurztrip zum Valentinstag? Nina Heinemann verrät, was sich hier wirklich lohnt.',
'duration': 307.24,
},
'params': {
'skip_download': True,
},
},
{
'url': 'http://www.prosieben.de/tv/joko-gegen-klaas/videos/playlists/episode-8-ganze-folge-playlist',
'info_dict': {
'id': '439664',
'title': 'Episode 8 - Ganze Folge - Playlist',
'description': 'md5:63b8963e71f481782aeea877658dec84',
},
'playlist_count': 2,
'skip': 'This video is unavailable',
},
{
'url': 'http://www.7tv.de/circus-halligalli/615-best-of-circus-halligalli-ganze-folge',
'info_dict': {
'id': '4187506',
'ext': 'mp4',
'title': 'Best of Circus HalliGalli',
'description': 'md5:8849752efd90b9772c9db6fdf87fb9e9',
'upload_date': '20151229',
},
'params': {
'skip_download': True,
},
},
{
# geo restricted to Germany
'url': 'http://www.kabeleinsdoku.de/tv/mayday-alarm-im-cockpit/video/102-notlandung-im-hudson-river-ganze-folge',
'only_matching': True,
},
{
# geo restricted to Germany
'url': 'http://www.sat1gold.de/tv/edel-starck/video/11-staffel-1-episode-1-partner-wider-willen-ganze-folge',
'only_matching': True,
},
{
'url': 'http://www.sat1gold.de/tv/edel-starck/playlist/die-gesamte-1-staffel',
'only_matching': True,
},
{
'url': 'http://www.advopedia.de/videos/lenssen-klaert-auf/lenssen-klaert-auf-folge-8-staffel-3-feiertage-und-freie-tage',
'only_matching': True,
},
]
_TOKEN = 'prosieben'
_SALT = '01!8d8F_)r9]4s[qeuXfP%'
_CLIENT_NAME = 'kolibri-2.0.19-splec4'
_CLIPID_REGEXES = [
r'"clip_id"\s*:\s+"(\d+)"',
r'clipid: "(\d+)"',
r'clip[iI]d=(\d+)',
r'clip[iI]d\s*=\s*["\'](\d+)',
r"'itemImageUrl'\s*:\s*'/dynamic/thumbnails/full/\d+/(\d+)",
]
_TITLE_REGEXES = [
r'<h2 class="subtitle" itemprop="name">\s*(.+?)</h2>',
r'<header class="clearfix">\s*<h3>(.+?)</h3>',
r'<!-- start video -->\s*<h1>(.+?)</h1>',
r'<h1 class="att-name">\s*(.+?)</h1>',
r'<header class="module_header">\s*<h2>([^<]+)</h2>\s*</header>',
r'<h2 class="video-title" itemprop="name">\s*(.+?)</h2>',
r'<div[^>]+id="veeseoTitle"[^>]*>(.+?)</div>',
]
_DESCRIPTION_REGEXES = [
r'<p itemprop="description">\s*(.+?)</p>',
r'<div class="videoDecription">\s*<p><strong>Beschreibung</strong>: (.+?)</p>',
r'<div class="g-plusone" data-size="medium"></div>\s*</div>\s*</header>\s*(.+?)\s*<footer>',
r'<p class="att-description">\s*(.+?)\s*</p>',
r'<p class="video-description" itemprop="description">\s*(.+?)</p>',
r'<div[^>]+id="veeseoDescription"[^>]*>(.+?)</div>',
]
_UPLOAD_DATE_REGEXES = [
r'<meta property="og:published_time" content="(.+?)">',
r'<span>\s*(\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}) \|\s*<span itemprop="duration"',
r'<footer>\s*(\d{2}\.\d{2}\.\d{4}) \d{2}:\d{2} Uhr',
r'<span style="padding-left: 4px;line-height:20px; color:#404040">(\d{2}\.\d{2}\.\d{4})</span>',
r'(\d{2}\.\d{2}\.\d{4}) \| \d{2}:\d{2} Min<br/>',
]
_PAGE_TYPE_REGEXES = [
r'<meta name="page_type" content="([^"]+)">',
r"'itemType'\s*:\s*'([^']*)'",
]
_PLAYLIST_ID_REGEXES = [
r'content[iI]d=(\d+)',
r"'itemId'\s*:\s*'([^']*)'",
]
_PLAYLIST_CLIP_REGEXES = [
r'(?s)data-qvt=.+?<a href="([^"]+)"',
]
def _extract_clip(self, url, webpage):
clip_id = self._html_search_regex(
self._CLIPID_REGEXES, webpage, 'clip id')
title = self._html_search_regex(self._TITLE_REGEXES, webpage, 'title')
info = self._extract_video_info(url, clip_id)
description = self._html_search_regex(
self._DESCRIPTION_REGEXES, webpage, 'description', default=None)
if description is None:
description = self._og_search_description(webpage)
thumbnail = self._og_search_thumbnail(webpage)
upload_date = unified_strdate(self._html_search_regex(
self._UPLOAD_DATE_REGEXES, webpage, 'upload date', default=None))
info.update({
'id': clip_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'upload_date': upload_date,
})
return info
def _extract_playlist(self, url, webpage):
playlist_id = self._html_search_regex(
self._PLAYLIST_ID_REGEXES, webpage, 'playlist id')
playlist = self._parse_json(
self._search_regex(
r'var\s+contentResources\s*=\s*(\[.+?\]);\s*</script',
webpage, 'playlist'),
playlist_id)
entries = []
for item in playlist:
clip_id = item.get('id') or item.get('upc')
if not clip_id:
continue
info = self._extract_video_info(url, clip_id)
info.update({
'id': clip_id,
'title': item.get('title') or item.get('teaser', {}).get('headline'),
'description': item.get('teaser', {}).get('description'),
'thumbnail': item.get('poster'),
'duration': float_or_none(item.get('duration')),
'series': item.get('tvShowTitle'),
'uploader': item.get('broadcastPublisher'),
})
entries.append(info)
return self.playlist_result(entries, playlist_id)
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
page_type = self._search_regex(
self._PAGE_TYPE_REGEXES, webpage,
'page type', default='clip').lower()
if page_type == 'clip':
return self._extract_clip(url, webpage)
elif page_type == 'playlist':
return self._extract_playlist(url, webpage)
else:
raise ExtractorError(
'Unsupported page type %s' % page_type, expected=True)
| Dunkas12/BeepBoopBot | lib/youtube_dl/extractor/prosiebensat1.py | Python | gpl-3.0 | 17,726 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.task;
import org.openconcerto.sql.users.UserManager;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TodoListElementEditorPanel extends JPanel {
private transient TodoListElement element;
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy à HH:mm");
TodoListElementEditorPanel(TodoListElement e) {
this.element = e;
System.out.println(e);
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2, 2, 2, 2);
c.fill = GridBagConstraints.HORIZONTAL;
// Ligne 1 =====================================
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
JLabel l = new JLabel("Résumé:");
this.add(l, c);
//
c.gridx++;
c.weightx = 1;
final JTextField f = new JTextField();
f.setText(e.getName());
this.add(f, c);
// Ligne 1 bis =====================================
c.gridwidth = 2;
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
c.insets = new Insets(0, 0, 0, 0);
this.add(new JSeparator(JSeparator.HORIZONTAL), c);
// Ligne 2 =====================================
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
final JTextArea fComment = new JTextArea();
fComment.setFont(f.getFont());
fComment.setText(e.getComment());
this.add(fComment, c);
// Ligne 2 bis =====================================
c.gridwidth = 2;
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
c.weighty = 0;
this.add(new JSeparator(JSeparator.HORIZONTAL), c);
// Ligne 3 =====================================
c.gridx = 0;
c.gridy++;
c.weighty = 0;
c.gridwidth = 2;
c.insets = new Insets(2, 2, 2, 2);
c.fill = GridBagConstraints.HORIZONTAL;
JLabel label = new JLabel("A réaliser pour le " + simpleDateFormat.format(e.getExpectedDate()) + " par " + UserManager.getInstance().getUser(e.getUserId()).getFullName());
this.add(label, c);
// Ligne 4 =====================================
JButton bOk = new JButton("Ok");
bOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
element.setName(f.getText());
element.setComment(fComment.getText());
element.commitChanges();
SwingUtilities.getWindowAncestor(TodoListElementEditorPanel.this).dispose();
}
});
JButton bAnnuler = new JButton("Annuler");
bAnnuler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
SwingUtilities.getWindowAncestor(TodoListElementEditorPanel.this).dispose();
}
});
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.add(bOk);
p.add(bAnnuler);
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
this.add(p, c);
}
}
| eric-lemesre/OpenConcerto | OpenConcerto/src/org/openconcerto/task/TodoListElementEditorPanel.java | Java | gpl-3.0 | 4,376 |
<?php
/**
* The template for displaying Archive pages.
*
* Used to display archive-type pages if nothing more specific matches a query.
* For example, puts together date-based pages if no date.php file exists.
*
* If you'd like to further customize these archive views, you may create a
* new template file for each specific one. For example, Quasar Theme
* already has tag.php for Tag archives, category.php for Category archives,
* and author.php for Author archives.
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage Quasar Theme
* @since Quasar Theme 1.0
*/
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php if ( have_posts() ) : ?>
<header class="archive-header">
<h1 class="archive-title"><?php
if ( is_day() ) :
printf( __( 'Daily Archives: %s', 'quasartheme' ), get_the_date() );
elseif ( is_month() ) :
printf( __( 'Monthly Archives: %s', 'quasartheme' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'quasartheme' ) ) );
elseif ( is_year() ) :
printf( __( 'Yearly Archives: %s', 'quasartheme' ), get_the_date( _x( 'Y', 'yearly archives date format', 'quasartheme' ) ) );
else :
_e( 'Archives', 'quasartheme' );
endif;
?></h1>
</header><!-- .archive-header -->
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php quasartheme_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?> | peeyarmenon/quasar-theme-framework | archive.php | PHP | gpl-3.0 | 1,773 |
//
// PostShowPage.xaml.cpp
// Implementation of the PostShowPage class
//
#include "pch.h"
#include "PostShowPage.xaml.h"
#include "PostPage.xaml.h"
#include "LoginPage.xaml.h"
#include "define.h"
using namespace GhostBlogClient;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Popups;
using namespace concurrency;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556
PostShowPage::PostShowPage()
{
InitializeComponent();
SetValue(_defaultViewModelProperty, ref new Platform::Collections::Map<String^, Object^>(std::less<String^>()));
auto navigationHelper = ref new Common::NavigationHelper(this);
SetValue(_navigationHelperProperty, navigationHelper);
navigationHelper->LoadState += ref new Common::LoadStateEventHandler(this, &PostShowPage::LoadState);
navigationHelper->SaveState += ref new Common::SaveStateEventHandler(this, &PostShowPage::SaveState);
}
DependencyProperty^ PostShowPage::_defaultViewModelProperty =
DependencyProperty::Register("DefaultViewModel",
TypeName(IObservableMap<String^, Object^>::typeid), TypeName(PostShowPage::typeid), nullptr);
/// <summary>
/// Used as a trivial view model.
/// </summary>
IObservableMap<String^, Object^>^ PostShowPage::DefaultViewModel::get()
{
return safe_cast<IObservableMap<String^, Object^>^>(GetValue(_defaultViewModelProperty));
}
DependencyProperty^ PostShowPage::_navigationHelperProperty =
DependencyProperty::Register("NavigationHelper",
TypeName(Common::NavigationHelper::typeid), TypeName(PostShowPage::typeid), nullptr);
/// <summary>
/// Gets an implementation of <see cref="NavigationHelper"/> designed to be
/// used as a trivial view model.
/// </summary>
Common::NavigationHelper^ PostShowPage::NavigationHelper::get()
{
return safe_cast<Common::NavigationHelper^>(GetValue(_navigationHelperProperty));
}
#pragma region Navigation support
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="NavigationHelper::LoadState"/>
/// and <see cref="NavigationHelper::SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
void PostShowPage::OnNavigatedTo(NavigationEventArgs^ e)
{
NavigationHelper->OnNavigatedTo(e);
}
void PostShowPage::OnNavigatedFrom(NavigationEventArgs^ e)
{
NavigationHelper->OnNavigatedFrom(e);
}
#pragma endregion
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
void PostShowPage::LoadState(Object^ sender, Common::LoadStateEventArgs^ e)
{
(void) sender; // Unused parameter
(void) e; // Unused parameter
if (e != nullptr && e->NavigationParameter != nullptr) {
blogAll = safe_cast<BlogAll^>(e->NavigationParameter);
ghostClient = blogAll->GhostClient;
currentPost = blogAll->ShowPost;
StartWaiting();
create_task(blogAll->FormatPostToHtml(currentPost))
.then([this](String^ html)
{
PostShowWebView->NavigateToString(html);
FinishWaiting();
});
}
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager::SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
void PostShowPage::SaveState(Object^ sender, Common::SaveStateEventArgs^ e){
(void) sender; // Unused parameter
(void) e; // Unused parameter
}
void PostShowPage::StartWaiting()
{
PostShowCommandBar->IsEnabled = false;
}
void PostShowPage::FinishWaiting()
{
PostShowCommandBar->IsEnabled = true;
}
void PostShowPage::PostShowDeleteButtonClick(Object^ sender, RoutedEventArgs^ e)
{
SubmitDeleteRequest(false, currentPost->Id);
}
void PostShowPage::SubmitDeleteRequest(bool needRefresh, int postId)
{
StartWaiting();
IAsyncOperation<Boolean>^ bOpe;
if (needRefresh) {
bOpe = ghostClient->RefreshAuthToken();
}
else {
bOpe = blogAll->GetBooleanAsyncOperation();
}
create_task(bOpe)
.then([=](Boolean resp)
{
return ghostClient->DeletePost(postId);
}).then([this](PostInfo^ p)
{
blogAll->DeletePost(currentPost);
auto dialog = ref new MessageDialog("删除成功");
return dialog->ShowAsync();
}).then([=](IUICommand^ resp) {
this->FinishWaiting();
NavigationHelper->GoBack();
}).then([=](task<void> prevTask) {
try
{
prevTask.get();
}
catch (Exception ^ex)
{
if (ghostClient->ErrorMsg->ErrorKind == GHOST_AUTH_ERROR)
{
if (!needRefresh) {
this->SubmitDeleteRequest(true, postId);
return;
}
else {
// 需要重新登录
this->FinishWaiting();
this->NeedReLogin();
return;
}
}
this->FinishWaiting();
String^ errMsg = ghostClient->ErrorMsg->GetErrorMessge(ex);
auto dialog = ref new MessageDialog(errMsg, "删除失败");
dialog->ShowAsync();
}
});
}
void PostShowPage::PostShowEditButtonClick(Object^ sender, RoutedEventArgs^ e)
{
if (blogAll->EditPost == nullptr) {
blogAll->EditPost = ref new PostInfo;
}
blogAll->EditPost->SetData(blogAll->ShowPost);
this->Frame->Navigate(TypeName(PostPage::typeid), blogAll);
}
void PostShowPage::SubmitRefreshRequest(bool needRefresh, int postId)
{
IAsyncOperation<Boolean>^ bOpe;
if (!needRefresh) {
StartWaiting();
bOpe = blogAll->GetBooleanAsyncOperation();
}
else {
bOpe = ghostClient->RefreshAuthToken();
}
create_task(bOpe)
.then([=](Boolean resp)
{
return ghostClient->GetPost(postId);
}).then([this](PostInfo^ p)
{
blogAll->AddPost(p, false);
blogAll->ShowPost = p;
currentPost = p;
return blogAll->FormatPostToHtml(p);
}).then([this](String^ html)
{
PostShowWebView->NavigateToString(html);
FinishWaiting();
}).then([=](task<void> prevTask) {
try
{
prevTask.get();
}
catch (Exception ^ex)
{
if (ghostClient->ErrorMsg->ErrorKind == GHOST_AUTH_ERROR)
{
if (!needRefresh) {
this->SubmitDeleteRequest(true, postId);
return;
}
else {
// 需要重新登录
this->FinishWaiting();
this->NeedReLogin();
return;
}
}
this->FinishWaiting();
String^ errMsg = ghostClient->ErrorMsg->GetErrorMessge(ex);
auto dialog = ref new MessageDialog(errMsg, "刷新失败");
dialog->ShowAsync();
}
});
}
void PostShowPage::PostShowRefreshButtonClick(Object^ sender, RoutedEventArgs^ e)
{
SubmitRefreshRequest(false, currentPost->Id);
}
void PostShowPage::NeedReLogin()
{
auto dialog = ref new MessageDialog("操作失败,Token 过时,需要重新登陆");
create_task(dialog->ShowAsync())
.then([this](IUICommand^ resp)
{
blogAll->OnlyLogin = true;
if (this->Frame != nullptr)
{
this->Frame->Navigate(TypeName(LoginPage::typeid), blogAll);
}
}).then([=](task<void> prevTask) {
try
{
prevTask.get();
}
catch (Exception ^ex)
{
}
});
} | padicao2010/Ghost-Client-for-WP | GhostBlogClient/GhostBlogClient.WindowsPhone/PostShowPage.xaml.cpp | C++ | gpl-3.0 | 8,225 |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
from random import *
import numpy
import pdb
import cPickle
import bz2
import sys
import pylab
import nupic.bindings.algorithms as algo
from nupic.bindings.math import GetNumpyDataType
type = GetNumpyDataType('NTA_Real')
type = 'float32'
#--------------------------------------------------------------------------------
# Simple use case
#--------------------------------------------------------------------------------
def simple():
print "Simple"
numpy.random.seed(42)
n_dims = 2
n_class = 4
size = 200
labels = numpy.random.random_integers(0, n_class-1, size)
samples = numpy.zeros((size, n_dims), dtype=type)
do_plot = False
print "Generating data"
centers = numpy.array([[0,0],[0,1],[1,0],[1,1]])
for i in range(0, size):
t = 6.28 * numpy.random.random_sample()
samples[i][0] = 2 * centers[labels[i]][0] + .5*numpy.random.random() * numpy.cos(t)
samples[i][1] = 2 * centers[labels[i]][1] + .5*numpy.random.random() * numpy.sin(t)
classifier = algo.svm_dense(0, n_dims, probability=True, seed=42)
print "Adding sample vectors"
for y, x_list in zip(labels, samples):
x = numpy.array(x_list, dtype=type)
classifier.add_sample(float(y), x)
print "Displaying problem"
problem = classifier.get_problem()
print "Problem size:", problem.size()
print "Problem dimensionality:", problem.n_dims()
print "Problem samples:"
s = numpy.zeros((problem.size(), problem.n_dims()+1), dtype=type)
problem.get_samples(s)
print s
if do_plot:
pylab.ion()
pylab.plot(s[s[:,0]==0,1], s[s[:,0]==0,2], '.', color='r')
pylab.plot(s[s[:,0]==1,1], s[s[:,0]==1,2], '+', color='b')
pylab.plot(s[s[:,0]==2,1], s[s[:,0]==2,2], '^', color='g')
pylab.plot(s[s[:,0]==3,1], s[s[:,0]==3,2], 'v', color='g')
print "Training"
classifier.train(gamma = 1./3., C = 100, eps=1e-1)
print "Displaying model"
model = classifier.get_model()
print "Number of support vectors:", model.size()
print "Number of classes:", model.n_class()
print "Number of dimensions: ", model.n_dims()
print "Support vectors:"
sv = numpy.zeros((model.size(), model.n_dims()), dtype=type)
model.get_support_vectors(sv)
print sv
if do_plot:
pylab.plot(sv[:,0], sv[:,1], 'o', color='g')
print "Support vector coefficients:"
svc = numpy.zeros((model.n_class()-1, model.size()), dtype=type)
model.get_support_vector_coefficients(svc)
print svc
print "Hyperplanes (for linear kernel only):"
h = model.get_hyperplanes()
print h
if do_plot:
xmin = numpy.min(samples[:,0])
xmax = numpy.max(samples[:,0])
xstep = (xmax - xmin) / 10
X = numpy.arange(xmin, xmax, xstep)
ymin = numpy.min(samples[:,1])
ymax = numpy.max(samples[:,1])
ystep = (ymax - ymin) / 10
Y = numpy.arange(ymin, ymax, ystep)
points = numpy.zeros((len(X), len(Y)))
for i,x in enumerate(X):
for j,y in enumerate(Y):
proba = numpy.zeros(model.n_class(), dtype=type)
classifier.predict_probability(numpy.array([x,y]), proba)
points[i,j] = proba[0]
pylab.contour(X,Y,points)
print "Cross-validation"
print classifier.cross_validate(2, gamma = .5, C = 10, eps = 1e-3)
print "Predicting"
for y, x_list in zip(labels, samples):
x = numpy.array(x_list, dtype=type)
proba = numpy.zeros(model.n_class(), dtype=type)
print x, ': real=', y,
print 'p1=', classifier.predict(x),
print 'p2=', classifier.predict_probability(x, proba),
print 'proba=', proba
print "Discarding problem"
classifier.discard_problem()
print "Predicting after discarding the problem"
for y, x_list in zip(labels, samples):
x = numpy.array(x_list, dtype=type)
proba = numpy.zeros(model.n_class(), dtype=type)
print x, ': real=', y,
print 'p1=', classifier.predict(x),
print 'p2=', classifier.predict_probability(x, proba),
print 'proba=', proba
#--------------------------------------------------------------------------------
# Persistence
#--------------------------------------------------------------------------------
def persistence():
print "Persistence"
numpy.random.seed(42)
n_dims = 2
n_class = 12
size = 100
labels = numpy.random.random_integers(0, 256, size)
samples = numpy.zeros((size, n_dims), dtype=type)
print "Generating data"
for i in range(0, size):
t = 6.28 * numpy.random.random_sample()
samples[i][0] = 2 * labels[i] + 1.5 * numpy.cos(t)
samples[i][1] = 2 * labels[i] + 1.5 * numpy.sin(t)
print "Creating dense classifier"
classifier = algo.svm_dense(0, n_dims = n_dims, seed=42)
print "Adding sample vectors to dense classifier"
for y, x_list in zip(labels, samples):
x = numpy.array(x_list, dtype=type)
classifier.add_sample(float(y), x)
print "Pickling dense classifier"
cPickle.dump(classifier, open('test', 'wb'))
classifier = cPickle.load(open('test', 'rb'))
print "Training dense classifier"
classifier.train(gamma = 1, C = 10, eps=1e-1)
print "Predicting with dense classifier"
print classifier.predict(samples[0])
print "Creating 0/1 classifier"
classifier01 = algo.svm_01(n_dims = n_dims, seed=42)
print "Adding sample vectors to 0/1 classifier"
for y, x_list in zip(labels, samples):
x = numpy.array(x_list, dtype=type)
classifier01.add_sample(float(y), x)
print "Training 0/1 classifier"
classifier01.train(gamma = 1./3., C = 100, eps=1e-1)
print "Pickling 0/1 classifier"
cPickle.dump(classifier01, open('test', 'wb'))
classifier01 = cPickle.load(open('test', 'rb'))
print "Predicting with 0/1 classifier"
print classifier01.predict(numpy.array(samples[0], dtype=type))
#--------------------------------------------------------------------------------
# Cross validation
#--------------------------------------------------------------------------------
def cross_validation():
return
print "Cross validation"
numpy.random.seed(42)
labels = [0, 1, 1, 2, 1, 2]
samples = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1], [1, 1, 0], [0, 1, 1]]
classifier = algo.svm_dense(0, n_dims = 3, seed=42)
print "Adding sample vectors"
for y, x_list in zip(labels, samples):
x = numpy.array(x_list, dtype=type)
classifier.add_sample(float(y), x)
cPickle.dump(classifier, open('test', 'wb'))
classifier = cPickle.load(open('test', 'rb'))
print "Training"
classifier.train(gamma = 1./3., C = 100, eps=1e-1)
print "Cross validation =",
print classifier.cross_validate(3, gamma = .5, C = 10, eps = 1e-3)
#--------------------------------------------------------------------------------
simple()
persistence()
cross_validation()
| tkaitchuck/nupic | examples/bindings/svm_how_to.py | Python | gpl-3.0 | 8,034 |
from cantilever_divingboard import *
# We need to scale the parameters before applying the optimization algorithm
# Normally there are about 20 orders of magnitude between the dimensions and
# the doping concentration, so this is a critical step
# Run the script
freq_min = 1e3
freq_max = 1e5
omega_min = 100e3
initial_guess = (50e-6, 1e-6, 1e-6,
30e-6, 1e-6, 1e-6, 500e-9, 5., 1e15)
constraints = ((30e-6, 100e-6), (500e-9, 20e-6), (1e-6, 10e-6),
(2e-6, 100e-6), (500e-9, 5e-6), (500e-9, 20e-6), (30e-9, 10e-6),
(1., 10.), (1e15, 4e19))
x = optimize_cantilever(initial_guess, constraints, freq_min, freq_max, omega_min)
c = cantilever_divingboard(freq_min, freq_max, x)
c.print_performance() | jcdoll/PiezoD | python/archive/lbfgs.py | Python | gpl-3.0 | 752 |
enyo.kind({
name: "Remote.Movies",
kind: "VFlexBox",
events: {
onPlay: "",
},
components: [
{kind: "PageHeader", components: [
{name: "headerText", kind: enyo.VFlexBox,
content: "", flex: 1
},
{name: "backButton", kind: "Button", content: "Back",
onclick: "goBack"
}
]},
{name: "pane", kind: "Pane", flex: 1, components: [
{name: "movies", className: "enyo-bg", kind: "Remote.MovieList",
onSelect: "selectMovie"
},
]},
],
update: function() {
this.$.pane.view.update();
},
selectMovie: function(inSender, inMovie) {
this.doPlay(inMovie.id);
},
});
| jerrykan/webos-xbmcremote | source/Movies.js | JavaScript | gpl-3.0 | 770 |
/*
* Copyright (C) 2014 Alfons Wirtz
* website www.freerouting.net
*
* Copyright (C) 2017 Michael Hoffer <info@michaelhoffer.de>
* Website www.freerouting.mihosoft.eu
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License at <http://www.gnu.org/licenses/>
* for more details.
*
* LocateFoundConnectionAlgo.java
*
* Created on 31. Januar 2006, 08:20
*
*/
package eu.mihosoft.freerouting.autoroute;
import java.util.Collection;
import java.util.SortedSet;
import java.util.LinkedList;
import java.util.Iterator;
import eu.mihosoft.freerouting.geometry.planar.IntPoint;
import eu.mihosoft.freerouting.geometry.planar.FloatPoint;
import eu.mihosoft.freerouting.geometry.planar.TileShape;
import eu.mihosoft.freerouting.board.Connectable;
import eu.mihosoft.freerouting.board.Item;
import eu.mihosoft.freerouting.board.AngleRestriction;
import eu.mihosoft.freerouting.board.ShapeSearchTree;
import eu.mihosoft.freerouting.board.TestLevel;
/**
*
* @author Alfons Wirtz
*/
public abstract class LocateFoundConnectionAlgo
{
/**
* Returns a new Instance of LocateFoundConnectionAlgo or null,
* if p_destination_door is null.
*/
public static LocateFoundConnectionAlgo get_instance(MazeSearchAlgo.Result p_maze_search_result, AutorouteControl p_ctrl,
ShapeSearchTree p_search_tree, AngleRestriction p_angle_restriction, SortedSet<Item> p_ripped_item_list, TestLevel p_test_level)
{
if (p_maze_search_result == null)
{
return null;
}
LocateFoundConnectionAlgo result;
if (p_angle_restriction == AngleRestriction.NINETY_DEGREE || p_angle_restriction == AngleRestriction.FORTYFIVE_DEGREE)
{
result = new LocateFoundConnectionAlgo45Degree(p_maze_search_result, p_ctrl, p_search_tree, p_angle_restriction,
p_ripped_item_list, p_test_level);
}
else
{
result = new LocateFoundConnectionAlgoAnyAngle(p_maze_search_result, p_ctrl, p_search_tree, p_angle_restriction,
p_ripped_item_list, p_test_level);
}
return result;
}
/** Creates a new instance of LocateFoundConnectionAlgo */
protected LocateFoundConnectionAlgo(MazeSearchAlgo.Result p_maze_search_result, AutorouteControl p_ctrl,
ShapeSearchTree p_search_tree, AngleRestriction p_angle_restriction, SortedSet<Item> p_ripped_item_list, TestLevel p_test_level)
{
this.ctrl = p_ctrl;
this.angle_restriction = p_angle_restriction;
this.test_level = p_test_level;
Collection<BacktrackElement> backtrack_list = backtrack(p_maze_search_result, p_ripped_item_list);
this.backtrack_array = new BacktrackElement[backtrack_list.size()];
Iterator<BacktrackElement> it = backtrack_list.iterator();
for (int i = 0; i < backtrack_array.length; ++i)
{
this.backtrack_array[i] = it.next();
}
this.connection_items = new LinkedList<ResultItem>();
BacktrackElement start_info = this.backtrack_array[backtrack_array.length - 1];
if (!(start_info.door instanceof TargetItemExpansionDoor))
{
System.out.println("LocateFoundConnectionAlgo: ItemExpansionDoor expected for start_info.door");
this.start_item = null;
this.start_layer = 0;
this.target_item = null;
this.target_layer = 0;
this.start_door = null;
return;
}
this.start_door = (TargetItemExpansionDoor) start_info.door;
this.start_item = start_door.item;
this.start_layer = start_door.room.get_layer();
this.current_from_door_index = 0;
boolean at_fanout_end = false;
if (p_maze_search_result.destination_door instanceof TargetItemExpansionDoor)
{
TargetItemExpansionDoor curr_destination_door = (TargetItemExpansionDoor) p_maze_search_result.destination_door;
this.target_item = curr_destination_door.item;
this.target_layer = curr_destination_door.room.get_layer();
this.current_from_point = calculate_starting_point(curr_destination_door, p_search_tree);
}
else if (p_maze_search_result.destination_door instanceof ExpansionDrill)
{
// may happen only in case of fanout
this.target_item = null;
ExpansionDrill curr_drill = (ExpansionDrill) p_maze_search_result.destination_door;
this.current_from_point = curr_drill.location.to_float();
this.target_layer = curr_drill.first_layer + p_maze_search_result.section_no_of_door;
at_fanout_end = true;
}
else
{
System.out.println("LocateFoundConnectionAlgo: unexpected type of destination_door");
this.target_item = null;
this.target_layer = 0;
return;
}
this.current_trace_layer = this.target_layer;
this.previous_from_point = this.current_from_point;
boolean connection_done = false;
while (!connection_done)
{
boolean layer_changed = false;
if (at_fanout_end)
{
// do not increase this.current_target_door_index
layer_changed = true;
}
else
{
this.current_target_door_index = this.current_from_door_index + 1;
while (current_target_door_index < this.backtrack_array.length && !layer_changed)
{
if (this.backtrack_array[this.current_target_door_index].door instanceof ExpansionDrill)
{
layer_changed = true;
}
else
{
++this.current_target_door_index;
}
}
}
if (layer_changed)
{
// the next trace leads to a via
ExpansionDrill current_target_drill = (ExpansionDrill) this.backtrack_array[this.current_target_door_index].door;
this.current_target_shape = TileShape.get_instance(current_target_drill.location);
}
else
{
// the next trace leads to the final target
connection_done = true;
this.current_target_door_index = this.backtrack_array.length - 1;
TileShape target_shape = ((Connectable) start_item).get_trace_connection_shape(p_search_tree, start_door.tree_entry_no);
this.current_target_shape = target_shape.intersection(start_door.room.get_shape());
if (this.current_target_shape.dimension() >= 2)
{
// the target is a conduction area, make a save connection
// by shrinking the shape by the trace halfwidth.
double trace_half_width = this.ctrl.compensated_trace_half_width[start_door.room.get_layer()];
TileShape shrinked_shape = (TileShape) this.current_target_shape.offset(-trace_half_width);
if (!shrinked_shape.is_empty())
{
this.current_target_shape = shrinked_shape;
}
}
}
this.current_to_door_index = this.current_from_door_index + 1;
ResultItem next_trace = this.calculate_next_trace(layer_changed, at_fanout_end);
at_fanout_end = false;
this.connection_items.add(next_trace);
}
}
/**
* Calclates the next trace trace of the connection under construction.
* Returns null, if all traces are returned.
*/
private ResultItem calculate_next_trace(boolean p_layer_changed, boolean p_at_fanout_end)
{
Collection<FloatPoint> corner_list = new LinkedList<FloatPoint>();
corner_list.add(this.current_from_point);
if (!p_at_fanout_end)
{
FloatPoint adjusted_start_corner = this.adjust_start_corner();
if (adjusted_start_corner != this.current_from_point)
{
FloatPoint add_corner = calculate_additional_corner(this.current_from_point, adjusted_start_corner,
true, this.angle_restriction);
corner_list.add(add_corner);
corner_list.add(adjusted_start_corner);
this.previous_from_point = this.current_from_point;
this.current_from_point = adjusted_start_corner;
}
}
FloatPoint prev_corner = this.current_from_point;
for (;;)
{
Collection<FloatPoint> next_corners = calculate_next_trace_corners();
if (next_corners.isEmpty())
{
break;
}
Iterator<FloatPoint> it = next_corners.iterator();
while (it.hasNext())
{
FloatPoint curr_next_corner = it.next();
if (curr_next_corner != prev_corner)
{
corner_list.add(curr_next_corner);
this.previous_from_point = this.current_from_point;
this.current_from_point = curr_next_corner;
prev_corner = curr_next_corner;
}
}
}
int next_layer = this.current_trace_layer;
if (p_layer_changed)
{
this.current_from_door_index = this.current_target_door_index + 1;
CompleteExpansionRoom next_room = this.backtrack_array[this.current_from_door_index].next_room;
if (next_room != null)
{
next_layer = next_room.get_layer();
}
}
// Round the new trace corners to Integer.
Collection<IntPoint> rounded_corner_list = new LinkedList<IntPoint>();
Iterator<FloatPoint> it = corner_list.iterator();
IntPoint prev_point = null;
while (it.hasNext())
{
IntPoint curr_point = (it.next()).round();
if (!curr_point.equals(prev_point))
{
rounded_corner_list.add(curr_point);
prev_point = curr_point;
}
}
// Construct the result item
IntPoint[] corner_arr = new IntPoint[rounded_corner_list.size()];
Iterator<IntPoint> it2 = rounded_corner_list.iterator();
for (int i = 0; i < corner_arr.length; ++i)
{
corner_arr[i] = it2.next();
}
ResultItem result = new ResultItem(corner_arr, this.current_trace_layer);
this.current_trace_layer = next_layer;
return result;
}
/**
* Returns the next list of corners for the construction of the trace
* in calculate_next_trace. If the result is emppty, the trace is already completed.
*/
protected abstract Collection<FloatPoint> calculate_next_trace_corners();
/** Test display of the baktrack rooms. */
public void draw(java.awt.Graphics p_graphics, eu.mihosoft.freerouting.boardgraphics.GraphicsContext p_graphics_context)
{
for (int i = 0; i < backtrack_array.length; ++i)
{
CompleteExpansionRoom next_room = backtrack_array[i].next_room;
if (next_room != null)
{
next_room.draw(p_graphics, p_graphics_context, 0.2);
}
ExpandableObject next_door = backtrack_array[i].door;
if (next_door instanceof ExpansionDrill)
{
((ExpansionDrill) next_door).draw(p_graphics, p_graphics_context, 0.2);
}
}
}
/**
* Calculates the starting point of the next trace on p_from_door.item.
* The implementation is not yet optimal for starting points on traces
* or areas.
*/
private static FloatPoint calculate_starting_point(TargetItemExpansionDoor p_from_door, ShapeSearchTree p_search_tree)
{
TileShape connection_shape =
((Connectable) p_from_door.item).get_trace_connection_shape(p_search_tree, p_from_door.tree_entry_no);
connection_shape = connection_shape.intersection(p_from_door.room.get_shape());
return connection_shape.centre_of_gravity().round().to_float();
}
/**
* Creates a list of doors by backtracking from p_destination_door to
* the start door.
* Returns null, if p_destination_door is null.
*/
private static Collection<BacktrackElement> backtrack(MazeSearchAlgo.Result p_maze_search_result, SortedSet<Item> p_ripped_item_list)
{
if (p_maze_search_result == null)
{
return null;
}
Collection<BacktrackElement> result = new LinkedList<BacktrackElement>();
CompleteExpansionRoom curr_next_room = null;
ExpandableObject curr_backtrack_door = p_maze_search_result.destination_door;
MazeSearchElement curr_maze_search_element = curr_backtrack_door.get_maze_search_element(p_maze_search_result.section_no_of_door);
if (curr_backtrack_door instanceof TargetItemExpansionDoor)
{
curr_next_room = ((TargetItemExpansionDoor) curr_backtrack_door).room;
}
else if (curr_backtrack_door instanceof ExpansionDrill)
{
ExpansionDrill curr_drill = (ExpansionDrill) curr_backtrack_door;
curr_next_room = curr_drill.room_arr[curr_drill.first_layer + p_maze_search_result.section_no_of_door];
if (curr_maze_search_element.room_ripped)
{
for (CompleteExpansionRoom tmp_room : curr_drill.room_arr)
{
if (tmp_room instanceof ObstacleExpansionRoom)
{
p_ripped_item_list.add(((ObstacleExpansionRoom) tmp_room).get_item());
}
}
}
}
BacktrackElement curr_backtrack_element = new BacktrackElement(curr_backtrack_door, p_maze_search_result.section_no_of_door, curr_next_room);
for (;;)
{
result.add(curr_backtrack_element);
curr_backtrack_door = curr_maze_search_element.backtrack_door;
if (curr_backtrack_door == null)
{
break;
}
int curr_section_no = curr_maze_search_element.section_no_of_backtrack_door;
if (curr_section_no >= curr_backtrack_door.maze_search_element_count())
{
System.out.println("LocateFoundConnectionAlgo: curr_section_no to big");
curr_section_no = curr_backtrack_door.maze_search_element_count() - 1;
}
if (curr_backtrack_door instanceof ExpansionDrill)
{
ExpansionDrill curr_drill = (ExpansionDrill) curr_backtrack_door;
curr_next_room = curr_drill.room_arr[curr_section_no];
}
else
{
curr_next_room = curr_backtrack_door.other_room(curr_next_room);
}
curr_maze_search_element = curr_backtrack_door.get_maze_search_element(curr_section_no);
curr_backtrack_element = new BacktrackElement(curr_backtrack_door, curr_section_no, curr_next_room);
if (curr_maze_search_element.room_ripped)
{
if (curr_next_room instanceof ObstacleExpansionRoom)
{
p_ripped_item_list.add(((ObstacleExpansionRoom) curr_next_room).get_item());
}
}
}
return result;
}
/**
* Adjusts the start corner, so that a trace starting at this corner is completely
* contained in the start room.
*/
private FloatPoint adjust_start_corner()
{
if (this.current_from_door_index < 0)
{
return this.current_from_point;
}
BacktrackElement curr_from_info = this.backtrack_array[this.current_from_door_index];
if (curr_from_info.next_room == null)
{
return this.current_from_point;
}
double trace_half_width = this.ctrl.compensated_trace_half_width[this.current_trace_layer];
TileShape shrinked_room_shape = (TileShape) curr_from_info.next_room.get_shape().offset(-trace_half_width);
if (shrinked_room_shape.is_empty() || shrinked_room_shape.contains(this.current_from_point))
{
return this.current_from_point;
}
return shrinked_room_shape.nearest_point_approx(this.current_from_point).round().to_float();
}
private static FloatPoint ninety_degree_corner(FloatPoint p_from_point, FloatPoint p_to_point,
boolean p_horizontal_first)
{
double x;
double y;
if (p_horizontal_first)
{
x = p_to_point.x;
y = p_from_point.y;
}
else
{
x = p_from_point.x;
y = p_to_point.y;
}
return new FloatPoint(x, y);
}
private static FloatPoint fortyfive_degree_corner(FloatPoint p_from_point, FloatPoint p_to_point,
boolean p_horizontal_first)
{
double abs_dx = Math.abs(p_to_point.x - p_from_point.x);
double abs_dy = Math.abs(p_to_point.y - p_from_point.y);
double x;
double y;
if (abs_dx <= abs_dy)
{
if (p_horizontal_first)
{
x = p_to_point.x;
if (p_to_point.y >= p_from_point.y)
{
y = p_from_point.y + abs_dx;
}
else
{
y = p_from_point.y - abs_dx;
}
}
else
{
x = p_from_point.x;
if (p_to_point.y > p_from_point.y)
{
y = p_to_point.y - abs_dx;
}
else
{
y = p_to_point.y + abs_dx;
}
}
}
else
{
if (p_horizontal_first)
{
y = p_from_point.y;
if (p_to_point.x > p_from_point.x)
{
x = p_to_point.x - abs_dy;
}
else
{
x = p_to_point.x + abs_dy;
}
}
else
{
y = p_to_point.y;
if (p_to_point.x > p_from_point.x)
{
x = p_from_point.x + abs_dy;
}
else
{
x = p_from_point.x - abs_dy;
}
}
}
return new FloatPoint(x, y);
}
/**
* Calculates an additional corner, so that for the lines from p_from_point to the result corner
* and from the result corner to p_to_point p_angle_restriction is fulfilled.
*/
static FloatPoint calculate_additional_corner(FloatPoint p_from_point, FloatPoint p_to_point,
boolean p_horizontal_first, AngleRestriction p_angle_restriction)
{
FloatPoint result;
if (p_angle_restriction == AngleRestriction.NINETY_DEGREE)
{
result = ninety_degree_corner(p_from_point, p_to_point, p_horizontal_first);
}
else if (p_angle_restriction == AngleRestriction.FORTYFIVE_DEGREE)
{
result = fortyfive_degree_corner(p_from_point, p_to_point, p_horizontal_first);
}
else
{
result = p_to_point;
}
return result;
}
/** The new items implementing the found connection */
public final Collection<ResultItem> connection_items;
/** The start item of the new routed connection */
public final Item start_item;
/** The layer of the connection to the start item */
public final int start_layer;
/** The destination item of the new routed connection */
public final Item target_item;
/** The layer of the connection to the target item */
public final int target_layer;
/**
* The array of backtrack doors from the destination to the start of a found
* connection of the maze search algorithm.
*/
protected final BacktrackElement[] backtrack_array;
protected final AutorouteControl ctrl;
protected final AngleRestriction angle_restriction;
protected final TestLevel test_level;
protected final TargetItemExpansionDoor start_door;
protected FloatPoint current_from_point;
protected FloatPoint previous_from_point;
protected int current_trace_layer;
protected int current_from_door_index;
protected int current_to_door_index;
protected int current_target_door_index;
protected TileShape current_target_shape;
/**
* Type of a single item in the result list connection_items.
* Used to create a new PolylineTrace.
*/
protected static class ResultItem
{
public ResultItem(IntPoint[] p_corners, int p_layer)
{
corners = p_corners;
layer = p_layer;
}
public final IntPoint[] corners;
public final int layer;
}
/**
* Type of the elements of the list returned by this.backtrack().
* Next_room is the common room of the current door and the next
* door in the backtrack list.
*/
protected static class BacktrackElement
{
private BacktrackElement(ExpandableObject p_door, int p_section_no_of_door, CompleteExpansionRoom p_room)
{
door = p_door;
section_no_of_door = p_section_no_of_door;
next_room = p_room;
}
public final ExpandableObject door;
public final int section_no_of_door;
public final CompleteExpansionRoom next_room;
}
}
| andrasfuchs/BioBalanceDetector | Tools/KiCad_FreeRouting/FreeRouting-miho-master/freerouting-master/src/main/java/eu/mihosoft/freerouting/autoroute/LocateFoundConnectionAlgo.java | Java | gpl-3.0 | 22,361 |
/*******************************************************************
Part of the Fritzing project - http://fritzing.org
Copyright (c) 2007-2011 Fachhochschule Potsdam - http://fh-potsdam.de
Fritzing is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fritzing is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Fritzing. If not, see <http://www.gnu.org/licenses/>.
********************************************************************
$Revision: 5950 $:
$Author: cohen@irascible.com $:
$Date: 2012-04-07 10:26:22 -0700 (Sat, 07 Apr 2012) $
********************************************************************/
#include "logoitem.h"
#include "../utils/graphicsutils.h"
#include "../utils/folderutils.h"
#include "../utils/textutils.h"
#include "../fsvgrenderer.h"
#include "../sketch/infographicsview.h"
#include "../svg/svgfilesplitter.h"
#include "moduleidnames.h"
#include "../svg/groundplanegenerator.h"
#include "../utils/cursormaster.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFrame>
#include <QLabel>
#include <QRegExp>
#include <QPushButton>
#include <QImageReader>
#include <QMessageBox>
#include <QImage>
#include <QLineEdit>
#include <QApplication>
static QStringList ImageNames;
static QStringList NewImageNames;
static QStringList Copper0ImageNames;
static QStringList NewCopper0ImageNames;
static QStringList Copper1ImageNames;
static QStringList NewCopper1ImageNames;
LogoItem::LogoItem( ModelPart * modelPart, ViewIdentifierClass::ViewIdentifier viewIdentifier, const ViewGeometry & viewGeometry, long id, QMenu * itemMenu, bool doLabel)
: ResizableBoard(modelPart, viewIdentifier, viewGeometry, id, itemMenu, doLabel)
{
if (ImageNames.count() == 0) {
ImageNames << "Made with Fritzing" << "Fritzing icon" << "OHANDA logo" << "OSHW logo";
}
m_inLogoEntry = QTime::currentTime().addSecs(-10);
m_fileNameComboBox = NULL;
m_aspectRatioCheck = NULL;
m_keepAspectRatio = true;
m_hasLogo = (modelPart->moduleID() == ModuleIDNames::LogoTextModuleIDName);
m_logo = modelPart->prop("logo").toString();
if (m_hasLogo && m_logo.isEmpty()) {
m_logo = modelPart->properties().value("logo", "logo");
modelPart->setProp("logo", m_logo);
}
}
LogoItem::~LogoItem() {
}
void LogoItem::addedToScene(bool temporary)
{
if (this->scene()) {
setInitialSize();
m_aspectRatio.setWidth(this->boundingRect().width());
m_aspectRatio.setHeight(this->boundingRect().height());
m_originalFilename = filename();
QString shape = prop("shape");
if (!shape.isEmpty()) {
m_aspectRatio = modelPart()->prop("aspectratio").toSizeF();
if (loadExtraRenderer(shape.toUtf8(), false)) {
}
else {
DebugDialog::debug("bad shape in " + m_originalFilename + " " + shape);
}
}
else {
QFile f(m_originalFilename);
if (f.open(QFile::ReadOnly)) {
QString svg = f.readAll();
f.close();
modelPart()->setProp("shape", svg);
modelPart()->setProp("lastfilename", m_originalFilename);
initImage();
}
}
}
return ResizableBoard::addedToScene(temporary);
}
QString LogoItem::retrieveSvg(ViewLayer::ViewLayerID viewLayerID, QHash<QString, QString> & svgHash, bool blackOnly, double dpi)
{
if (viewLayerID == layer() ) {
QString svg = prop("shape");
if (!svg.isEmpty()) {
QString xmlName = ViewLayer::viewLayerXmlNameFromID(viewLayerID);
SvgFileSplitter splitter;
bool result = splitter.splitString(svg, xmlName);
if (!result) {
return "";
}
double scaleX = 1;
double scaleY = 1;
if (m_hasLogo) {
QDomDocument doc = splitter.domDocument();
QDomElement root = doc.documentElement();
QDomElement g = root.firstChildElement("g");
QDomElement text = g.firstChildElement("text");
// TODO: this is really a hack and resizing should change a scale factor rather than the <text> coordinates
// but it's not clear how to deal with existing sketches
QString viewBox = root.attribute("viewBox");
double w = TextUtils::convertToInches(root.attribute("width"));
double h = TextUtils::convertToInches(root.attribute("height"));
QStringList coords = viewBox.split(" ", QString::SkipEmptyParts);
double sx = w / coords.at(2).toDouble();
double sy = h / coords.at(3).toDouble();
if (qAbs(sx - sy) > .001) {
// change vertical dpi to match horizontal dpi
// y coordinate is really intended in relation to font size so leave it be
scaleY = sy / sx;
root.setAttribute("viewBox", QString("0 0 %1 %2").arg(coords.at(2)).arg(h / sx));
}
}
result = splitter.normalize(dpi, xmlName, blackOnly);
if (!result) {
return "";
}
QString string = splitter.elementString(xmlName);
if (scaleY == 1) return string;
QTransform t;
t.scale(scaleX, scaleY);
return TextUtils::svgTransform(string, t, false, "");
}
}
return PaletteItemBase::retrieveSvg(viewLayerID, svgHash, blackOnly, dpi);
}
bool LogoItem::collectExtraInfo(QWidget * parent, const QString & family, const QString & prop, const QString & value, bool swappingEnabled, QString & returnProp, QString & returnValue, QWidget * & returnWidget)
{
if (m_hasLogo) {
if (prop.compare("logo", Qt::CaseInsensitive) == 0) {
returnProp = tr("logo");
returnValue = m_logo;
QLineEdit * edit = new QLineEdit(parent);
edit->setObjectName("infoViewLineEdit");
edit->setText(m_logo);
edit->setEnabled(swappingEnabled);
connect(edit, SIGNAL(editingFinished()), this, SLOT(logoEntry()));
returnWidget = edit;
return true;
}
}
else {
if (prop.compare("filename", Qt::CaseInsensitive) == 0) {
returnProp = tr("image file");
QFrame * frame = new QFrame();
frame->setObjectName("infoViewPartFrame");
QVBoxLayout * vboxLayout = new QVBoxLayout();
vboxLayout->setContentsMargins(0, 0, 0, 0);
vboxLayout->setSpacing(0);
vboxLayout->setMargin(0);
QComboBox * comboBox = new QComboBox();
comboBox->setObjectName("infoViewComboBox");
comboBox->setEditable(false);
comboBox->setEnabled(swappingEnabled);
m_fileNameComboBox = comboBox;
setFileNameItems();
connect(comboBox, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(fileNameEntry(const QString &)));
QPushButton * button = new QPushButton (tr("load image file"));
button->setObjectName("infoViewButton");
connect(button, SIGNAL(pressed()), this, SLOT(prepLoadImage()));
button->setEnabled(swappingEnabled);
vboxLayout->addWidget(comboBox);
vboxLayout->addWidget(button);
frame->setLayout(vboxLayout);
returnWidget = frame;
returnProp = "";
return true;
}
}
if (prop.compare("shape", Qt::CaseInsensitive) == 0) {
returnWidget = setUpDimEntry(true, returnWidget);
returnProp = tr("shape");
return true;
}
return PaletteItem::collectExtraInfo(parent, family, prop, value, swappingEnabled, returnProp, returnValue, returnWidget);
}
void LogoItem::prepLoadImage() {
QList<QByteArray> supportedImageFormats = QImageReader::supportedImageFormats();
QString imagesStr = tr("Images");
imagesStr += " (";
foreach (QByteArray ba, supportedImageFormats) {
imagesStr += "*." + QString(ba) + " ";
}
if (!imagesStr.contains("svg")) {
imagesStr += "*.svg";
}
imagesStr += ")";
QString fileName = FolderUtils::getOpenFileName(
NULL,
tr("Select an image file to load"),
"",
imagesStr
);
if (fileName.isEmpty()) return;
prepLoadImageAux(fileName, true);
}
void LogoItem::prepLoadImageAux(const QString & fileName, bool addName)
{
InfoGraphicsView * infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this);
if (infoGraphicsView != NULL) {
infoGraphicsView->loadLogoImage(this->id(), prop("shape"), m_aspectRatio, prop("lastfilename"), fileName, addName);
}
}
void LogoItem::reloadImage(const QString & svg, const QSizeF & aspectRatio, const QString & fileName, bool addName)
{
bool result = loadExtraRenderer(svg.toUtf8(), false);
if (result) {
if (aspectRatio == QSizeF(0, 0)) {
QRectF r = m_extraRenderer->viewBoxF();
m_aspectRatio.setWidth(r.width());
m_aspectRatio.setHeight(r.height());
}
else {
m_aspectRatio = aspectRatio;
}
modelPart()->setProp("aspectratio", m_aspectRatio);
modelPart()->setProp("shape", svg);
modelPart()->setProp("logo", "");
modelPart()->setProp("lastfilename", fileName);
if (addName) {
if (!getNewImageNames().contains(fileName, Qt::CaseInsensitive)) {
getNewImageNames().append(fileName);
bool wasBlocked = m_fileNameComboBox->blockSignals(true);
while (m_fileNameComboBox->count() > 0) {
m_fileNameComboBox->removeItem(0);
}
setFileNameItems();
m_fileNameComboBox->blockSignals(wasBlocked);
}
}
m_logo = "";
LayerHash layerHash;
resizeMM(GraphicsUtils::pixels2mm(m_aspectRatio.width(), FSvgRenderer::printerScale()),
GraphicsUtils::pixels2mm(m_aspectRatio.height(), FSvgRenderer::printerScale()),
layerHash);
}
else {
// restore previous (not sure whether this is necessary)
loadExtraRenderer(prop("shape").toUtf8(), false);
unableToLoad(fileName);
}
}
void LogoItem::loadImage(const QString & fileName, bool addName)
{
QString svg;
if (fileName.endsWith(".svg")) {
QFile f(fileName);
if (f.open(QFile::ReadOnly)) {
svg = f.readAll();
}
if (svg.isEmpty()) {
unableToLoad(fileName);
return;
}
TextUtils::cleanSodipodi(svg);
TextUtils::fixPixelDimensionsIn(svg);
TextUtils::fixViewboxOrigin(svg);
TextUtils::tspanRemove(svg);
QString errorStr;
int errorLine;
int errorColumn;
QDomDocument domDocument;
if (!domDocument.setContent(svg, true, &errorStr, &errorLine, &errorColumn)) {
unableToLoad(fileName);
return;
}
QDomElement root = domDocument.documentElement();
if (root.isNull()) {
unableToLoad(fileName);
return;
}
if (root.tagName() != "svg") {
unableToLoad(fileName);
return;
}
QStringList exceptions;
exceptions << "none" << "";
QString toColor(colorString());
SvgFileSplitter::changeColors(root, toColor, exceptions);
bool isIllustrator = TextUtils::isIllustratorDoc(domDocument);
QString viewBox = root.attribute("viewBox");
if (viewBox.isEmpty()) {
bool ok1, ok2;
double w = TextUtils::convertToInches(root.attribute("width"), &ok1, isIllustrator) * FSvgRenderer::printerScale();
double h = TextUtils::convertToInches(root.attribute("height"), &ok2, isIllustrator) * FSvgRenderer::printerScale();
if (!ok1 || !ok2) {
unableToLoad(fileName);
return;
}
root.setAttribute("viewBox", QString("0 0 %1 %2").arg(w).arg(h));
}
QList<QDomNode> rootChildren;
QDomNode rootChild = root.firstChild();
while (!rootChild.isNull()) {
rootChildren.append(rootChild);
rootChild = rootChild.nextSibling();
}
QDomElement topG = domDocument.createElement("g");
topG.setAttribute("id", layerName());
root.appendChild(topG);
foreach (QDomNode node, rootChildren) {
topG.appendChild(node);
}
svg = TextUtils::removeXMLEntities(domDocument.toString());
}
else {
QImage image(fileName);
if (image.isNull()) {
unableToLoad(fileName);
return;
}
if (image.format() != QImage::Format_RGB32 && image.format() != QImage::Format_ARGB32) {
image = image.convertToFormat(QImage::Format_Mono);
}
GroundPlaneGenerator gpg;
gpg.setLayerName(layerName());
gpg.setMinRunSize(1, 1);
double res = image.dotsPerMeterX() / GraphicsUtils::InchesPerMeter;
gpg.scanImage(image, image.width(), image.height(), 1, res, colorString(), false, false, QSizeF(0, 0), 0, QPointF(0, 0));
QStringList newSvgs = gpg.newSVGs();
if (newSvgs.count() < 1) {
QMessageBox::information(
NULL,
tr("Unable to display"),
tr("Unable to display image from %1").arg(fileName)
);
return;
}
QDomDocument doc;
foreach (QString newSvg, newSvgs) {
TextUtils::mergeSvg(doc, newSvg, layerName());
}
svg = TextUtils::mergeSvgFinish(doc);
}
reloadImage(svg, QSizeF(0, 0), fileName, addName);
}
void LogoItem::resizeMM(double mmW, double mmH, const LayerHash & viewLayers) {
Q_UNUSED(viewLayers);
if (mmW == 0 || mmH == 0) {
return;
}
DebugDialog::debug(QString("resize mm %1 %2").arg(mmW).arg(mmH));
QRectF r = this->boundingRect();
if (qAbs(GraphicsUtils::pixels2mm(r.width(), FSvgRenderer::printerScale()) - mmW) < .001 &&
qAbs(GraphicsUtils::pixels2mm(r.height(), FSvgRenderer::printerScale()) - mmH) < .001)
{
return;
}
double inW = GraphicsUtils::mm2mils(mmW) / 1000;
double inH = GraphicsUtils::mm2mils(mmH) / 1000;
// TODO: deal with aspect ratio
QString svg = prop("shape");
if (svg.isEmpty()) return;
QString errorStr;
int errorLine;
int errorColumn;
QDomDocument domDocument;
if (!domDocument.setContent(svg, &errorStr, &errorLine, &errorColumn)) {
return;
}
QDomElement root = domDocument.documentElement();
if (root.isNull()) {
return;
}
if (root.tagName() != "svg") {
return;
}
root.setAttribute("width", QString::number(inW) + "in");
root.setAttribute("height", QString::number(inH) + "in");
svg = TextUtils::removeXMLEntities(domDocument.toString());
bool result = loadExtraRenderer(svg.toUtf8(), false);
if (result) {
modelPart()->setProp("shape", svg);
modelPart()->setProp("width", mmW);
modelPart()->setProp("height", mmH);
}
setWidthAndHeight(qRound(mmW * 10) / 10.0, qRound(mmH * 10) / 10.0);
}
void LogoItem::setProp(const QString & prop, const QString & value) {
if (prop.compare("logo", Qt::CaseInsensitive) == 0) {
setLogo(value, false);
return;
}
ResizableBoard::setProp(prop, value);
}
void LogoItem::setLogo(QString logo, bool force) {
if (!force && m_logo.compare(logo) == 0) return;
switch (this->m_viewIdentifier) {
case ViewIdentifierClass::PCBView:
break;
default:
return;
}
QString svg;
QFile f(m_originalFilename);
if (f.open(QFile::ReadOnly)) {
svg = f.readAll();
}
if (svg.isEmpty()) return;
QSizeF oldSize = m_size;
QXmlStreamReader streamReader(svg);
QSizeF oldSvgSize = m_extraRenderer ? m_extraRenderer->viewBoxF().size() : QSizeF(0, 0);
DebugDialog::debug(QString("size %1 %2, %3 %4").arg(m_size.width()).arg(m_size.height()).arg(oldSvgSize.width()).arg(oldSvgSize.height()));
svg = hackSvg(svg, logo);
QXmlStreamReader newStreamReader(svg);
bool ok = rerender(svg);
m_logo = logo;
modelPart()->setProp("logo", logo);
modelPart()->setProp("shape", svg);
if (ok && !force) {
QSizeF newSvgSize = m_extraRenderer->viewBoxF().size();
QSizeF newSize = newSvgSize * oldSize.height() / oldSvgSize.height();
DebugDialog::debug(QString("size %1 %2, %3 %4").arg(m_size.width()).arg(m_size.height()).arg(newSize.width()).arg(newSize.height()));
// set the new text to approximately the same height as the original
// if the text is non-proportional that will be lost
LayerHash layerHash;
resizeMM(GraphicsUtils::pixels2mm(newSize.width(), FSvgRenderer::printerScale()),
GraphicsUtils::pixels2mm(newSize.height(), FSvgRenderer::printerScale()),
layerHash);
//DebugDialog::debug(QString("size %1 %2").arg(m_size.width()).arg(m_size.height()));
}
}
bool LogoItem::rerender(const QString & svg)
{
bool result = loadExtraRenderer(svg.toUtf8(), false);
if (result) {
QRectF r = m_extraRenderer->viewBoxF();
m_aspectRatio.setWidth(r.width());
m_aspectRatio.setHeight(r.height());
}
return result;
}
QString LogoItem::getProperty(const QString & key) {
if (key.compare("logo", Qt::CaseInsensitive) == 0) {
return m_logo;
}
return PaletteItem::getProperty(key);
}
const QString & LogoItem::logo() {
return m_logo;
}
bool LogoItem::canEditPart() {
return false;
}
bool LogoItem::hasPartLabel() {
return false;
}
void LogoItem::logoEntry() {
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
if (edit == NULL) return;
if (edit->text().compare(this->logo()) == 0) return;
// m_inLogoEntry is a hack because a focus out event was being triggered on m_widthEntry when a user hit the return key in logoentry
// this triggers a call to widthEntry() which causes all kinds of havoc. (bug in version 0.7.1 and possibly earlier)
m_inLogoEntry = QTime::currentTime().addSecs(1);
InfoGraphicsView * infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this);
if (infoGraphicsView != NULL) {
infoGraphicsView->setProp(this, "logo", tr("logo"), this->logo(), edit->text(), true);
}
}
void LogoItem::initImage() {
if (m_hasLogo) {
setLogo(m_logo, true);
return;
}
loadImage(m_originalFilename, false);
}
QString LogoItem::hackSvg(const QString & svg, const QString & logo)
{
QString errorStr;
int errorLine;
int errorColumn;
QDomDocument doc;
if (!doc.setContent(svg, &errorStr, &errorLine, &errorColumn)) return svg;
QDomElement root = doc.documentElement();
root.setAttribute("width", QString::number(logo.length() * 0.1) + "in");
QString viewBox = root.attribute("viewBox");
QStringList coords = viewBox.split(" ", QString::SkipEmptyParts);
coords[2] = QString::number(logo.length() * 10);
root.setAttribute("viewBox", coords.join(" "));
QDomNodeList domNodeList = root.elementsByTagName("text");
for (int i = 0; i < domNodeList.count(); i++) {
QDomElement node = domNodeList.item(i).toElement();
if (node.isNull()) continue;
if (node.attribute("id").compare("label") != 0) continue;
node.setAttribute("x", QString::number(logo.length() * 5));
QDomNodeList childList = node.childNodes();
for (int j = 0; j < childList.count(); j++) {
QDomNode child = childList.item(i);
if (child.isText()) {
child.setNodeValue(logo);
modelPart()->setProp("width", logo.length() * 0.1 * 25.4);
QString h = root.attribute("height");
bool ok;
modelPart()->setProp("height", TextUtils::convertToInches(h, &ok, false) * 25.4);
return doc.toString();
}
}
}
return svg;
}
void LogoItem::widthEntry() {
if (QTime::currentTime() < m_inLogoEntry) return;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
if (edit == NULL) return;
double w = edit->text().toDouble();
double oldW = m_modelPart->prop("width").toDouble();
if (w == oldW) return;
double h = m_modelPart->prop("height").toDouble();
if (m_keepAspectRatio) {
h = w * m_aspectRatio.height() / m_aspectRatio.width();
}
InfoGraphicsView * infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this);
if (infoGraphicsView != NULL) {
infoGraphicsView->resizeBoard(w, h, true);
}
}
void LogoItem::heightEntry() {
if (QTime::currentTime() < m_inLogoEntry) return;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
if (edit == NULL) return;
double h = edit->text().toDouble();
double oldH = m_modelPart->prop("height").toDouble();
if (h == oldH) return;
setHeight(h);
}
void LogoItem::setHeight(double h)
{
double w = m_modelPart->prop("width").toDouble();
if (m_keepAspectRatio) {
w = h * m_aspectRatio.width() / m_aspectRatio.height();
}
InfoGraphicsView * infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this);
if (infoGraphicsView != NULL) {
infoGraphicsView->resizeBoard(w, h, true);
}
}
void LogoItem::unableToLoad(const QString & fileName) {
QMessageBox::information(
NULL,
tr("Unable to load"),
tr("Unable to load image from %1").arg(fileName)
);
}
void LogoItem::keepAspectRatio(bool checkState) {
m_keepAspectRatio = checkState;
}
void LogoItem::fileNameEntry(const QString & filename) {
foreach (QString name, getImageNames()) {
if (filename.compare(name) == 0) {
QString f = FolderUtils::getApplicationSubFolderPath("parts") + "/svg/core/pcb/" + filename + ".svg";
return prepLoadImageAux(f, false);
break;
}
}
prepLoadImageAux(filename, true);
}
void LogoItem::setFileNameItems() {
if (m_fileNameComboBox == NULL) return;
m_fileNameComboBox->addItems(getImageNames());
m_fileNameComboBox->addItems(getNewImageNames());
int ix = 0;
foreach (QString name, getImageNames()) {
if (prop("lastfilename").contains(name)) {
m_fileNameComboBox->setCurrentIndex(ix);
return;
}
ix++;
}
foreach (QString name, getNewImageNames()) {
if (prop("lastfilename").contains(name)) {
m_fileNameComboBox->setCurrentIndex(ix);
return;
}
ix++;
}
}
bool LogoItem::stickyEnabled() {
return true;
}
ItemBase::PluralType LogoItem::isPlural() {
return Plural;
}
ViewLayer::ViewLayerID LogoItem::layer() {
return ViewLayer::Silkscreen1;
}
QString LogoItem::colorString() {
return ViewLayer::Silkscreen1Color;
}
QString LogoItem::layerName()
{
return ViewLayer::viewLayerXmlNameFromID(layer());
}
QStringList & LogoItem::getImageNames() {
return ImageNames;
}
QStringList & LogoItem::getNewImageNames() {
return NewImageNames;
}
double LogoItem::minWidth() {
return ResizableBoard::CornerHandleSize * 2;
}
double LogoItem::minHeight() {
return ResizableBoard::CornerHandleSize * 2;
}
bool LogoItem::freeRotationAllowed(Qt::KeyboardModifiers modifiers) {
if ((modifiers & altOrMetaModifier()) == 0) return false;
if (!isSelected()) return false;
return true;
}
ResizableBoard::Corner LogoItem::findCorner(QPointF scenePos, Qt::KeyboardModifiers modifiers) {
ResizableBoard::Corner corner = ResizableBoard::findCorner(scenePos, modifiers);
if (corner == ResizableBoard::NO_CORNER) return corner;
if (modifiers & altOrMetaModifier()) {
// free rotate
setCursor(*CursorMaster::RotateCursor);
return ResizableBoard::NO_CORNER;
}
return corner;
}
void LogoItem::paintHover(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
PaletteItem::paintHover(painter, option, widget);
}
///////////////////////////////////////////////////////////////////////
CopperLogoItem::CopperLogoItem( ModelPart * modelPart, ViewIdentifierClass::ViewIdentifier viewIdentifier, const ViewGeometry & viewGeometry, long id, QMenu * itemMenu, bool doLabel)
: LogoItem(modelPart, viewIdentifier, viewGeometry, id, itemMenu, doLabel)
{
if (Copper1ImageNames.count() == 0) {
Copper1ImageNames << "Fritzing icon copper1";
}
if (Copper0ImageNames.count() == 0) {
Copper0ImageNames << "Fritzing icon copper0";
}
m_hasLogo = (modelPart->moduleID().endsWith(ModuleIDNames::LogoTextModuleIDName));
m_logo = modelPart->prop("logo").toString();
if (m_hasLogo && m_logo.isEmpty()) {
m_logo = modelPart->properties().value("logo", "logo");
modelPart->setProp("logo", m_logo);
}
}
CopperLogoItem::~CopperLogoItem() {
}
ViewLayer::ViewLayerID CopperLogoItem::layer() {
return isCopper0() ? ViewLayer::Copper0 : ViewLayer::Copper1;
}
QString CopperLogoItem::colorString() {
return isCopper0() ? ViewLayer::Copper0Color : ViewLayer::Copper1Color;
}
QStringList & CopperLogoItem::getImageNames() {
return isCopper0() ? Copper0ImageNames : Copper1ImageNames;
}
QStringList & CopperLogoItem::getNewImageNames() {
return isCopper0() ? NewCopper0ImageNames : NewCopper1ImageNames;
}
QString CopperLogoItem::hackSvg(const QString & svg, const QString & logo) {
QString newSvg = LogoItem::hackSvg(svg, logo);
if (!isCopper0()) return newSvg;
return flipSvg(newSvg);
}
QString CopperLogoItem::flipSvg(const QString & svg)
{
QString newSvg = svg;
newSvg.replace("copper1", "copper0");
newSvg.replace(ViewLayer::Copper1Color, ViewLayer::Copper0Color, Qt::CaseInsensitive);
QMatrix m;
QSvgRenderer renderer(newSvg.toUtf8());
QRectF bounds = renderer.viewBoxF();
m.translate(bounds.center().x(), bounds.center().y());
QMatrix mMinus = m.inverted();
QMatrix cm = mMinus * QMatrix().scale(-1, 1) * m;
int gix = newSvg.indexOf("<g");
newSvg.replace(gix, 2, "<g _flipped_='1' transform='" + TextUtils::svgMatrix(cm) + "'");
return newSvg;
}
void CopperLogoItem::reloadImage(const QString & svg, const QSizeF & aspectRatio, const QString & fileName, bool addName)
{
if (isCopper0()) {
if (!svg.contains("_flipped_")) {
LogoItem::reloadImage(flipSvg(svg), aspectRatio, fileName, addName);
return;
}
}
LogoItem::reloadImage(svg, aspectRatio, fileName, addName);
}
bool CopperLogoItem::isCopper0() {
return modelPart()->properties().value("layer").contains("0");
}
| logxen/Fritzing | src/items/logoitem.cpp | C++ | gpl-3.0 | 24,431 |
package com.google.todotxt.backend;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
/** The Objectify object model for device registrations we are persisting */
@Entity
public class RegistrationRecord {
@Id
Long id;
@Index
private String regId;
// you can add more fields...
public RegistrationRecord() {}
public String getRegId() {
return regId;
}
public void setRegId(String regId) {
this.regId = regId;
}
} | Belobobr/Eventsource | todoTxtBackend/src/main/java/com/google/todotxt/backend/RegistrationRecord.java | Java | gpl-3.0 | 572 |
<?php
/**
* Copyright © OXID eSales AG. All rights reserved.
* See LICENSE file for license details.
*/
namespace OxidEsales\EshopCommunity\Tests\Acceptance\Admin\testData\modules\ModuleWithNamespace\Application\Controller;
use OxidEsales\Eshop\Application\Controller\FrontendController;
class TestModuleTenPaymentController extends FrontendController
{
/**
* @return mixed The template name.
*/
public function render()
{
$template = parent::render();
$model = oxNew('TestModuleTenModel');
$message = $model->getInfo();
oxRegistry::getSession()->setVariable('payerror', '-1');
oxRegistry::getSession()->setVariable('payerrortext', 'Test module prevents payment! ' . microtime(true) . $message);
return $template;
}
}
| OXID-eSales/oxideshop_ce | tests/Codeception/_data/modules/ModuleWithNamespace/Controller/TestModuleTenPaymentController.php | PHP | gpl-3.0 | 802 |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void выходToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
public void LoadImg(string path)
{
Image image = Image.FromFile(path);
int width = image.Width;
int height = image.Height;
pictureBox1.Image = image;
pictureBox1.Width = width;
pictureBox1.Height = height;
}
private void ВолгаToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке река Волга";
LoadImg("../../../jpg/volga.jpg");
}
private void МоскваToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке река Москва";
LoadImg("../../../jpg/moskva.jpg");
}
private void ОкаToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке река Ока";
LoadImg("../../../jpg/oka.jpg");
}
private void ЧерноеToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке Черное море";
LoadImg("../../../jpg/black.jpg");
}
private void БалтийскоеToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке Балтийское море";
LoadImg("../../../jpg/balta.jpg");
}
private void АзовскоеToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке Азовское море";
LoadImg("../../../jpg/azov.jpg");
}
private void ЛадожскоеToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке Ладожское озеро";
LoadImg("../../../jpg/ladoshskoye.jpg");
}
private void ОнежскоеToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке Онежское озеро";
LoadImg("../../../jpg/oneshskoye.jpg");
}
private void БайкалToolStripMenuItem_Click(object sender, EventArgs e)
{
MainLabel.Text = "На картинке озеро Байкал";
LoadImg("../../../jpg/baykal.jpg");
}
private void открытьИзФайлаToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image files (*.BMP, *.JPG, *.GIF, *.PNG)| *.bmp; *.jpg; *.gif; *.png";
if (dialog.ShowDialog() == DialogResult.OK)
{
Image image = Image.FromFile(dialog.FileName);
int width = image.Width;
int height = image.Height;
pictureBox1.Width = width;
pictureBox1.Height = height;
pictureBox1.Image = image;
}
}
private void сохранитьКакToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
pictureBox1.Image.Save("../../../output.jpg", ImageFormat.Jpeg);
}
catch (System.NullReferenceException)
{
MessageBox.Show("Не загружено изображение");
}
}
}
}
| GeorgiyDemo/KIP | Course IV/ТРПО/examples/MenuDialogExample/WindowsFormsApp1/WindowsFormsApp1/Form1.cs | C# | gpl-3.0 | 4,034 |
/**
* Copyright (C) 2009 STMicroelectronics
*
* This file is part of "Mind Compiler" is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: mind@ow2.org
*
* Authors: Matthieu Leclercq
* Contributors:
*/
package org.ow2.mind.adl.imports;
import static org.ow2.mind.NameHelper.getPackageName;
import static org.ow2.mind.adl.imports.ast.ImportASTHelper.isOnDemandImport;
import static org.ow2.mind.adl.imports.ast.ImportASTHelper.setUsedImport;
import java.util.Map;
import org.objectweb.fractal.adl.ADLException;
import org.objectweb.fractal.adl.Definition;
import org.ow2.mind.adl.ADLLocator;
import org.ow2.mind.adl.DefinitionReferenceResolver;
import org.ow2.mind.adl.DefinitionReferenceResolver.AbstractDelegatingDefinitionReferenceResolver;
import org.ow2.mind.adl.ast.DefinitionReference;
import org.ow2.mind.adl.imports.ast.Import;
import org.ow2.mind.adl.imports.ast.ImportContainer;
import com.google.inject.Inject;
/**
* Delegating {@link DefinitionReferenceResolver} that uses {@link Import} nodes
* of the <code>encapsulatingDefinition</code> to complete the name contained in
* the definition reference to resolve.
*/
public class ImportDefinitionReferenceResolver
extends
AbstractDelegatingDefinitionReferenceResolver {
@Inject
protected ADLLocator adlLocatorItf;
// ---------------------------------------------------------------------------
// Implementation of the DefinitionReferenceResolver interface
// ---------------------------------------------------------------------------
public Definition resolve(final DefinitionReference reference,
final Definition encapsulatingDefinition,
final Map<Object, Object> context) throws ADLException {
reference.setName(resolveName(reference.getName(), encapsulatingDefinition,
context));
return clientResolverItf.resolve(reference, encapsulatingDefinition,
context);
}
protected String resolveName(final String name,
final Definition encapsilatingDefinition,
final Map<Object, Object> context) {
if (name.contains(".")) {
return name;
}
final Import[] imports = (encapsilatingDefinition instanceof ImportContainer)
? ((ImportContainer) encapsilatingDefinition).getImports()
: null;
if (imports != null) {
for (final Import imp : imports) {
if (isOnDemandImport(imp)) {
// on-demand import.
final String fullyQualifiedName = imp.getPackageName() + '.' + name;
if (adlLocatorItf.findBinaryADL(fullyQualifiedName, context) != null
|| adlLocatorItf.findSourceADL(fullyQualifiedName, context) != null) {
return fullyQualifiedName;
}
} else {
if (imp.getSimpleName().equals(name)) {
// import simple name matches
setUsedImport(imp);
return imp.getPackageName() + '.' + name;
}
}
}
}
if (encapsilatingDefinition != null) {
final String packageName = getPackageName(encapsilatingDefinition
.getName());
// try in current package.
if (packageName != null) {
final String fullyQualifiedName = packageName + '.' + name;
if (adlLocatorItf.findBinaryADL(fullyQualifiedName, context) != null
|| adlLocatorItf.findSourceADL(fullyQualifiedName, context) != null) {
return fullyQualifiedName;
}
}
}
// no import match, return the name as it is (i.e. assume that it refers to
// an ADL in the 'default package').
return name;
}
}
| MIND-Tools/mind-compiler | adl-frontend/src/main/java/org/ow2/mind/adl/imports/ImportDefinitionReferenceResolver.java | Java | gpl-3.0 | 4,188 |
/**
* Copyright 2014, 2015, 2016 TAIN, Inc. all rights reserved.
*
* Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007 (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.gnu.org/licenses/
*
* 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.
*
* -----------------------------------------------------------------
* Copyright 2014, 2015, 2016 TAIN, Inc.
*
*/
package tain.kr.com.test.file.v02;
/**
*
* Code Templates > Comments > Types
*
* <PRE>
* -. FileName : FileInfoBean.java
* -. Package : tain.kr.com.test.file.v02
* -. Comment :
* -. Author : taincokr
* -. First Date : 2016. 2. 2. {time}
* </PRE>
*
* @author taincokr
*
*/
public class FileInfoBean {
private static boolean flag = true;
private String type; // file type : RF(Remote File), LF(Local File), RD(Remote File Download), LU(Local File Upload)
private String base; // base path name
private String name; // file name except base path name
private long time; // last modified time by millisecond
private long length; // file size
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
///////////////////////////////////////////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
if (flag) {
sb.append(this.type).append("||");
sb.append(this.base).append("||");
sb.append(this.name).append("||");
sb.append(this.time).append("||");
sb.append(this.length);
}
return sb.toString();
}
}
| grtlinux/KIEA_JAVA7 | KIEA_JAVA7/src/tain/kr/com/test/file/v02/FileInfoBean.java | Java | gpl-3.0 | 2,390 |
// Decompiled with JetBrains decompiler
// Type: System.Deployment.Internal.Isolation.IEnumSTORE_CATEGORY_SUBCATEGORY
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 255ABCDF-D9D6-4E3D-BAD4-F74D4CE3D7A8
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll
using System.Runtime.InteropServices;
using System.Security;
namespace System.Deployment.Internal.Isolation
{
[Guid("19be1967-b2fc-4dc1-9627-f3cb6305d2a7")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
internal interface IEnumSTORE_CATEGORY_SUBCATEGORY
{
[SecurityCritical]
uint Next([In] uint celt, [MarshalAs(UnmanagedType.LPArray), Out] STORE_CATEGORY_SUBCATEGORY[] rgElements);
[SecurityCritical]
void Skip([In] uint ulElements);
[SecurityCritical]
void Reset();
[SecurityCritical]
IEnumSTORE_CATEGORY_SUBCATEGORY Clone();
}
}
| mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/mscorlib/System/Deployment/Internal/Isolation/IEnumSTORE_CATEGORY_SUBCATEGORY.cs | C# | gpl-3.0 | 938 |
#pragma once
/* This file is part of Imagine.
Imagine is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Imagine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Imagine. If not, see <http://www.gnu.org/licenses/> */
#include <imagine/config/defs.hh>
#ifdef __APPLE__
#include <imagine/thread/MachSemaphore.hh>
#else
#include <imagine/thread/PosixSemaphore.hh>
#endif
namespace IG
{
class Semaphore : public SemaphoreImpl
{
public:
Semaphore(unsigned int startValue);
void wait();
void notify();
};
}
| DarkCaster/emu-ex-plus-alpha | imagine/include/imagine/thread/Semaphore.hh | C++ | gpl-3.0 | 950 |
//
// Created by icebeetle on 18-6-23.
//
#include<bits/stdc++.h>
using namespace std;
struct _t {
int x, y, z, t;
explicit _t(int xx = 0, int yy = 0, int zz = 0, int tt = 0) : x(xx), y(yy), z(zz), t(tt) {};
friend bool operator<(const _t &a, const _t &b) {
return a.t < b.t;
}
};
const int SIZE_T = 200000;
const int SIZE = 510;
_t peo[SIZE_T];
inline int read_t(int a, int b, int c, int d) {
return (a * 60 * 60 + b * 60 + c) * 1000 + d;
}
int chess[SIZE][SIZE];
int main(int argc, char *argv[]) {
int n, m, k;
while (scanf("%d%d%d", &n, &m, &k) != EOF) {
for (int i = 0; i < k; ++i) {
int x, y, z, a, b, c, d;
scanf("%d%d%d%d:%d:%d.%d", &x, &y, &z, &a, &b, &c, &d);
peo[i] = _t(x - 1, y - 1, z, read_t(a, b, c, d));
}
sort(peo, peo + k);
int cnt = 0;
int mcnt = 0;
int ansid = -1;
memset(chess, 0, sizeof(chess));
for (int i = 0; i < k; ++i) {
if (peo[i].z == 0) {
if (chess[peo[i].x][peo[i].y] == 0) cnt++;
chess[peo[i].x][peo[i].y]++;
} else {
if (chess[peo[i].x][peo[i].y] == 1) cnt--;
chess[peo[i].x][peo[i].y]--;
}
if (mcnt <= cnt) {
mcnt = cnt;
ansid = i;
}
}
memset(chess, 0, sizeof(chess));
for (int i = 0; i <= ansid; ++i) {
if (peo[i].z == 0) {
if (chess[peo[i].x][peo[i].y] == 0) cnt++;
chess[peo[i].x][peo[i].y]++;
} else {
if (chess[peo[i].x][peo[i].y] == 1) cnt--;
chess[peo[i].x][peo[i].y]--;
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j)printf(chess[i][j] ? "1" : "0");
printf("\n");
}
}
return 0;
} | bitwater1997/ACM | Contest/CodeM2018/B-Round/1.cpp | C++ | gpl-3.0 | 1,917 |
/*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*!
* Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=bdc334eb7ee1e998de2a85b5f46ddcac)
* Config saved to config.json and https://gist.github.com/bdc334eb7ee1e998de2a85b5f46ddcac
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4')
}
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.7
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.7'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector === '#' ? [] : selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.7
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.7'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d).prop(d, true)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d).prop(d, false)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target).closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
// Prevent double click on radios, and the double selections (so cancellation) on checkboxes
e.preventDefault()
// The target component still receive the focus
if ($btn.is('input,button')) $btn.trigger('focus')
else $btn.find('input:visible,button:visible').first().trigger('focus')
}
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.7
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.7'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (document !== e.target &&
this.$element[0] !== e.target &&
!this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.7
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
/* jshint latedef: false */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.7'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.7
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
| GM-Connor/KanjiSheets | js/bootstrap.js | JavaScript | gpl-3.0 | 24,744 |
<?
define("HOMESTEAD_PAGE", "Y");
define("NO_MAIN_WRAPPER", "Y");
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
$APPLICATION->SetTitle("Гостевой дом");
?><?
$APPLICATION->IncludeFile(
"inc/tmpl/homestead.php",
array(
"IBLOCK_TYPE" => LANGUAGE_ID,
"IBLOCK_CODE" => "homestead",
"SECTION_CODE" => "guesthouse"
),
array(
"SHOW_BORDER" => false
)
);
?><?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?> | web-izmerenie/usadba-parfenova | homestead/guesthouse/index.php | PHP | gpl-3.0 | 526 |
/*
* SLD Editor - The Open Source Java SLD Editor
*
* Copyright (C) 2018, SCISYS UK Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sldeditor.filter.v2.function.temporal;
import com.sldeditor.filter.v2.expression.ExpressionTypeEnum;
import com.sldeditor.filter.v2.function.FilterBase;
import com.sldeditor.filter.v2.function.FilterConfigInterface;
import com.sldeditor.filter.v2.function.FilterExtendedInterface;
import com.sldeditor.filter.v2.function.FilterName;
import com.sldeditor.filter.v2.function.FilterNameParameter;
import java.util.Date;
import java.util.List;
import org.geotools.filter.temporal.MetByImpl;
import org.opengis.filter.Filter;
import org.opengis.filter.expression.Expression;
/**
* The Class MetBy.
*
* @author Robert Ward (SCISYS)
*/
public class MetBy extends FilterBase implements FilterConfigInterface {
/** The Class MetByExtended. */
public class MetByExtended extends MetByImpl implements FilterExtendedInterface {
/** Instantiates a new after extended. */
public MetByExtended() {
super(null, null);
}
/**
* Instantiates a new after extended.
*
* @param expression1 the expression 1
* @param expression2 the expression 2
*/
public MetByExtended(Expression expression1, Expression expression2) {
super(expression1, expression2);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "[ " + getExpression1() + " MetBy " + getExpression2() + " ]";
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.filter.v2.function.FilterExtendedInterface#getOriginalFilter()
*/
@Override
public Class<?> getOriginalFilter() {
return MetByImpl.class;
}
}
/** Default constructor. */
public MetBy(String category) {
super(category);
}
/**
* Gets the filter configuration.
*
* @return the filter configuration
*/
@Override
public FilterName getFilterConfiguration() {
FilterName filterName = new FilterName("MetBy", Boolean.class);
filterName.addParameter(
new FilterNameParameter("property", ExpressionTypeEnum.PROPERTY, Date.class));
filterName.addParameter(
new FilterNameParameter("datetime", ExpressionTypeEnum.LITERAL, Date.class));
return filterName;
}
/**
* Gets the filter class.
*
* @return the filter class
*/
@Override
public Class<?> getFilterClass() {
return MetByImpl.class;
}
/**
* Creates the filter.
*
* @return the filter
*/
@Override
public Filter createFilter() {
return new MetByExtended();
}
/**
* Creates the filter.
*
* @param parameterList the parameter list
* @return the filter
*/
@Override
public Filter createFilter(List<Expression> parameterList) {
MetByImpl filter = null;
if ((parameterList == null) || (parameterList.size() != 2)) {
filter = new MetByExtended();
} else {
filter = new MetByExtended(parameterList.get(0), parameterList.get(1));
}
return filter;
}
/**
* Creates the logic filter.
*
* @param filterList the filter list
* @return the filter
*/
@Override
public Filter createLogicFilter(List<Filter> filterList) {
// Not supported
return null;
}
}
| robward-scisys/sldeditor | modules/application/src/main/java/com/sldeditor/filter/v2/function/temporal/MetBy.java | Java | gpl-3.0 | 4,262 |
/* Copyright � 2007 Apple Inc. All Rights Reserved.
Disclaimer: IMPORTANT: This Apple software is supplied to you by
Apple Inc. ("Apple") in consideration of your agreement to the
following terms, and your use, installation, modification or
redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use,
install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc.
may be used to endorse or promote products derived from the Apple
Software without specific prior written permission from Apple. Except
as expressly stated in this notice, no other rights or licenses, express
or implied, are granted by Apple herein, including but not limited to
any patent rights that may be infringed by your derivative works or by
other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "audiofiles.h"
#include "CAChannelLayouts.h"
#include <sys/stat.h>
#include <algorithm>
#include "CAXException.h"
#include "CAFilePathUtils.h"
#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__)
#include <AudioUnit/AudioCodec.h>
#else
#include <AudioCodec.h>
#endif
nynex::FileReaderWriter::ConversionParameters::ConversionParameters() :
flags(0)
{
memset(this, 0, sizeof(nynex::FileReaderWriter::ConversionParameters));
output.channels = -1;
output.bitRate = -1;
output.codecQuality = -1;
output.srcQuality = -1;
output.srcComplexity = 0;
output.strategy = -1;
output.primeMethod = -1;
output.creationFlags = 0;
}
nynex::FileReaderWriter::FileReaderWriter() :
mOpenedSourceFile(false),
mCreatedOutputFile(false),
mEncoding(false),
mDecoding(false)
{
mOutName[0] = '\0';
}
nynex::FileReaderWriter::~FileReaderWriter()
{
}
void nynex::FileReaderWriter::GenerateOutputFileName(const char *inputFilePath,
const CAStreamBasicDescription &inputFormat,
const CAStreamBasicDescription &outputFormat,
OSType outputFileType,
char *outName)
{
struct stat sb;
char inputDir[256];
char inputBasename[256];
strcpy(inputDir, dirname((char*)inputFilePath));
const char *infname = basename((char*)inputFilePath);
const char *inext = strrchr(infname, '.');
if (inext == NULL) strcpy(inputBasename, infname);
else {
int n;
memcpy(inputBasename, infname, n = inext - infname);
inputBasename[n] = '\0';
}
CFArrayRef exts;
UInt32 propSize = sizeof(exts);
XThrowIfError(AudioFileGetGlobalInfo(kAudioFileGlobalInfo_ExtensionsForType,
sizeof(OSType), &outputFileType, &propSize, &exts), "generate output file name");
char outputExt[32];
CFStringRef cfext = (CFStringRef)CFArrayGetValueAtIndex(exts, 0);
CFStringGetCString(cfext, outputExt, sizeof(outputExt), kCFStringEncodingUTF8);
CFRelease(exts);
// 1. olddir + oldname + newext
sprintf(outName, "%s/%s.%s", inputDir, inputBasename, outputExt);
#if TARGET_OS_MAC
if (lstat(outName, &sb)) return;
#else
if (stat(outName, &sb)) return;
#endif
if (outputFormat.IsPCM()) {
// If sample rate changed:
// 2. olddir + oldname + "-SR" + newext
if (inputFormat.mSampleRate != outputFormat.mSampleRate && outputFormat.mSampleRate != 0.) {
sprintf(outName, "%s/%s-%.0fk.%s", inputDir, inputBasename, outputFormat.mSampleRate/1000., outputExt);
#if TARGET_OS_MAC
if (lstat(outName, &sb)) return;
#else
if (stat(outName, &sb)) return;
#endif
}
// If bit depth changed:
// 3. olddir + oldname + "-bit" + newext
if (inputFormat.mBitsPerChannel != outputFormat.mBitsPerChannel) {
sprintf(outName, "%s/%s-%ldbit.%s", inputDir, inputBasename, outputFormat.mBitsPerChannel, outputExt);
#if TARGET_OS_MAC
if (lstat(outName, &sb)) return;
#else
if (stat(outName, &sb)) return;
#endif
}
}
// maybe more with channels/layouts? $$$
// now just append digits
for (int i = 1; ; ++i) {
sprintf(outName, "%s/%s-%d.%s", inputDir, inputBasename, i, outputExt);
#if TARGET_OS_MAC
if (lstat(outName, &sb)) return;
#else
if (stat(outName, &sb)) return;
#endif
}
}
void nynex::FileReaderWriter::OpenInputFile()
{
AudioFileID fileid = mParams.input.audioFileID;
if (mParams.input.trackIndex != 0) {
if (fileid == 0) {
CACFURL url = CFURLCreateFromFileSystemRepresentation(NULL, (const Byte *)mParams.input.filePath, strlen(mParams.input.filePath), false);
XThrowIfError(AudioFileOpenURL(url.GetCFObject(), fsRdPerm, 0, &fileid), "Couldn't open input file");
}
XThrowIfError(AudioFileSetProperty(fileid, 'uatk' /*kAudioFilePropertyUseAudioTrack*/, sizeof(mParams.input.trackIndex), &mParams.input.trackIndex), "Couldn't set input file's track index");
}
if (fileid)
mSrcFile.WrapAudioFileID(fileid, false);
else
mSrcFile.Open(mParams.input.filePath);
}
void nynex::FileReaderWriter::OpenOutputFile(const CAStreamBasicDescription &destFormat, CAAudioChannelLayout &destFileLayout)
{
const ConversionParameters ¶ms = mParams;
// output file - need to get this from somewhere else
strcpy(mOutName, params.output.filePath);
// deal with pre-existing output file
struct stat st;
if (stat(mOutName, &st) == 0) {
XThrowIf(!(params.flags & kOpt_OverwriteOutputFile), 1, "overwrite output file");
// not allowed to overwrite
// output file exists - delete it
XThrowIfError(unlink(mOutName), "delete output file");
}
// create the output file
mDestFile.Create(mOutName, params.output.fileType, destFormat, &destFileLayout.Layout(), params.output.creationFlags);
}
void nynex::FileReaderWriter::Input(const char * filename) {
CloseInputFile();
mParams.input.filePath = filename; // object never owns this memory. don't free or malloc
PrepareConverters();
}
void nynex::FileReaderWriter::CloseInputFile() {
try { mSrcFile.Close(); } catch (...) { }
mOpenedSourceFile = false;
}
void nynex::FileReaderWriter::Output(const char * filename) {
CloseOutputFile();
XThrowIf(!mReady, -1, "Output: not prepared");
OpenOutputFile(mDestFormat, mDstFileLayout);
mCreatedOutputFile = true;
mDestFile.SetClientFormat(mDestClientFormat);
mDestFile.SetClientChannelLayout(mDstClientLayout); // must succeed
if (!mDestFormat.IsPCM()) {
// set the codec quality
if (mParams.output.codecQuality != -1) {
if (mParams.flags & kOpt_Verbose)
printf("codec quality = %ld\n", mParams.output.codecQuality);
mDestFile.SetConverterProperty(kAudioConverterCodecQuality, sizeof(UInt32), &mParams.output.codecQuality);
}
// set the bitrate strategy -- called bitrate format in the codecs since it had already shipped
if (mParams.output.strategy != -1) {
if (mParams.flags & kOpt_Verbose)
printf("strategy = %ld\n", mParams.output.strategy);
mDestFile.SetConverterProperty(kAudioCodecBitRateFormat, sizeof(UInt32), &mParams.output.strategy);
}
// set any user defined properties
UInt32 i = 0;
while (mParams.output.userProperty[i].propertyID != 0 && i < kMaxUserProps)
{
if (mParams.flags & kOpt_Verbose)
printf("user property '%4.4s' = %ld\n", (char *)(&mParams.output.userProperty[i].propertyID), mParams.output.userProperty[i].propertyValue);
mDestFile.SetConverterProperty(mParams.output.userProperty[i].propertyID, sizeof(SInt32), &mParams.output.userProperty[i].propertyValue);
++i;
}
// set the bitrate
if (mParams.output.bitRate != -1) {
if (mParams.flags & kOpt_Verbose)
printf("bitrate = %ld\n", mParams.output.bitRate);
mDestFile.SetConverterProperty(kAudioConverterEncodeBitRate, sizeof(UInt32), &mParams.output.bitRate);
}
if (mParams.output.srcComplexity) {
mDestFile.SetConverterProperty('srca'/*kAudioConverterSampleRateConverterComplexity*/, sizeof(UInt32), &mParams.output.srcComplexity, true);
}
// set the SRC quality
if (mParams.output.srcQuality != -1) {
if (mParams.flags & kOpt_Verbose)
printf("SRC quality = %ld\n", mParams.output.srcQuality);
mDestFile.SetConverterProperty(kAudioConverterSampleRateConverterQuality, sizeof(UInt32), &mParams.output.srcQuality);
}
}
}
void nynex::FileReaderWriter::CloseOutputFile() {
try { mDestFile.Close(); } catch (...) { }
mCreatedOutputFile = false;
}
void nynex::FileReaderWriter::Prepare(const nynex::FileReaderWriter::ConversionParameters &_params) {
CloseFiles();
mReady = false;
mParams = _params;
PrepareConverters();
mReady = true;
}
void nynex::FileReaderWriter::PrepareConverters()
{
try {
if (TaggedDecodingFromCAF())
ReadCAFInfo();
OpenInputFile();
mOpenedSourceFile = true;
// get input file's format and channel layout
const CAStreamBasicDescription &srcFormat = mSrcFile.GetFileDataFormat();
mSrcFileLayout = mSrcFile.GetFileChannelLayout();
if (mParams.flags & kOpt_Verbose) {
printf("Input file: %s, %qd frames", mParams.input.filePath ? basename((char*)mParams.input.filePath) : "?",
mSrcFile.GetNumberFrames());
if (mSrcFileLayout.IsValid()) {
printf(", %s", CAChannelLayouts::ConstantToString(mSrcFileLayout.Tag()));
}
printf("\n");
}
mSrcFormat = srcFormat;
// prepare output file's format
mDestFormat = mParams.output.dataFormat;
bool encoding = !mDestFormat.IsPCM();
bool decoding = !srcFormat.IsPCM();
// Don't want to allow this
XThrowIf((!encoding && mDestFormat.mSampleRate == 0.), -1, "destination sample rate not defined");
// on encode, it's OK to have a 0 sample rate; ExtAudioFile will get the SR from the converter and set it on the file.
// on decode or PCM->PCM, a sample rate of 0 is interpreted as using the source sample rate
if (mParams.input.channelLayoutTag != 0) {
XThrowIf(AudioChannelLayoutTag_GetNumberOfChannels(mParams.input.channelLayoutTag)
!= srcFormat.mChannelsPerFrame, -1, "input channel layout has wrong number of channels for file");
mSrcFileLayout = CAAudioChannelLayout(mParams.input.channelLayoutTag);
mSrcFile.SetFileChannelLayout(mSrcFileLayout); // happens
}
// destination channel layout
int outChannels = mParams.output.channels;
if (mParams.output.channelLayoutTag != 0) {
// use the one specified by caller, if any
mDstFileLayout = CAAudioChannelLayout(mParams.output.channelLayoutTag);
} /*else if (srcFileLayout.IsValid()) { // shouldn't allow this
// otherwise, assume the same as the source, if any
destFileLayout = srcFileLayout;
destLayoutDefaulted = true;
}*/
if (mDstFileLayout.IsValid()) {
// the output channel layout specifies the number of output channels
if (outChannels != -1)
XThrowIf((unsigned)outChannels != mDstFileLayout.NumberChannels(), -1,
"output channel layout has wrong number of channels");
else
outChannels = mDstFileLayout.NumberChannels();
}
/* this is totally wrong if (!(mParams.flags & kOpt_NoSanitizeOutputFormat)) {
// adjust the output format's channels; output.channels overrides the channels
// can't rely on source because we have so many possible files
XThrowIf( (outChannels == -1) , -1, "output channels never specified");
if (outChannels > 0) {
mDestFormat.mChannelsPerFrame = outChannels;
mDestFormat.mBytesPerPacket *= outChannels;
mDestFormat.mBytesPerFrame *= outChannels;
}
} */
CAStreamBasicDescription srcClientFormat, destClientFormat;
if (encoding) {
// encoding
mSrcClientFormat = mSrcFormat;
// if we're removing channels, do it on the source file
// (solves problems with mono-only codecs like AMR and is more efficient)
// this bit belongs in Input() only
// destformat needs to be specified in input parameters
if (mSrcFormat.mChannelsPerFrame > mDestFormat.mChannelsPerFrame) {
mSrcClientFormat.ChangeNumberChannels(mDestFormat.mChannelsPerFrame, true);
mSrcFile.SetClientFormat(mSrcClientFormat, NULL);
}
mDestClientFormat = mSrcClientFormat;
// by here, destClientFormat will have a valid sample rate
mDstClientLayout = mSrcFileLayout.IsValid() ? mSrcFileLayout : mDstFileLayout;
} else {
// decoding or PCM->PCM
XThrowIf((mDestFormat.mSampleRate == 0.), -1, "No sample rate defined for output");
mDestClientFormat = mDestFormat;
mSrcClientFormat = mDestFormat;
mSrcClientLayout = mDstFileLayout;
mSrcFile.SetClientFormat(mSrcClientFormat, &mSrcClientLayout);
}
XThrowIf(mSrcClientFormat.mBytesPerPacket == 0, -1, "source client format not PCM");
XThrowIf(mDestClientFormat.mBytesPerPacket == 0, -1, "dest client format not PCM");
// separate, must happen on every new input file
if (mSrcFormat.mSampleRate != 0. && mDestFormat.mSampleRate != 0. && mSrcFormat.mSampleRate != mDestFormat.mSampleRate)
{
// set the SRC quality
if (mParams.output.srcQuality != -1) {
if (mParams.flags & kOpt_Verbose)
printf("SRC quality = %ld\n", mParams.output.srcQuality);
if (!encoding)
mSrcFile.SetConverterProperty(kAudioConverterSampleRateConverterQuality, sizeof(UInt32), &mParams.output.srcQuality);
}
// set the SRC complexity
if (mParams.output.srcComplexity) {
if (mParams.flags & kOpt_Verbose)
printf("SRC complexity = '%4.4s'\n", (char *)(&mParams.output.srcComplexity));
if (!encoding)
mSrcFile.SetConverterProperty('srca'/*kAudioConverterSampleRateConverterComplexity*/, sizeof(UInt32), &mParams.output.srcComplexity, true);
}
}
if (decoding) {
if (mParams.output.primeMethod != -1)
mSrcFile.SetConverterProperty(kAudioConverterPrimeMethod, sizeof(UInt32), &mParams.output.primeMethod);
// set any user defined properties
UInt32 i = 0;
while (mParams.output.userProperty[i].propertyID != 0 && i < kMaxUserProps)
{
if (mParams.flags & kOpt_Verbose)
printf("user property '%4.4s' = %ld\n", (char *)(&mParams.output.userProperty[i].propertyID), mParams.output.userProperty[i].propertyValue);
mSrcFile.SetConverterProperty(mParams.output.userProperty[i].propertyID, sizeof(SInt32), &mParams.output.userProperty[i].propertyValue);
++i;
}
}
if (mParams.output.creationFlags & kAudioFileFlags_DontPageAlignAudioData) {
if (mParams.flags & kOpt_Verbose) {
printf("no filler chunks\n");
}
}
} catch (...) {
mReady = false;
try { mSrcFile.Close(); } catch (...) { } // close in Output() before doing anything else
try { mDestFile.Close(); } catch (...) { } // close in Output() before doing anything else
if (mCreatedOutputFile)
unlink(mOutName); // don't do this ever
throw;
}
}
nynex::FileReaderWriter::ReadBuffer * nynex::FileReaderWriter::GetNextReadBuffer() throw (CAXException) {
// prepare I/O buffers
UInt32 bytesToRead = 0x10000;
UInt32 framesToRead = bytesToRead; // OK, ReadPackets will limit as appropriate
ReadBuffer * out = new ReadBuffer();
out->readBuffer = CABufferList::New("readbuf", mSrcClientFormat);
out->readBuffer->AllocateBuffers(bytesToRead);
out->readPtrs = CABufferList::New("readptrs", mSrcClientFormat);
out->nFrames = framesToRead;
out->readPtrs->SetFrom(out->readBuffer);
mSrcFile.Read(out->nFrames, &out->readPtrs->GetModifiableBufferList());
return out;
}
void nynex::FileReaderWriter::WriteFromBuffer(nynex::FileReaderWriter::ReadBuffer * in) throw (CAXException) {
XThrowIf(in == NULL, -1, "NULL passed into WriteFromBuffer");
mDestFile.Write(in->nFrames, &in->readPtrs->GetModifiableBufferList());
}
#define kMaxFilename 64
struct CAFSourceInfo {
// our private user data chunk -- careful about compiler laying this out!
// big endian
char asbd[40];
UInt32 filetype;
char filename[kMaxFilename];
};
static void ASBD_NtoB(const AudioStreamBasicDescription *infmt, AudioStreamBasicDescription *outfmt)
{
*(UInt64 *)&outfmt->mSampleRate = EndianU64_NtoB(*(UInt64 *)&infmt->mSampleRate);
outfmt->mFormatID = EndianU32_NtoB(infmt->mFormatID);
outfmt->mFormatFlags = EndianU32_NtoB(infmt->mFormatFlags);
outfmt->mBytesPerPacket = EndianU32_NtoB(infmt->mBytesPerPacket);
outfmt->mFramesPerPacket = EndianU32_NtoB(infmt->mFramesPerPacket);
outfmt->mBytesPerFrame = EndianU32_NtoB(infmt->mBytesPerFrame);
outfmt->mChannelsPerFrame = EndianU32_NtoB(infmt->mChannelsPerFrame);
outfmt->mBitsPerChannel = EndianU32_NtoB(infmt->mBitsPerChannel);
}
static void ASBD_BtoN(const AudioStreamBasicDescription *infmt, AudioStreamBasicDescription *outfmt)
{
*(UInt64 *)&outfmt->mSampleRate = EndianU64_BtoN(*(UInt64 *)&infmt->mSampleRate);
outfmt->mFormatID = EndianU32_BtoN(infmt->mFormatID);
outfmt->mFormatFlags = EndianU32_BtoN(infmt->mFormatFlags);
outfmt->mBytesPerPacket = EndianU32_BtoN(infmt->mBytesPerPacket);
outfmt->mFramesPerPacket = EndianU32_BtoN(infmt->mFramesPerPacket);
outfmt->mBytesPerFrame = EndianU32_BtoN(infmt->mBytesPerFrame);
outfmt->mChannelsPerFrame = EndianU32_BtoN(infmt->mChannelsPerFrame);
outfmt->mBitsPerChannel = EndianU32_BtoN(infmt->mBitsPerChannel);
}
void nynex::FileReaderWriter::WriteCAFInfo()
{
AudioFileID afid = 0;
CAFSourceInfo info;
UInt32 size;
try {
CACFURL url = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8 *)mParams.input.filePath, strlen(mParams.input.filePath), false);
XThrowIf(url.GetCFObject() == NULL, -1, "couldn't locate input file");
XThrowIfError(AudioFileOpenURL(url.GetCFObject(), fsRdPerm, 0, &afid), "couldn't open input file");
size = sizeof(AudioFileTypeID);
XThrowIfError(AudioFileGetProperty(afid, kAudioFilePropertyFileFormat, &size, &info.filetype), "couldn't get input file's format");
AudioFileClose(afid);
afid = 0;
url = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8 *)mOutName, strlen(mOutName), false);
XThrowIf(url.GetCFObject() == NULL, -1, "couldn't locate output file");
XThrowIfError(AudioFileOpenURL(url.GetCFObject(), fsRdWrPerm, 0, &afid), "couldn't open output file");
const char *srcFilename = strrchr(mParams.input.filePath, '/');
if (srcFilename++ == NULL) srcFilename = mParams.input.filePath;
ASBD_NtoB(&mSrcFormat, (AudioStreamBasicDescription *)info.asbd);
int namelen = std::min(kMaxFilename-1, (int)strlen(srcFilename));
memcpy(info.filename, srcFilename, namelen);
info.filename[namelen++] = 0;
info.filetype = EndianU32_NtoB(info.filetype);
XThrowIfError(AudioFileSetUserData(afid, 'srcI', 0, offsetof(CAFSourceInfo, filename) + namelen, &info), "couldn't set CAF file's source info chunk");
AudioFileClose(afid);
}
catch (...) {
if (afid)
AudioFileClose(afid);
throw;
}
}
void nynex::FileReaderWriter::ReadCAFInfo()
{
AudioFileID afid = 0;
CAFSourceInfo info;
UInt32 size;
OSStatus err;
try {
CACFURL url = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8 *)mParams.input.filePath, strlen(mParams.input.filePath), false);
XThrowIf(!url.IsValid(), -1, "couldn't locate input file");
XThrowIfError(AudioFileOpenURL(url.GetCFObject(), fsRdPerm, 0, &afid), "couldn't open input file");
size = sizeof(AudioFileTypeID);
XThrowIfError(AudioFileGetProperty(afid, kAudioFilePropertyFileFormat, &size, &info.filetype), "couldn't get input file's format");
if (info.filetype == kAudioFileCAFType) {
size = sizeof(info);
err = AudioFileGetUserData(afid, 'srcI', 0, &size, &info);
if (!err) {
// restore the following from the original file info:
// filetype
// data format
// filename
AudioStreamBasicDescription destfmt;
ASBD_BtoN((AudioStreamBasicDescription *)info.asbd, &destfmt);
mParams.output.dataFormat = destfmt;
mParams.output.fileType = EndianU32_BtoN(info.filetype);
if (mParams.output.filePath == NULL) {
int len = strlen(mParams.input.filePath) + strlen(info.filename) + 2;
char *newname = (char *)malloc(len); // $$$ leaked
const char *dir = dirname((char*)mParams.input.filePath);
if (dir && (dir[0] !='.' && dir[1] != '/'))
sprintf(newname, "%s/%s", dir, info.filename);
else
strcpy(newname, info.filename);
mParams.output.filePath = newname;
mParams.flags = (mParams.flags & ~kOpt_OverwriteOutputFile) | kOpt_NoSanitizeOutputFormat;
}
}
}
AudioFileClose(afid);
}
catch (...) {
if (afid)
AudioFileClose(afid);
throw;
}
}
| mkb218/nynex | src/evolver/audiofiles.cpp | C++ | gpl-3.0 | 22,809 |
package org.freedom.modulos.fnc.business.component.cnab;
import org.freedom.infra.functions.StringFunctions;
import org.freedom.library.business.component.Banco;
import org.freedom.library.business.exceptions.ExceptionCnab;
import org.freedom.modulos.fnc.library.business.compoent.FbnUtil.ETipo;
public class RegTrailer extends Reg {
private String codBanco;
private String loteServico;
private String registroTrailer;
private String conta;
private int qtdLotes;
private int qtdRegistros;
private int qtdConsilacoes;
private int seqregistro;
public RegTrailer() {
setLoteServico( "9999" );
setRegistroTrailer( "9" );
}
public int getSeqregistro() {
return seqregistro;
}
public void setSeqregistro( int seqregistro ) {
this.seqregistro = seqregistro;
}
public String getCodBanco() {
return codBanco;
}
public void setCodBanco( final String codBanco ) {
this.codBanco = codBanco;
}
public String getLoteServico() {
return loteServico;
}
private void setLoteServico( final String loteServico ) {
this.loteServico = loteServico;
}
public int getQtdConsilacoes() {
return qtdConsilacoes;
}
public void setQtdConsilacoes( final int qtdConsilacoes ) {
this.qtdConsilacoes = qtdConsilacoes;
}
public int getQtdLotes() {
return qtdLotes;
}
public void setQtdLotes( final int qtdLotes ) {
this.qtdLotes = qtdLotes;
}
public int getQtdRegistros() {
return qtdRegistros;
}
public void setQtdRegistros( final int qtdRegistros ) {
this.qtdRegistros = qtdRegistros;
}
public String getRegistroTrailer() {
return registroTrailer;
}
private void setRegistroTrailer( final String regTrailer ) {
this.registroTrailer = regTrailer;
}
public String getConta() {
return conta;
}
public void setConta( String codConta ) {
this.conta = codConta;
}
@ Override
public String getLine( String padraocnab ) throws ExceptionCnab {
StringBuilder line = new StringBuilder();
try {
if ( padraocnab.equals( CNAB_240 ) ) {
line.append( format( getCodBanco(), ETipo.$9, 3, 0 ) );
line.append( format( getLoteServico(), ETipo.$9, 4, 0 ) );
line.append( format( getRegistroTrailer(), ETipo.$9, 1, 0 ) );
line.append( StringFunctions.replicate( " ", 9 ) );
line.append( format( getQtdLotes(), ETipo.$9, 6, 0 ) );
line.append( format( getQtdRegistros(), ETipo.$9, 6, 0 ) );
line.append( format( getQtdConsilacoes(), ETipo.$9, 6, 0 ) );
line.append( StringFunctions.replicate( " ", 205 ) );
}
else if ( padraocnab.equals( CNAB_400 ) ) {
line.append( StringFunctions.replicate( "9", 1 ) ); // Posição 001 a 001 - Identificação do registro
if( getCodBanco().equals( Banco.SICRED )){
line.append( "1" );
line.append( getCodBanco() );
line.append( format( getConta(), ETipo.$9, 5, 0 ) );
line.append( StringFunctions.replicate( " ", 384 ) );
} else {
line.append( StringFunctions.replicate( " ", 393 ) ); // Posição 002 a 394 - Branco
}
line.append( format( seqregistro, ETipo.$9, 6, 0 ) ); // Posição 395 a 400 - Nro Sequancial do ultimo registro
}
} catch ( Exception e ) {
throw new ExceptionCnab( "CNAB registro trailer.\nErro ao escrever registro.\n" + e.getMessage() );
}
line.append( (char) 13 );
line.append( (char) 10 );
return line.toString();
}
/*
* (non-Javadoc)
*
* @see org.freedom.modulos.fnc.CnabUtil.Reg#parseLine(java.lang.String)
*/
@ Override
public void parseLine( String line ) throws ExceptionCnab {
try {
if ( line == null ) {
throw new ExceptionCnab( "Linha nula." );
}
else {
setCodBanco( line.substring( 0, 3 ) );
setLoteServico( line.substring( 3, 7 ) );
setRegistroTrailer( line.substring( 7, 8 ) );
setQtdRegistros( line.substring( 17, 23 ).trim().length() > 0 ? Integer.parseInt( line.substring( 17, 23 ).trim() ) : 0 );
setQtdLotes( line.substring( 23, 29 ).trim().length() > 0 ? Integer.parseInt( line.substring( 23, 29 ).trim() ) : 0 );
setQtdRegistros( line.substring( 29, 35 ).trim().length() > 0 ? Integer.parseInt( line.substring( 29, 35 ).trim() ) : 0 );
}
} catch ( Exception e ) {
throw new ExceptionCnab( "CNAB registro trailer.\nErro ao ler registro.\n" + e.getMessage() );
}
}
}
| cams7/erp | freedom/src/main/java/org/freedom/modulos/fnc/business/component/cnab/RegTrailer.java | Java | gpl-3.0 | 4,314 |
/**
* Copyright 2015 IBM Corp. 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.
*
*/
using FullSerializer;
using IBM.Watson.DeveloperCloud.Connection;
using IBM.Watson.DeveloperCloud.Logging;
using IBM.Watson.DeveloperCloud.Utilities;
using System;
using System.IO;
using System.Text;
using UnityEngine;
namespace IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v3
{
/// <summary>
/// This class wraps the Personality Insights service.
/// <a href="http://www.ibm.com/watson/developercloud/personality-insights.html">Personality Insights Service</a>
/// </summary>
public class PersonalityInsights : IWatsonService
{
#region Private Data
private const string ServiceId = "PersonalityInsightsV3";
private fsSerializer _serializer = new fsSerializer();
private Credentials _credentials = null;
private string _url = "https://gateway.watsonplatform.net/personality-insights/api";
private string _versionDate;
#endregion
#region Public Properties
/// <summary>
/// Gets and sets the endpoint URL for the service.
/// </summary>
public string Url
{
get { return _url; }
set { _url = value; }
}
/// <summary>
/// Gets and sets the versionDate of the service.
/// </summary>
public string VersionDate
{
get
{
if (string.IsNullOrEmpty(_versionDate))
throw new ArgumentNullException("VersionDate cannot be null. Use a VersionDate formatted as `YYYY-MM-DD`");
return _versionDate;
}
set { _versionDate = value; }
}
/// <summary>
/// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined.
/// </summary>
public Credentials Credentials
{
get { return _credentials; }
set
{
_credentials = value;
if (!string.IsNullOrEmpty(_credentials.Url))
{
_url = _credentials.Url;
}
}
}
#endregion
#region Constructor
public PersonalityInsights(Credentials credentials)
{
if (credentials.HasCredentials() || credentials.HasAuthorizationToken())
{
Credentials = credentials;
}
else
{
throw new WatsonException("Please provide a username and password or authorization token to use the Personality Insights service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials");
}
}
#endregion
#region Profile
private const string ProfileEndpoint = "/v3/profile";
public delegate void OnGetProfile(Profile profile, string data);
public bool GetProfile(OnGetProfile callback, string source,
string contentType = ContentType.TextPlain,
string contentLanguage = ContentLanguage.English,
string accept = ContentType.ApplicationJson,
string acceptLanguage = AcceptLanguage.English,
bool raw_scores = false,
bool csv_headers = false,
bool consumption_preferences = false,
string version = PersonalityInsightsVersion.Version,
string data = default(string))
{
if (callback == null)
throw new ArgumentNullException("callback");
if (string.IsNullOrEmpty(source))
throw new ArgumentNullException("A JSON or Text source is required for GetProfile!");
RESTConnector connector = RESTConnector.GetConnector(Credentials, ProfileEndpoint);
if (connector == null)
return false;
GetProfileRequest req = new GetProfileRequest();
req.Source = source;
req.Callback = callback;
req.Data = data;
req.OnResponse = GetProfileResponse;
req.Parameters["raw_scores"] = raw_scores.ToString();
req.Parameters["csv_headers"] = csv_headers.ToString();
req.Parameters["consumption_preferences"] = consumption_preferences.ToString();
req.Parameters["version"] = version;
req.Headers["Content-Type"] = contentType;
req.Headers["Content-Language"] = contentLanguage;
req.Headers["Accept"] = accept;
req.Headers["Accept-Language"] = acceptLanguage;
if (source.StartsWith(Application.dataPath))
{
string jsonData = default(string);
jsonData = File.ReadAllText(source);
req.Send = System.Text.Encoding.UTF8.GetBytes(jsonData);
}
else
{
req.Send = System.Text.Encoding.UTF8.GetBytes(source);
}
return connector.Send(req);
}
/// <summary>
/// Get profile request.
/// </summary>
public class GetProfileRequest : RESTConnector.Request
{
/// <summary>
/// The source string.
/// </summary>
public string Source { get; set; }
/// <summary>
/// Custom data.
/// </summary>
public string Data { get; set; }
/// <summary>
/// The callback.
/// </summary>
public OnGetProfile Callback { get; set; }
}
private void GetProfileResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
Profile response = new Profile();
fsData data = null;
if (resp.Success)
{
try
{
fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
object obj = response;
r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
}
catch (Exception e)
{
Log.Error("PersonalityInsights", "GetProfileResponse Exception: {0}", e.ToString());
resp.Success = false;
}
}
string customData = ((GetProfileRequest)req).Data;
if (((GetProfileRequest)req).Callback != null)
((GetProfileRequest)req).Callback(resp.Success ? response : null, !string.IsNullOrEmpty(customData) ? customData : data.ToString());
}
#endregion
#region IWatsonService implementation
public string GetServiceID()
{
return ServiceId;
}
#endregion
}
} | aparant777/SimpleProjectLineups | SampleSpeechToTextConverter/Assets/Watson/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs | C# | gpl-3.0 | 7,582 |
"""
Django settings for spa_movies project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ss!@cvdm$38bkbuk5hw!_csg(_@kfl3_)3vi$!@_2q(f!l1q!q'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['davgibbs.pythonanywhere.com', '127.0.0.1']
SECURE_SSL_REDIRECT = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'movies.apps.MoviesConfig',
'rest_framework_swagger',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'spa_movies.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'spa_movies.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
# User uploaded files "Media"
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Expire session after 3 hours
SESSION_COOKIE_AGE = 60 * 60 * 3
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
)
}
| davgibbs/movies-spa | apps/spa_movies/settings.py | Python | gpl-3.0 | 3,710 |
/*
* Symphony - A modern community (forum/SNS/blog) platform written in Java.
* Copyright (C) 2012-2017, b3log.org & hacpai.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.b3log.symphony.processor;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.User;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.Before;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.util.Requests;
import org.b3log.symphony.model.*;
import org.b3log.symphony.processor.advice.CSRFCheck;
import org.b3log.symphony.processor.advice.LoginCheck;
import org.b3log.symphony.processor.advice.PermissionCheck;
import org.b3log.symphony.processor.advice.validate.ClientCommentAddValidation;
import org.b3log.symphony.processor.advice.validate.CommentAddValidation;
import org.b3log.symphony.service.*;
import org.json.JSONObject;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* Comment processor.
* <p>
* <ul>
* <li>Adds a comment (/comment) <em>locally</em>, POST</li>
* <li>Adds a comment (/solo/comment) <em>remotely</em>, POST</li>
* <li>Thanks a comment (/comment/thank), POST</li>
* <li>Gets a comment's replies (/comment/replies), GET </li>
* </ul>
* </p>
* <p>
* The '<em>locally</em>' means user post a comment on Symphony directly rather than receiving a comment from externally
* (for example Solo).
* </p>
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.5.1.13, Jan 21, 2017
* @since 0.2.0
*/
@RequestProcessor
public class CommentProcessor {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(CommentProcessor.class.getName());
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Comment management service.
*/
@Inject
private CommentMgmtService commentMgmtService;
/**
* Comment query service.
*/
@Inject
private CommentQueryService commentQueryService;
/**
* Client management service.
*/
@Inject
private ClientMgmtService clientMgmtService;
/**
* Client query service.
*/
@Inject
private ClientQueryService clientQueryService;
/**
* Article query service.
*/
@Inject
private ArticleQueryService articleQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Reward query service.
*/
@Inject
private RewardQueryService rewardQueryService;
/**
* Gets a comment's original comment.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/comment/original", method = HTTPRequestMethod.POST)
public void getOriginalComment(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
final String commentId = requestJSONObject.optString(Comment.COMMENT_T_ID);
int commentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE);
int avatarViewMode = UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL;
final JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null != currentUser) {
avatarViewMode = currentUser.optInt(UserExt.USER_AVATAR_VIEW_MODE);
}
final JSONObject originalCmt = commentQueryService.getOriginalComment(avatarViewMode, commentViewMode, commentId);
// Fill thank
final String originalCmtId = originalCmt.optString(Keys.OBJECT_ID);
if (null != currentUser) {
originalCmt.put(Common.REWARDED,
rewardQueryService.isRewarded(currentUser.optString(Keys.OBJECT_ID),
originalCmtId, Reward.TYPE_C_COMMENT));
}
originalCmt.put(Common.REWARED_COUNT, rewardQueryService.rewardedCount(originalCmtId, Reward.TYPE_C_COMMENT));
context.renderJSON(true).renderJSONValue(Comment.COMMENT_T_REPLIES, (Object) originalCmt);
}
/**
* Gets a comment's replies.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/comment/replies", method = HTTPRequestMethod.POST)
public void getReplies(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
final String commentId = requestJSONObject.optString(Comment.COMMENT_T_ID);
int commentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE);
int avatarViewMode = UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL;
final JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null != currentUser) {
avatarViewMode = currentUser.optInt(UserExt.USER_AVATAR_VIEW_MODE);
}
final List<JSONObject> replies = commentQueryService.getReplies(avatarViewMode, commentViewMode, commentId);
// Fill reply thank
for (final JSONObject reply : replies) {
final String replyId = reply.optString(Keys.OBJECT_ID);
if (null != currentUser) {
reply.put(Common.REWARDED,
rewardQueryService.isRewarded(currentUser.optString(Keys.OBJECT_ID),
replyId, Reward.TYPE_C_COMMENT));
}
reply.put(Common.REWARED_COUNT, rewardQueryService.rewardedCount(replyId, Reward.TYPE_C_COMMENT));
}
context.renderJSON(true).renderJSONValue(Comment.COMMENT_T_REPLIES, (Object) replies);
}
/**
* Adds a comment locally.
* <p>
* The request json object (a comment):
* <pre>
* {
* "articleId": "",
* "commentContent": "",
* "commentAnonymous": boolean,
* "commentOriginalCommentId": "", // optional
* "userCommentViewMode": int
* }
* </pre>
* </p>
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws IOException io exception
* @throws ServletException servlet exception
*/
@RequestProcessing(value = "/comment", method = HTTPRequestMethod.POST)
@Before(adviceClass = {CSRFCheck.class, CommentAddValidation.class, PermissionCheck.class})
public void addComment(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
context.renderJSON();
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final String articleId = requestJSONObject.optString(Article.ARTICLE_T_ID);
final String commentContent = requestJSONObject.optString(Comment.COMMENT_CONTENT);
final String commentOriginalCommentId = requestJSONObject.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID);
final int commentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE);
final String ip = Requests.getRemoteAddr(request);
final String ua = request.getHeader("User-Agent");
final boolean isAnonymous = requestJSONObject.optBoolean(Comment.COMMENT_ANONYMOUS, false);
final JSONObject comment = new JSONObject();
comment.put(Comment.COMMENT_CONTENT, commentContent);
comment.put(Comment.COMMENT_ON_ARTICLE_ID, articleId);
comment.put(UserExt.USER_COMMENT_VIEW_MODE, commentViewMode);
comment.put(Comment.COMMENT_IP, "");
if (StringUtils.isNotBlank(ip)) {
comment.put(Comment.COMMENT_IP, ip);
}
comment.put(Comment.COMMENT_UA, "");
if (StringUtils.isNotBlank(ua)) {
comment.put(Comment.COMMENT_UA, ua);
}
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, commentOriginalCommentId);
try {
final JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null == currentUser) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
final String currentUserName = currentUser.optString(User.USER_NAME);
final JSONObject article = articleQueryService.getArticle(articleId);
final String articleContent = article.optString(Article.ARTICLE_CONTENT);
final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId);
final String articleAuthorName = articleAuthor.optString(User.USER_NAME);
final Set<String> userNames = userQueryService.getUserNames(articleContent);
if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
&& !articleAuthorName.equals(currentUserName)) {
boolean invited = false;
for (final String userName : userNames) {
if (userName.equals(currentUserName)) {
invited = true;
break;
}
}
if (!invited) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
comment.put(Comment.COMMENT_AUTHOR_ID, currentUser.optString(Keys.OBJECT_ID));
comment.put(Comment.COMMENT_T_COMMENTER, currentUser);
comment.put(Comment.COMMENT_ANONYMOUS, isAnonymous
? Comment.COMMENT_ANONYMOUS_C_ANONYMOUS : Comment.COMMENT_ANONYMOUS_C_PUBLIC);
commentMgmtService.addComment(comment);
context.renderTrueResult();
} catch (final ServiceException e) {
context.renderMsg(e.getMessage());
}
}
/**
* Adds a comment remotely.
* <p>
* The request json object (a comment):
* <pre>
* {
* "comment": {
* "commentId": "", // client comment id
* "articleId": "",
* "commentContent": "",
* "commentAuthorName": "", // optional, 'default commenter'
* "commentAuthorEmail": "" // optional, 'default commenter'
* },
* "clientName": "",
* "clientVersion": "",
* "clientHost": "",
* "clientRuntimeEnv": "" // LOCAL
* "clientAdminEmail": "",
* "userB3Key": ""
* }
* </pre>
* </p>
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/solo/comment", method = HTTPRequestMethod.POST)
@Before(adviceClass = ClientCommentAddValidation.class)
public void addCommentFromSolo(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
LOGGER.log(Level.DEBUG, "Adds a comment from solo");
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final JSONObject originalCmt = requestJSONObject.optJSONObject(Comment.COMMENT);
final JSONObject article = (JSONObject) request.getAttribute(Article.ARTICLE);
final String ip = Requests.getRemoteAddr(request);
final String ua = request.getHeader("User-Agent");
final JSONObject defaultCommenter = userQueryService.getDefaultCommenter();
final JSONObject comment = new JSONObject();
comment.put(Comment.COMMENT_AUTHOR_ID, defaultCommenter.optString(Keys.OBJECT_ID));
comment.put(Comment.COMMENT_CLIENT_COMMENT_ID, originalCmt.optString(Comment.COMMENT_T_ID));
comment.put(Comment.COMMENT_CONTENT, originalCmt.optString(Comment.COMMENT_CONTENT));
comment.put(Comment.COMMENT_ON_ARTICLE_ID, article.optString(Keys.OBJECT_ID));
comment.put(Comment.COMMENT_T_COMMENTER, defaultCommenter);
comment.put(Comment.COMMENT_IP, "");
if (StringUtils.isNotBlank(ip)) {
comment.put(Comment.COMMENT_IP, ip);
}
comment.put(Comment.COMMENT_UA, "");
if (StringUtils.isNotBlank(ua)) {
comment.put(Comment.COMMENT_UA, ua);
}
comment.put(Comment.COMMENT_T_AUTHOR_NAME, originalCmt.optString(Comment.COMMENT_T_AUTHOR_NAME));
commentMgmtService.addComment(comment);
// Updates client record
final String clientAdminEmail = requestJSONObject.optString(Client.CLIENT_ADMIN_EMAIL);
final String clientName = requestJSONObject.optString(Client.CLIENT_NAME);
final String clientVersion = requestJSONObject.optString(Client.CLIENT_VERSION);
final String clientHost = requestJSONObject.optString(Client.CLIENT_HOST);
final String clientRuntimeEnv = requestJSONObject.optString(Client.CLIENT_RUNTIME_ENV);
JSONObject client = clientQueryService.getClientByAdminEmail(clientAdminEmail);
if (null == client) {
client = new JSONObject();
client.put(Client.CLIENT_ADMIN_EMAIL, clientAdminEmail);
client.put(Client.CLIENT_HOST, clientHost);
client.put(Client.CLIENT_NAME, clientName);
client.put(Client.CLIENT_RUNTIME_ENV, clientRuntimeEnv);
client.put(Client.CLIENT_VERSION, clientVersion);
client.put(Client.CLIENT_LATEST_ADD_COMMENT_TIME, System.currentTimeMillis());
client.put(Client.CLIENT_LATEST_ADD_ARTICLE_TIME, 0L);
clientMgmtService.addClient(client);
} else {
client.put(Client.CLIENT_ADMIN_EMAIL, clientAdminEmail);
client.put(Client.CLIENT_HOST, clientHost);
client.put(Client.CLIENT_NAME, clientName);
client.put(Client.CLIENT_RUNTIME_ENV, clientRuntimeEnv);
client.put(Client.CLIENT_VERSION, clientVersion);
client.put(Client.CLIENT_LATEST_ADD_COMMENT_TIME, System.currentTimeMillis());
clientMgmtService.updateClient(client);
}
LOGGER.log(Level.DEBUG, "Added a comment from solo");
}
}
| anvarzkr/symphony | src/main/java/org/b3log/symphony/processor/CommentProcessor.java | Java | gpl-3.0 | 15,876 |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using MixERP.Net.EntityParser;
using MixERP.Net.Framework;
using PetaPoco;
namespace MixERP.Net.Schemas.Office.Data
{
public interface IStoreRepository
{
/// <summary>
/// Counts the number of Store in IStoreRepository.
/// </summary>
/// <returns>Returns the count of IStoreRepository.</returns>
long Count();
/// <summary>
/// Returns all instances of Store.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of Store.</returns>
IEnumerable<MixERP.Net.Entities.Office.Store> GetAll();
/// <summary>
/// Returns all instances of Store to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of Store.</returns>
IEnumerable<dynamic> Export();
/// <summary>
/// Returns a single instance of the Store against storeId.
/// </summary>
/// <param name="storeId">The column "store_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of Store.</returns>
MixERP.Net.Entities.Office.Store Get(int storeId);
/// <summary>
/// Returns multiple instances of the Store against storeIds.
/// </summary>
/// <param name="storeIds">Array of column "store_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of Store.</returns>
IEnumerable<MixERP.Net.Entities.Office.Store> Get(int[] storeIds);
/// <summary>
/// Custom fields are user defined form elements for IStoreRepository.
/// </summary>
/// <returns>Returns an enumerable custom field collection for Store.</returns>
IEnumerable<PetaPoco.CustomField> GetCustomFields(string resourceId);
/// <summary>
/// Displayfields provide a minimal name/value context for data binding Store.
/// </summary>
/// <returns>Returns an enumerable name and value collection for Store.</returns>
IEnumerable<DisplayField> GetDisplayFields();
/// <summary>
/// Inserts the instance of Store class to IStoreRepository.
/// </summary>
/// <param name="store">The instance of Store class to insert or update.</param>
/// <param name="customFields">The custom field collection.</param>
object AddOrEdit(dynamic store, List<EntityParser.CustomField> customFields);
/// <summary>
/// Inserts the instance of Store class to IStoreRepository.
/// </summary>
/// <param name="store">The instance of Store class to insert.</param>
object Add(dynamic store);
/// <summary>
/// Inserts or updates multiple instances of Store class to IStoreRepository.;
/// </summary>
/// <param name="stores">List of Store class to import.</param>
/// <returns>Returns list of inserted object ids.</returns>
List<object> BulkImport(List<ExpandoObject> stores);
/// <summary>
/// Updates IStoreRepository with an instance of Store class against the primary key value.
/// </summary>
/// <param name="store">The instance of Store class to update.</param>
/// <param name="storeId">The value of the column "store_id" which will be updated.</param>
void Update(dynamic store, int storeId);
/// <summary>
/// Deletes Store from IStoreRepository against the primary key value.
/// </summary>
/// <param name="storeId">The value of the column "store_id" which will be deleted.</param>
void Delete(int storeId);
/// <summary>
/// Produces a paginated result of 10 Store classes.
/// </summary>
/// <returns>Returns the first page of collection of Store class.</returns>
IEnumerable<MixERP.Net.Entities.Office.Store> GetPaginatedResult();
/// <summary>
/// Produces a paginated result of 10 Store classes.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of Store class.</returns>
IEnumerable<MixERP.Net.Entities.Office.Store> GetPaginatedResult(long pageNumber);
List<EntityParser.Filter> GetFilters(string catalog, string filterName);
/// <summary>
/// Performs a filtered count on IStoreRepository.
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of Store class using the filter.</returns>
long CountWhere(List<EntityParser.Filter> filters);
/// <summary>
/// Performs a filtered pagination against IStoreRepository producing result of 10 items.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns collection of Store class.</returns>
IEnumerable<MixERP.Net.Entities.Office.Store> GetWhere(long pageNumber, List<EntityParser.Filter> filters);
/// <summary>
/// Performs a filtered count on IStoreRepository.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of Store class using the filter.</returns>
long CountFiltered(string filterName);
/// <summary>
/// Gets a filtered result of IStoreRepository producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns collection of Store class.</returns>
IEnumerable<MixERP.Net.Entities.Office.Store> GetFiltered(long pageNumber, string filterName);
}
} | gguruss/mixerp | src/Libraries/DAL/Office/IStoreRepository.cs | C# | gpl-3.0 | 6,206 |
# -*- coding: utf-8 -*-
from module.plugins.internal.XFSHoster import XFSHoster, create_getInfo
class SendmywayCom(XFSHoster):
__name__ = "SendmywayCom"
__type__ = "hoster"
__version__ = "0.04"
__pattern__ = r'http://(?:www\.)?sendmyway\.com/\w{12}'
__description__ = """SendMyWay hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("zoidberg", "zoidberg@mujmail.cz")]
HOSTER_DOMAIN = "sendmyway.com"
NAME_PATTERN = r'<p class="file-name" ><.*?>\s*(?P<N>.+)'
SIZE_PATTERN = r'<small>\((?P<S>\d+) bytes\)</small>'
getInfo = create_getInfo(SendmywayCom)
| sebdelsol/pyload | module/plugins/hoster/SendmywayCom.py | Python | gpl-3.0 | 619 |
// Copyright (c) 2012 Oliver Lau <ola@ct.de>, Heise Zeitschriften Verlag
// All rights reserved.
#include "util.h"
#include <qmath.h>
QRgb rgbFromWaveLength(qreal wave)
{
qreal r = 0, g = 0, b = 0;
if (wave >= 380 && wave <= 440) {
r = -(wave - 440) / (440 - 380);
b = 1;
}
else if (wave >= 440 && wave <= 490) {
g = (wave - 440) / (490 - 440);
b = 1;
}
else if (wave >= 490 && wave <= 510) {
g = 1;
b = -(wave - 510) / (510 - 490);
}
else if (wave >= 510 && wave <= 580) {
r = (wave - 510) / (580 - 510);
g = 1;
}
else if (wave >= 580 && wave <= 645) {
r = 1;
g = -(wave - 645) / (645 - 580);
}
else if (wave >= 645 && wave <= 780) {
r = 1;
}
qreal s = 1;
if (wave > 700)
s = 0.3 + 0.7 * (780 - wave) / (780 - 700);
else if (wave < 420)
s = 0.3 + 0.7 * (wave - 380) / (420 - 380);
r = qPow(r * s, 0.8);
g = qPow(g * s, 0.8);
b = qPow(b * s, 0.8);
return qRgb(int(r * 255), int(g * 255), int(b * 255));
}
QScriptValue rgbFromWaveLength(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 1)
return QScriptValue::UndefinedValue;
QRgb rgb = rgbFromWaveLength(context->argument(0).toNumber());
QScriptValue result = engine->newArray(3);
result.setProperty(0, qRed(rgb));
result.setProperty(1, qGreen(rgb));
result.setProperty(2, qBlue(rgb));
return result;
}
| ola-ct/mikromosaik | util.cpp | C++ | gpl-3.0 | 1,512 |
/*******************************************************************************
* Copyright (c) 2019 German Federal Institute for Risk Assessment (BfR)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* Department Biological Safety - BfR
*******************************************************************************/
package de.bund.bfr.knime.pmmlite.views;
import java.util.Arrays;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import de.bund.bfr.knime.pmmlite.views.chart.ChartSelectionPanel;
public class SingleSelectionViewSettings extends SingleDimensionViewSettings {
private static final String CFG_SELECTED_ID = "SelectedID";
protected String selectedID;
public SingleSelectionViewSettings() {
selectedID = null;
}
@Override
public void load(NodeSettingsRO settings) {
super.load(settings);
try {
selectedID = settings.getString(CFG_SELECTED_ID);
} catch (InvalidSettingsException e) {
}
}
@Override
public void save(NodeSettingsWO settings) throws InvalidSettingsException {
super.save(settings);
settings.addString(CFG_SELECTED_ID, selectedID);
}
@Override
public void setFromSelectionPanel(ChartSelectionPanel selectionPanel) {
super.setFromSelectionPanel(selectionPanel);
if (!selectionPanel.getSelectedIDs().isEmpty()) {
selectedID = selectionPanel.getSelectedIDs().get(0);
} else {
selectedID = null;
}
}
@Override
public void setToSelectionPanel(ChartSelectionPanel selectionPanel) {
super.setToSelectionPanel(selectionPanel);
if (getSelectedID() != null) {
selectionPanel.setSelectedIDs(Arrays.asList(selectedID));
}
}
public String getSelectedID() {
return selectedID;
}
public void setSelectedID(String selectedID) {
this.selectedID = selectedID;
}
}
| SiLeBAT/BfROpenLab | de.bund.bfr.knime.pmmlite.views/src/de/bund/bfr/knime/pmmlite/views/SingleSelectionViewSettings.java | Java | gpl-3.0 | 2,555 |
#include "stdafx.h"
using namespace System::Linq;
namespace JsPie { namespace Scripting { namespace V8 {
GlobalCallbacks::GlobalCallbacks(IScriptEnvironment^ environment)
{
_pConsoleCallbacks = new ConsoleCallbacks();
auto controllerIds = Enumerable::ToList(Enumerable::Union(
environment->ControllerDirectory->InputControllers->Keys,
environment->ControllerDirectory->OutputControllers->Keys));
auto count = controllerIds->Count;
_pControllerCallbacks = new ControllerCallbacks*[count + 1];
for (auto i = 0; i < count; i++)
{
auto controllerId = controllerIds[i];
ControllerInfo^ inputController;
if (!environment->ControllerDirectory->InputControllers->TryGetValue(controllerId, inputController))
inputController = nullptr;
ControllerInfo^ outputController;
if (!environment->ControllerDirectory->OutputControllers->TryGetValue(controllerId, outputController))
outputController = nullptr;
_pControllerCallbacks[i] = new ControllerCallbacks(inputController, outputController);
}
_pControllerCallbacks[count] = NULL;
}
GlobalCallbacks::~GlobalCallbacks()
{
delete _pConsoleCallbacks;
auto ppController = _pControllerCallbacks;
while (true)
{
auto pController = *ppController++;
if (pController == NULL)
break;
delete pController;
}
delete _pControllerCallbacks;
}
v8::Local<v8::ObjectTemplate> GlobalCallbacks::CreateTemplate(v8::Isolate* pIsolate)
{
v8::EscapableHandleScope handle_scope(pIsolate);
auto global = v8::ObjectTemplate::New(pIsolate);
auto ppController = _pControllerCallbacks;
while (true)
{
auto pController = *ppController++;
if (pController == NULL)
break;
auto oControllerInfo = pController->GetInputControllerInfo();
if (oControllerInfo == nullptr)
oControllerInfo = pController->GetOutputControllerInfo();
global->Set(ToV8String(pIsolate, oControllerInfo->Name), pController->CreateTemplate(pIsolate));
}
global->Set(v8::String::NewFromUtf8(pIsolate, "console"), _pConsoleCallbacks->CreateTemplate(pIsolate));
return handle_scope.Escape(global);
}
} } } | deftflux/JsPie | src/JsPie.Scripting.V8/GlobalCallbacks.cpp | C++ | gpl-3.0 | 2,120 |
namespace WhatIsYourStack.Responses
{
public class RegisterResponse
{
}
} | markwalsh-liverpool/whatisyourstack2 | server/WhatIsYourStack/Responses/RegisterResponse.cs | C# | gpl-3.0 | 85 |
Bitrix 16.5 Business Demo = a26b8f1f26e37861347f2caa61b9b274
| gohdan/DFC | known_files/hashes/bitrix/modules/iblock/classes/general/iblockpropresult.php | PHP | gpl-3.0 | 61 |
package de.cubeisland.games.dhbw.entity.action;
import de.cubeisland.games.dhbw.character.PlayerCharacter;
import de.cubeisland.games.dhbw.entity.CardAction;
/**
* This class represents the action that only increases the Math skill by a given value.
*
* @author Andreas Geis
*/
public class MathReward implements CardAction {
public void apply(PlayerCharacter character, int value) {
character.setMath(character.getMath() + value);
}
public void unapply(PlayerCharacter character, int value) {
}
}
| Banana4Life/Exmatrikulation | core/src/de/cubeisland/games/dhbw/entity/action/MathReward.java | Java | gpl-3.0 | 532 |
/*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
* MARLO is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
package org.cgiar.ccafs.marlo.data.manager.impl;
import org.cgiar.ccafs.marlo.data.dao.ReportSynthesisKeyPartnershipCollaborationPmuDAO;
import org.cgiar.ccafs.marlo.data.manager.ReportSynthesisKeyPartnershipCollaborationPmuManager;
import org.cgiar.ccafs.marlo.data.model.ReportSynthesisKeyPartnershipCollaborationPmu;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
/**
* @author CCAFS
*/
@Named
public class ReportSynthesisKeyPartnershipCollaborationPmuManagerImpl implements ReportSynthesisKeyPartnershipCollaborationPmuManager {
private ReportSynthesisKeyPartnershipCollaborationPmuDAO reportSynthesisKeyPartnershipCollaborationPmuDAO;
// Managers
@Inject
public ReportSynthesisKeyPartnershipCollaborationPmuManagerImpl(ReportSynthesisKeyPartnershipCollaborationPmuDAO reportSynthesisKeyPartnershipCollaborationPmuDAO) {
this.reportSynthesisKeyPartnershipCollaborationPmuDAO = reportSynthesisKeyPartnershipCollaborationPmuDAO;
}
@Override
public void deleteReportSynthesisKeyPartnershipCollaborationPmu(long reportSynthesisKeyPartnershipCollaborationPmuId) {
reportSynthesisKeyPartnershipCollaborationPmuDAO.deleteReportSynthesisKeyPartnershipCollaborationPmu(reportSynthesisKeyPartnershipCollaborationPmuId);
}
@Override
public boolean existReportSynthesisKeyPartnershipCollaborationPmu(long reportSynthesisKeyPartnershipCollaborationPmuID) {
return reportSynthesisKeyPartnershipCollaborationPmuDAO.existReportSynthesisKeyPartnershipCollaborationPmu(reportSynthesisKeyPartnershipCollaborationPmuID);
}
@Override
public List<ReportSynthesisKeyPartnershipCollaborationPmu> findAll() {
return reportSynthesisKeyPartnershipCollaborationPmuDAO.findAll();
}
@Override
public ReportSynthesisKeyPartnershipCollaborationPmu getReportSynthesisKeyPartnershipCollaborationPmuById(long reportSynthesisKeyPartnershipCollaborationPmuID) {
return reportSynthesisKeyPartnershipCollaborationPmuDAO.find(reportSynthesisKeyPartnershipCollaborationPmuID);
}
@Override
public ReportSynthesisKeyPartnershipCollaborationPmu saveReportSynthesisKeyPartnershipCollaborationPmu(ReportSynthesisKeyPartnershipCollaborationPmu reportSynthesisKeyPartnershipCollaborationPmu) {
return reportSynthesisKeyPartnershipCollaborationPmuDAO.save(reportSynthesisKeyPartnershipCollaborationPmu);
}
}
| CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ReportSynthesisKeyPartnershipCollaborationPmuManagerImpl.java | Java | gpl-3.0 | 3,312 |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections;
namespace ICSharpCode.Core
{
/// <summary>
/// Creates associations between file types or node types in the project browser and
/// icons in the resource service.
/// </summary>
/// <attribute name="resource" use="required">
/// The name of a bitmap resource in the resource service.
/// </attribute>
/// <attribute name="language">
/// This attribute is specified when a project icon association should be created.
/// It specifies the language of the project types that use the icon.
/// </attribute>
/// <attribute name="extensions">
/// This attribute is specified when a file icon association should be created.
/// It specifies the semicolon-separated list of file types that use the icon.
/// </attribute>
/// <usage>Only in /Workspace/Icons</usage>
/// <returns>
/// An IconDescriptor object that exposes the attributes.
/// </returns>
public class IconDoozer : IDoozer
{
/// <summary>
/// Gets if the doozer handles codon conditions on its own.
/// If this property return false, the item is excluded when the condition is not met.
/// </summary>
public bool HandleConditions {
get {
return false;
}
}
public object BuildItem(BuildItemArgs args)
{
return new IconDescriptor(args.Codon);
}
}
}
| hazama-yuinyan/BVEEditor | Src/Main/Core/Project/Src/AddInTree/AddIn/DefaultDoozers/Icon/IconDoozer.cs | C# | gpl-3.0 | 1,495 |
from __future__ import unicode_literals
from frappe import _
app_name = "erpnext"
app_title = "ERPNext"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = """ERP made simple"""
app_icon = "fa fa-th"
app_color = "#e74c3c"
app_email = "info@erpnext.com"
app_license = "GNU General Public License (v3)"
source_link = "https://github.com/frappe/erpnext"
develop_version = '12.x.x-develop'
# error_report_email = "support@erpnext.com"
app_include_js = "assets/js/erpnext.min.js"
app_include_css = "assets/css/erpnext.css"
web_include_js = "assets/js/erpnext-web.min.js"
web_include_css = "assets/css/erpnext-web.css"
doctype_js = {
"Communication": "public/js/communication.js",
"Event": "public/js/event.js"
}
welcome_email = "erpnext.setup.utils.welcome_email"
# setup wizard
setup_wizard_requires = "assets/erpnext/js/setup_wizard.js"
setup_wizard_stages = "erpnext.setup.setup_wizard.setup_wizard.get_setup_stages"
setup_wizard_test = "erpnext.setup.setup_wizard.test_setup_wizard.run_setup_wizard_test"
before_install = "erpnext.setup.install.check_setup_wizard_not_completed"
after_install = "erpnext.setup.install.after_install"
boot_session = "erpnext.startup.boot.boot_session"
notification_config = "erpnext.startup.notifications.get_notification_config"
get_help_messages = "erpnext.utilities.activation.get_help_messages"
get_user_progress_slides = "erpnext.utilities.user_progress.get_user_progress_slides"
update_and_get_user_progress = "erpnext.utilities.user_progress_utils.update_default_domain_actions_and_get_state"
on_session_creation = "erpnext.shopping_cart.utils.set_cart_count"
on_logout = "erpnext.shopping_cart.utils.clear_cart_count"
treeviews = ['Account', 'Cost Center', 'Warehouse', 'Item Group', 'Customer Group', 'Sales Person', 'Territory', 'Assessment Group']
# website
update_website_context = "erpnext.shopping_cart.utils.update_website_context"
my_account_context = "erpnext.shopping_cart.utils.update_my_account_context"
email_append_to = ["Job Applicant", "Lead", "Opportunity", "Issue"]
calendars = ["Task", "Work Order", "Leave Application", "Sales Order", "Holiday List", "Course Schedule"]
domains = {
'Agriculture': 'erpnext.domains.agriculture',
'Distribution': 'erpnext.domains.distribution',
'Education': 'erpnext.domains.education',
'Healthcare': 'erpnext.domains.healthcare',
'Hospitality': 'erpnext.domains.hospitality',
'Manufacturing': 'erpnext.domains.manufacturing',
'Non Profit': 'erpnext.domains.non_profit',
'Retail': 'erpnext.domains.retail',
'Services': 'erpnext.domains.services',
}
website_generators = ["Item Group", "Item", "BOM", "Sales Partner",
"Job Opening", "Student Admission"]
website_context = {
"favicon": "/assets/erpnext/images/favicon.png",
"splash_image": "/assets/erpnext/images/erp-icon.svg"
}
website_route_rules = [
{"from_route": "/orders", "to_route": "Sales Order"},
{"from_route": "/orders/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Sales Order",
"parents": [{"label": _("Orders"), "route": "orders"}]
}
},
{"from_route": "/invoices", "to_route": "Sales Invoice"},
{"from_route": "/invoices/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Sales Invoice",
"parents": [{"label": _("Invoices"), "route": "invoices"}]
}
},
{"from_route": "/supplier-quotations", "to_route": "Supplier Quotation"},
{"from_route": "/supplier-quotations/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Supplier Quotation",
"parents": [{"label": _("Supplier Quotation"), "route": "supplier-quotations"}]
}
},
{"from_route": "/quotations", "to_route": "Quotation"},
{"from_route": "/quotations/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Quotation",
"parents": [{"label": _("Quotations"), "route": "quotations"}]
}
},
{"from_route": "/shipments", "to_route": "Delivery Note"},
{"from_route": "/shipments/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Delivery Note",
"parents": [{"label": _("Shipments"), "route": "shipments"}]
}
},
{"from_route": "/rfq", "to_route": "Request for Quotation"},
{"from_route": "/rfq/<path:name>", "to_route": "rfq",
"defaults": {
"doctype": "Request for Quotation",
"parents": [{"label": _("Request for Quotation"), "route": "rfq"}]
}
},
{"from_route": "/addresses", "to_route": "Address"},
{"from_route": "/addresses/<path:name>", "to_route": "addresses",
"defaults": {
"doctype": "Address",
"parents": [{"label": _("Addresses"), "route": "addresses"}]
}
},
{"from_route": "/jobs", "to_route": "Job Opening"},
{"from_route": "/admissions", "to_route": "Student Admission"},
{"from_route": "/boms", "to_route": "BOM"},
{"from_route": "/timesheets", "to_route": "Timesheet"},
]
standard_portal_menu_items = [
{"title": _("Personal Details"), "route": "/personal-details", "reference_doctype": "Patient", "role": "Patient"},
{"title": _("Projects"), "route": "/project", "reference_doctype": "Project"},
{"title": _("Request for Quotations"), "route": "/rfq", "reference_doctype": "Request for Quotation", "role": "Supplier"},
{"title": _("Supplier Quotation"), "route": "/supplier-quotations", "reference_doctype": "Supplier Quotation", "role": "Supplier"},
{"title": _("Quotations"), "route": "/quotations", "reference_doctype": "Quotation", "role":"Customer"},
{"title": _("Orders"), "route": "/orders", "reference_doctype": "Sales Order", "role":"Customer"},
{"title": _("Invoices"), "route": "/invoices", "reference_doctype": "Sales Invoice", "role":"Customer"},
{"title": _("Shipments"), "route": "/shipments", "reference_doctype": "Delivery Note", "role":"Customer"},
{"title": _("Issues"), "route": "/issues", "reference_doctype": "Issue", "role":"Customer"},
{"title": _("Addresses"), "route": "/addresses", "reference_doctype": "Address"},
{"title": _("Timesheets"), "route": "/timesheets", "reference_doctype": "Timesheet", "role":"Customer"},
{"title": _("Timesheets"), "route": "/timesheets", "reference_doctype": "Timesheet", "role":"Customer"},
{"title": _("Lab Test"), "route": "/lab-test", "reference_doctype": "Lab Test", "role":"Patient"},
{"title": _("Prescription"), "route": "/prescription", "reference_doctype": "Patient Encounter", "role":"Patient"},
{"title": _("Patient Appointment"), "route": "/patient-appointments", "reference_doctype": "Patient Appointment", "role":"Patient"},
{"title": _("Fees"), "route": "/fees", "reference_doctype": "Fees", "role":"Student"},
{"title": _("Newsletter"), "route": "/newsletters", "reference_doctype": "Newsletter"},
{"title": _("Admission"), "route": "/admissions", "reference_doctype": "Student Admission"},
{"title": _("Certification"), "route": "/certification", "reference_doctype": "Certification Application"},
]
default_roles = [
{'role': 'Customer', 'doctype':'Contact', 'email_field': 'email_id'},
{'role': 'Supplier', 'doctype':'Contact', 'email_field': 'email_id'},
{'role': 'Student', 'doctype':'Student', 'email_field': 'student_email_id'},
]
has_website_permission = {
"Sales Order": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Quotation": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Sales Invoice": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Supplier Quotation": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Delivery Note": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Issue": "erpnext.support.doctype.issue.issue.has_website_permission",
"Timesheet": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Lab Test": "erpnext.healthcare.web_form.lab_test.lab_test.has_website_permission",
"Patient Encounter": "erpnext.healthcare.web_form.prescription.prescription.has_website_permission",
"Patient Appointment": "erpnext.healthcare.web_form.patient_appointments.patient_appointments.has_website_permission",
"Patient": "erpnext.healthcare.web_form.personal_details.personal_details.has_website_permission"
}
dump_report_map = "erpnext.startup.report_data_map.data_map"
before_tests = "erpnext.setup.utils.before_tests"
standard_queries = {
"Customer": "erpnext.selling.doctype.customer.customer.get_customer_list",
"Healthcare Practitioner": "erpnext.healthcare.doctype.healthcare_practitioner.healthcare_practitioner.get_practitioner_list"
}
doc_events = {
"Stock Entry": {
"on_submit": "erpnext.stock.doctype.material_request.material_request.update_completed_and_requested_qty",
"on_cancel": "erpnext.stock.doctype.material_request.material_request.update_completed_and_requested_qty"
},
"User": {
"after_insert": "frappe.contacts.doctype.contact.contact.update_contact",
"validate": "erpnext.hr.doctype.employee.employee.validate_employee_role",
"on_update": ["erpnext.hr.doctype.employee.employee.update_user_permissions",
"erpnext.portal.utils.set_default_role"]
},
("Sales Taxes and Charges Template", 'Price List'): {
"on_update": "erpnext.shopping_cart.doctype.shopping_cart_settings.shopping_cart_settings.validate_cart_settings"
},
"Website Settings": {
"validate": "erpnext.portal.doctype.products_settings.products_settings.home_page_is_products"
},
"Sales Invoice": {
"on_submit": ["erpnext.regional.france.utils.create_transaction_log", "erpnext.regional.italy.utils.sales_invoice_on_submit"],
"on_cancel": "erpnext.regional.italy.utils.sales_invoice_on_cancel",
"on_trash": "erpnext.regional.check_deletion_permission"
},
"Payment Entry": {
"on_submit": ["erpnext.regional.france.utils.create_transaction_log", "erpnext.accounts.doctype.payment_request.payment_request.make_status_as_paid"],
"on_trash": "erpnext.regional.check_deletion_permission"
},
'Address': {
'validate': ['erpnext.regional.india.utils.validate_gstin_for_india', 'erpnext.regional.italy.utils.set_state_code']
},
('Sales Invoice', 'Purchase Invoice', 'Delivery Note'): {
'validate': 'erpnext.regional.india.utils.set_place_of_supply'
},
"Contact":{
"on_trash": "erpnext.support.doctype.issue.issue.update_issue"
}
}
scheduler_events = {
"all": [
"erpnext.projects.doctype.project.project.project_status_update_reminder"
],
"hourly": [
'erpnext.hr.doctype.daily_work_summary_group.daily_work_summary_group.trigger_emails',
"erpnext.accounts.doctype.subscription.subscription.process_all",
"erpnext.erpnext_integrations.doctype.amazon_mws_settings.amazon_mws_settings.schedule_get_order_details",
"erpnext.projects.doctype.project.project.hourly_reminder",
"erpnext.projects.doctype.project.project.collect_project_status"
],
"daily": [
"erpnext.stock.reorder_item.reorder_item",
"erpnext.setup.doctype.email_digest.email_digest.send",
"erpnext.support.doctype.issue.issue.auto_close_tickets",
"erpnext.crm.doctype.opportunity.opportunity.auto_close_opportunity",
"erpnext.controllers.accounts_controller.update_invoice_status",
"erpnext.accounts.doctype.fiscal_year.fiscal_year.auto_create_fiscal_year",
"erpnext.hr.doctype.employee.employee.send_birthday_reminders",
"erpnext.projects.doctype.task.task.set_tasks_as_overdue",
"erpnext.assets.doctype.asset.depreciation.post_depreciation_entries",
"erpnext.hr.doctype.daily_work_summary_group.daily_work_summary_group.send_summary",
"erpnext.stock.doctype.serial_no.serial_no.update_maintenance_status",
"erpnext.buying.doctype.supplier_scorecard.supplier_scorecard.refresh_scorecards",
"erpnext.setup.doctype.company.company.cache_companies_monthly_sales_history",
"erpnext.assets.doctype.asset.asset.update_maintenance_status",
"erpnext.assets.doctype.asset.asset.make_post_gl_entry",
"erpnext.crm.doctype.contract.contract.update_status_for_contracts",
"erpnext.projects.doctype.project.project.update_project_sales_billing",
"erpnext.projects.doctype.project.project.send_project_status_email_to_users"
],
"daily_long": [
"erpnext.manufacturing.doctype.bom_update_tool.bom_update_tool.update_latest_price_in_all_boms"
],
"monthly": [
"erpnext.accounts.deferred_revenue.convert_deferred_revenue_to_income",
"erpnext.accounts.deferred_revenue.convert_deferred_expense_to_expense",
"erpnext.hr.utils.allocate_earned_leaves"
]
}
email_brand_image = "assets/erpnext/images/erpnext-logo.jpg"
default_mail_footer = """
<span>
Sent via
<a class="text-muted" href="https://erpnext.com?source=via_email_footer" target="_blank">
ERPNext
</a>
</span>
"""
get_translated_dict = {
("doctype", "Global Defaults"): "frappe.geo.country_info.get_translated_dict"
}
bot_parsers = [
'erpnext.utilities.bot.FindItemBot',
]
get_site_info = 'erpnext.utilities.get_site_info'
payment_gateway_enabled = "erpnext.accounts.utils.create_payment_gateway_account"
regional_overrides = {
'France': {
'erpnext.tests.test_regional.test_method': 'erpnext.regional.france.utils.test_method'
},
'India': {
'erpnext.tests.test_regional.test_method': 'erpnext.regional.india.utils.test_method',
'erpnext.controllers.taxes_and_totals.get_itemised_tax_breakup_header': 'erpnext.regional.india.utils.get_itemised_tax_breakup_header',
'erpnext.controllers.taxes_and_totals.get_itemised_tax_breakup_data': 'erpnext.regional.india.utils.get_itemised_tax_breakup_data',
'erpnext.accounts.party.get_regional_address_details': 'erpnext.regional.india.utils.get_regional_address_details',
'erpnext.hr.utils.calculate_annual_eligible_hra_exemption': 'erpnext.regional.india.utils.calculate_annual_eligible_hra_exemption',
'erpnext.hr.utils.calculate_hra_exemption_for_period': 'erpnext.regional.india.utils.calculate_hra_exemption_for_period'
},
'United Arab Emirates': {
'erpnext.controllers.taxes_and_totals.update_itemised_tax_data': 'erpnext.regional.united_arab_emirates.utils.update_itemised_tax_data'
},
'Saudi Arabia': {
'erpnext.controllers.taxes_and_totals.update_itemised_tax_data': 'erpnext.regional.united_arab_emirates.utils.update_itemised_tax_data'
},
'Italy': {
'erpnext.controllers.taxes_and_totals.update_itemised_tax_data': 'erpnext.regional.italy.utils.update_itemised_tax_data',
'erpnext.controllers.accounts_controller.validate_regional': 'erpnext.regional.italy.utils.sales_invoice_validate',
}
}
| ESS-LLP/erpnext-healthcare | erpnext/hooks.py | Python | gpl-3.0 | 14,269 |
/***************************************************************************
* Copyright (C) 2012 by santiago González *
* santigoro@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
#include "pin.h"
#include "connector.h"
Pin::Pin( int dir, const QPoint &pos, QString id, int index, Component* parent )
: QObject(), QGraphicsItem( parent ), ePin( index )
{
m_component = parent;
my_connector = 0l;
m_id = id;
m_area = QRect(-4, -4, 12, 8);
m_length = 8;
setObjectName( id );
setConnector( 0l );
setPos( pos );
rotate( 180-dir );
const QFont sansFont( "Helvetica [Cronyx]", 5 );
m_label = Circuit::self()->addSimpleText( id.toLatin1().data(), sansFont );
m_label->setParentItem( this );
m_label->setPos(-4, 4 );
m_label->rotate( 180-dir );
m_label->setText("");//( QString("%1 v").arg(m_volt) );
setCursor(Qt::CrossCursor);
this->setFlag( QGraphicsItem::ItemStacksBehindParent, true );
this->setFlag( QGraphicsItem::ItemIsSelectable, true );
connect( parent, SIGNAL( moved() ), this, SLOT( isMoved() ) );
}
Pin::~Pin(){}
void Pin::reset()
{
//qDebug() << "Pin::reset "<< m_id << m_numConections;
setConnector( 0l );
ePin::reset();
//qDebug() << "ePin::reset new:" << m_numConections;
//m_msg = msg_dis;
m_component->inStateChanged( m_index ); // Only used by node??
}
double Pin::getVolt()
{
return ePin::getVolt();
}
//void Pin::setChanged( bool changed ) { m_changed = changed; }
void Pin::setConnector( Connector* connector )
{
my_connector = connector;
if( my_connector )
{
//ePin::setEnode( connector->enode() );
setCursor( Qt::ArrowCursor );
}
else
{
//ePin::setEnode( 0l );
setCursor( Qt::CrossCursor );
}
}
/*void Pin::setConnected( bool connected )
{
ePin::m_connected = connected;
if( my_connector ) setCursor( Qt::ArrowCursor );
else { setCursor( Qt::CrossCursor );
my_connector = 0l; }
}*/
Connector* Pin::connector() { return my_connector; }
void Pin::isMoved()
{
if( my_connector ) my_connector->updateConRoute( this, scenePos() );
}
void Pin::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if( event->button() == Qt::LeftButton )
{
if( my_connector==0l )
{
event->accept();
if( Circuit::self()->is_constarted() ) Circuit::self()->closeconnector( this );
else Circuit::self()->newconnector( this );
}
else event->ignore();
}
}
QString Pin::itemID() { return m_id; }
void Pin::setLength( int length ) { m_length = length; }
void Pin::setConPin( Pin* pin ){ m_conPin = pin; }
Pin* Pin::conPin() { return m_conPin; }
//bool Pin::changed(){ return m_changed; }
void Pin::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget )
{
Q_UNUSED(option); Q_UNUSED(widget);
QPen pen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
//painter->setBrush( Qt::red );
//painter->drawRect( boundingRect() );
if( isSelected() ) pen.setColor( Qt::darkGray);
painter->setPen(pen);
if( m_length < 1 ) m_length = 1;
painter->drawLine( 0, 0, m_length-1, 0);
}
#include "moc_pin.cpp"
| jdpillon/simulide | src/simulator/graphic/pin.cpp | C++ | gpl-3.0 | 4,557 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-05-30 22:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pattern', '0014_pattern_editnumber'),
]
operations = [
migrations.AddField(
model_name='pattern',
name='json',
field=models.TextField(null=True),
),
]
| yaxu/patternlib | pattern/migrations/0015_pattern_json.py | Python | gpl-3.0 | 444 |
//
// HttpListener.cs
// Copied from System.Net.HttpListener
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012 sta.blockhead (sta.blockhead@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading;
// TODO: logging
namespace WebSocketSharp.Net {
public sealed class HttpListener : IDisposable {
#region Fields
AuthenticationSchemes auth_schemes;
AuthenticationSchemeSelector auth_selector;
Dictionary<HttpConnection, HttpConnection> connections;
List<HttpListenerContext> ctx_queue;
bool disposed;
bool ignore_write_exceptions;
bool listening;
HttpListenerPrefixCollection prefixes;
string realm;
Dictionary<HttpListenerContext, HttpListenerContext> registry;
bool unsafe_ntlm_auth;
List<ListenerAsyncResult> wait_queue;
#endregion
#region Constructor
public HttpListener ()
{
prefixes = new HttpListenerPrefixCollection (this);
registry = new Dictionary<HttpListenerContext, HttpListenerContext> ();
connections = new Dictionary<HttpConnection, HttpConnection> ();
ctx_queue = new List<HttpListenerContext> ();
wait_queue = new List<ListenerAsyncResult> ();
auth_schemes = AuthenticationSchemes.Anonymous;
}
#endregion
#region Properties
// TODO: Digest, NTLM and Negotiate require ControlPrincipal
public AuthenticationSchemes AuthenticationSchemes {
get { return auth_schemes; }
set {
CheckDisposed ();
auth_schemes = value;
}
}
public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate {
get { return auth_selector; }
set {
CheckDisposed ();
auth_selector = value;
}
}
public bool IgnoreWriteExceptions {
get { return ignore_write_exceptions; }
set {
CheckDisposed ();
ignore_write_exceptions = value;
}
}
public bool IsListening {
get { return listening; }
}
public static bool IsSupported {
get { return true; }
}
public HttpListenerPrefixCollection Prefixes {
get {
CheckDisposed ();
return prefixes;
}
}
// TODO: Use this
public string Realm {
get { return realm; }
set {
CheckDisposed ();
realm = value;
}
}
// TODO: Support for NTLM needs some loving.
public bool UnsafeConnectionNtlmAuthentication {
get { return unsafe_ntlm_auth; }
set {
CheckDisposed ();
unsafe_ntlm_auth = value;
}
}
#endregion
#region Private Methods
void Cleanup (bool close_existing)
{
lock (((ICollection)registry).SyncRoot) {
if (close_existing) {
// Need to copy this since closing will call UnregisterContext
ICollection keys = registry.Keys;
var all = new HttpListenerContext [keys.Count];
keys.CopyTo (all, 0);
registry.Clear ();
for (int i = all.Length - 1; i >= 0; i--)
all [i].Connection.Close (true);
}
lock (((ICollection)connections).SyncRoot) {
ICollection keys = connections.Keys;
var conns = new HttpConnection [keys.Count];
keys.CopyTo (conns, 0);
connections.Clear ();
for (int i = conns.Length - 1; i >= 0; i--)
conns [i].Close (true);
}
lock (((ICollection)ctx_queue).SyncRoot) {
var ctxs = ctx_queue.ToArray ();
ctx_queue.Clear ();
for (int i = ctxs.Length - 1; i >= 0; i--)
ctxs [i].Connection.Close (true);
}
lock (((ICollection)wait_queue).SyncRoot) {
Exception exc = new ObjectDisposedException ("listener");
foreach (ListenerAsyncResult ares in wait_queue) {
ares.Complete (exc);
}
wait_queue.Clear ();
}
}
}
void Close (bool force)
{
CheckDisposed ();
EndPointManager.RemoveListener (this);
Cleanup (force);
}
// Must be called with a lock on ctx_queue
HttpListenerContext GetContextFromQueue ()
{
if (ctx_queue.Count == 0)
return null;
var context = ctx_queue [0];
ctx_queue.RemoveAt (0);
return context;
}
void IDisposable.Dispose ()
{
if (disposed)
return;
Close (true); //TODO: Should we force here or not?
disposed = true;
}
#endregion
#region Internal Methods
internal void AddConnection (HttpConnection cnc)
{
connections [cnc] = cnc;
}
internal void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
}
internal void RegisterContext (HttpListenerContext context)
{
lock (((ICollection)registry).SyncRoot)
registry [context] = context;
ListenerAsyncResult ares = null;
lock (((ICollection)wait_queue).SyncRoot) {
if (wait_queue.Count == 0) {
lock (((ICollection)ctx_queue).SyncRoot)
ctx_queue.Add (context);
} else {
ares = wait_queue [0];
wait_queue.RemoveAt (0);
}
}
if (ares != null)
ares.Complete (context);
}
internal void RemoveConnection (HttpConnection cnc)
{
connections.Remove (cnc);
}
internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerContext context)
{
if (AuthenticationSchemeSelectorDelegate != null)
return AuthenticationSchemeSelectorDelegate (context.Request);
else
return auth_schemes;
}
internal void UnregisterContext (HttpListenerContext context)
{
lock (((ICollection)registry).SyncRoot)
registry.Remove (context);
lock (((ICollection)ctx_queue).SyncRoot) {
int idx = ctx_queue.IndexOf (context);
if (idx >= 0)
ctx_queue.RemoveAt (idx);
}
}
#endregion
#region Public Methods
public void Abort ()
{
if (disposed)
return;
if (!listening) {
return;
}
Close (true);
}
public IAsyncResult BeginGetContext (AsyncCallback callback, Object state)
{
CheckDisposed ();
if (!listening)
throw new InvalidOperationException ("Please, call Start before using this method.");
ListenerAsyncResult ares = new ListenerAsyncResult (callback, state);
// lock wait_queue early to avoid race conditions
lock (((ICollection)wait_queue).SyncRoot) {
lock (((ICollection)ctx_queue).SyncRoot) {
HttpListenerContext ctx = GetContextFromQueue ();
if (ctx != null) {
ares.Complete (ctx, true);
return ares;
}
}
wait_queue.Add (ares);
}
return ares;
}
public void Close ()
{
if (disposed)
return;
if (!listening) {
disposed = true;
return;
}
Close (true);
disposed = true;
}
public HttpListenerContext EndGetContext (IAsyncResult asyncResult)
{
CheckDisposed ();
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
ListenerAsyncResult ares = asyncResult as ListenerAsyncResult;
if (ares == null)
throw new ArgumentException ("Wrong IAsyncResult.", "asyncResult");
if (ares.EndCalled)
throw new ArgumentException ("Cannot reuse this IAsyncResult");
ares.EndCalled = true;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne ();
lock (((ICollection)wait_queue).SyncRoot) {
int idx = wait_queue.IndexOf (ares);
if (idx >= 0)
wait_queue.RemoveAt (idx);
}
HttpListenerContext context = ares.GetContext ();
context.ParseAuthentication (SelectAuthenticationScheme (context));
return context; // This will throw on error.
}
public HttpListenerContext GetContext ()
{
// The prefixes are not checked when using the async interface!?
if (prefixes.Count == 0)
throw new InvalidOperationException ("Please, call AddPrefix before using this method.");
ListenerAsyncResult ares = (ListenerAsyncResult) BeginGetContext (null, null);
ares.InGet = true;
return EndGetContext (ares);
}
public void Start ()
{
CheckDisposed ();
if (listening)
return;
EndPointManager.AddListener (this);
listening = true;
}
public void Stop ()
{
CheckDisposed ();
listening = false;
Close (false);
}
#endregion
}
}
| pasanzaza/Dragonbound | src/server/websocket-sharp/Net/HttpListener.cs | C# | gpl-3.0 | 9,433 |
<?php
/**
* Guild - Topic Daily Build System.
*
* @link http://git.intra.weibo.com/huati/daily-build
* @copyright Copyright (c) 2009-2016 Weibo Inc. (http://weibo.com)
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPL License
*/
namespace Library\Model;
use Library\Util\Config;
class SVNModel
{
/**
* Svn info.
*
* @var array
*/
private static $_svnInfo = array();
/**
* Current SVN version.
*
* @var string
*/
private static $_curVer = '';
/**
* Get info.
*
* @return array
*/
public function getInfo()
{
return $this->getLog($this->getCurVer(), $this->getLastVer());
}
/**
* Get current version.
*
* @return string
*/
public function getCurVer()
{
if (!isset(self::$_curVer) || empty(self::$_curVer)) {
$svnInfo = $this->getSVNInfo();
foreach ($svnInfo as $value) {
if (strpos($value, "Last Changed Rev") === 0) {
$item = explode(":", $value);
self::$_curVer = trim($item[1]);
break;
}
}
if(!isset(self::$_curVer)) {
die("Get cur version failed. At library\model\SVNmodel.");
}
}
return self::$_curVer;
}
/**
* Get last version.
*
* @return string
*/
public function getLastVer()
{
$file = APP_PATH . '/db/' . APP_NAME . '/' . 'svn';
$handler = fopen($file, "r");
$version = null;
while (!feof($handler)) {
$line = fgets($handler);
$item = explode(":", $line);
if ($item[0] == "last_version") {
$version = trim($item[1]);
}
}
fclose($handler);
if (isset($version)) {
return $version;
} else {
throw new \Exception("Not found the last_version in db/svn file.");
}
}
/**
* Set last version.
*
* @param $version string
* @return bool
*/
public function setLastVer($version = null)
{
if (!isset($version)) {
throw new \Exception("Unset version var.");
}
$file = APP_PATH . '/db/' . APP_NAME . '/' . 'svn';
$handler = fopen($file, "r+");
$content = "";
while (!feof($handler)) {
$line = fgets($handler);
$item = explode(":", $line);
if ($item[0] == "last_version") {
$line = "last_version:{$version}";
}
$content .= $line . "\n";
}
$content = trim($content);
fseek($handler, 0);
fwrite($handler, $content);
fclose($handler);
return true;
}
/**
* Get SVN info.
*
* @return array
*/
public function getSVNInfo()
{
if (!isset(self::$_svnInfo) || empty(self::$_svnInfo)) {
$cmd = "cd " . Config::get("common.product.cmd_path") . ";/usr/bin/svn info";
$output = shell_exec($cmd);
$output = explode("\n", $output);
if (!empty($output)) {
self::$_svnInfo = $output;
} else {
die("Get svn info failed. At library\model\SVNmodel.");
}
}
return self::$_svnInfo;
}
/**
* Get diff with param.
*
* @param $nv string
* @param $ov string
* @param $filename string
* @param $withSummarize bool
* @param $withXML bool
* @return string
*/
public function getDiffWithParam($nv, $ov, $filename = null, $withSummarize = false, $withXML = false)
{
if (!isset($filename)) {
$filename = "";
}
$paramStr = "";
if ($withSummarize === true) {
$paramStr .= " --summarize ";
}
if ($withXML === true) {
$paramStr .= " --xml ";
}
$cmd = "cd " . Config::get("common.product.cmd_path") . ";/usr/bin/svn diff -r{$nv}:{$ov} {$filename} {$paramStr}";
return shell_exec($cmd);
}
/**
* Get diff xml
*
* @param $ov string
* @param $nv string
* @return object
*/
public function getDiffXml($ov, $nv)
{
if (!isset($ov) || !isset($nv)) {
die("Getdiff parameters is invalid. At library\model\SVNmodel.");
}
$cmd = "cd " . Config::get("common.product.cmd_path") . ";/usr/bin/svn diff -r{$ov}:{$nv} --summarize --xml";
return simplexml_load_string(shell_exec($cmd));
}
/**
* Get diff.
*
* @param $ov string
* @param $nv string
* @return array
*/
public function getDiff($ov, $nv)
{
if (!isset($ov) || !isset($nv)) {
die("Getdiff parameters is invalid. At library\model\SVNmodel.");
}
$cmd = "cd " . Config::get("common.product.cmd_path") . " ;/usr/bin/svn diff -r{$ov}:{$nv} --summarize --xml";
$output = shell_exec($cmd);
$output = simplexml_load_string($output);
$output = json_decode(json_encode($output), true);
return $output;
}
/**
* Get log.
*
* @param $ov string
* @param $nv string
* @return array
*/
public function getLog($ov, $nv)
{
if (!isset($ov) || !isset($nv)) {
die("Getlog parameters is invalid. At library\model\SVNmodel.");
}
$cmd = "cd " . Config::get("common.product.cmd_path") . ";/usr/bin/svn log -r{$ov}:{$nv} --xml";
$output = shell_exec($cmd);
$output = simplexml_load_string($output);
$output = json_decode(json_encode($output), true);
return $output;
}
/**
* SVN up.
*
* @return string
*/
public function svnUp()
{
$cmd = "cd " . Config::get("common.product.cmd_path") . ";/usr/bin/svn up --ignore-externals";
return shell_exec($cmd);
}
/**
* SVN up build.
*
* @return string
*/
public function svnUpBuild()
{
$cmd = "cd " . Config::get("common.product.cmd_path") . ";/usr/bin/svn up --ignore-externals";
return shell_exec($cmd);
}
/**
* SVN up environment.
*
* @return string
*/
public function svnUpEnv()
{
$cmd = "cd " . Config::get("common.product.drop_path") . ";/usr/bin/svn up --ignore-externals";
return shell_exec($cmd);
}
}
| GenialX/guild | library/model/SVNModel.php | PHP | gpl-3.0 | 6,535 |