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
#include "vector_plot_2d.h" #include "../graph/vector_graph_2d.h" namespace Gnuplot { Vector_plot_2d::Vector_plot_2d() // Default constructor : Plot_2d {Representation::TwoDVector} { // Add default graph: this->graphs.push_back(std::make_shared<Vector_graph_2d>()); } Vector_plot_2d::Vector_plot_2d(const std::string& file_name) // Specify file name of output gnuplot script : Plot_2d {Representation::TwoDVector, file_name} { this->graphs.push_back(std::make_shared<Vector_graph_2d>(file_name)); } void Vector_plot_2d::add_data_point(const double& x, const double& y, const double& vec_x, const double& vec_y) { auto* ptr = dynamic_cast<Vector_graph_2d*>(this->graphs.front().get()); if (ptr == nullptr) { throw std::runtime_error("In Vector_plot_2d::add_data_point: No graph accessible"); } ptr->add_data_point(x, y, vec_x, vec_y); // Have Graph handle Data_point construction } }
Kadabash/Gnuplot_cpp
src/plot/vector_plot_2d.cpp
C++
gpl-3.0
977
package com.authpro.imageauthentication; import android.app.Fragment; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Base64; import android.util.Pair; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import static junit.framework.Assert.*; public class InputFragment extends Fragment implements ICallbackable<HttpResult> { private final int imageCount = 30; private int rowCount, columnCount; private ArrayList<Pair<Integer, Integer>> input = new ArrayList<>(); private TextView textView; private View initialButton = null; private ImageButton[][] imageButtons; private String[] imageHashes; private Bitmap[] images; private ArrayList<Integer> permutation; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_input, container, true); this.textView = (EditText)view.findViewById(R.id.textView); getDimensions(); setupButtons(view); fetchImages(); return view; } private void getDimensions() { Resources resources = getResources(); int columnCountResID = R.integer.gridColumnCount, rowCountResID = R.integer.gridRowCount; this.columnCount = resources.getInteger(columnCountResID); this.rowCount = resources.getInteger(rowCountResID); assertEquals(rowCount * columnCount, imageCount); } private void setupButtons(View view) { final ViewGroup gridLayout = (ViewGroup)view.findViewById(R.id.rows); final int realRowCount = gridLayout.getChildCount(); assertEquals(realRowCount, rowCount); this.imageButtons = new ImageButton[rowCount][columnCount]; for (int i = 0; i < rowCount; i++) { final View child = gridLayout.getChildAt(i); assertTrue(child instanceof LinearLayout); LinearLayout row = (LinearLayout) child; final int realColumnCount = row.getChildCount(); assertEquals(realColumnCount, columnCount); for (int j = 0; j < columnCount; j++) { final View cell = ((ViewGroup)row.getChildAt(j)).getChildAt(0); assertTrue(cell instanceof ImageButton); final ImageButton imageButton = (ImageButton)cell; final int index = i * columnCount + j; imageButton.setTag(index); imageButtons[i][j] = imageButton; setupForDragEvent(cell); } } } private void setupForDragEvent(View view) { view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { assertTrue(v instanceof ImageButton); int action = event.getAction() & MotionEvent.ACTION_MASK; switch (action) { case MotionEvent.ACTION_DOWN: assertNull(initialButton); // TODO: Fix the bug when this is not null sometimes. initialButton = v; View.DragShadowBuilder shadow = new View.DragShadowBuilder(); v.startDrag(null, shadow, null, 0); v.setPressed(true); break; case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: break; } return true; } }); view.setOnDragListener(new View.OnDragListener() { @Override public boolean onDrag(View v, DragEvent event) { int action = event.getAction(); switch (action) { case DragEvent.ACTION_DRAG_ENTERED: if (v != initialButton) v.setPressed(true); break; case DragEvent.ACTION_DRAG_EXITED: if (v != initialButton) v.setPressed(false); break; case DragEvent.ACTION_DROP: assertNotNull(initialButton); int firstIndex = (int)initialButton.getTag(), secondIndex = (int)v.getTag(); addInput(firstIndex, secondIndex); v.setPressed(false); v.playSoundEffect(SoundEffectConstants.CLICK); break; case DragEvent.ACTION_DRAG_ENDED: if (v == initialButton) { initialButton.setPressed(false); initialButton = null; } break; } return true; } }); } private void addInput(int firstIndex, int secondIndex) { input.add(new Pair<>(permutation.get(firstIndex), permutation.get(secondIndex))); textView.append("*"); assertEquals(textView.length(), input.size()); } private void fetchImages() { HttpMethod method = HttpMethod.GET; String url = Config.API_URL + "api/images"; HttpTask task = new HttpTask(this, method, url); task.execute(); } public void callback(HttpResult result) { HttpStatus status = result.getStatus(); switch (status) { case OK: String data = result.getContent(); setImages(data); break; default: // Silently fail. } } private void setImages(String data) { images = new Bitmap[imageCount]; imageHashes = new String[imageCount]; permutation = new ArrayList<>(imageCount); String[] base64Strings = data.split("\n"); for (int i = 0; i < rowCount; i++) for (int j = 0; j < columnCount; j++) { int index = i * columnCount + j; permutation.add(index); String base64 = base64Strings[index]; images[index] = fromBase64(base64); imageHashes[index] = Utils.computeHash(base64); } shuffle(); } public void shuffle() { Collections.shuffle(permutation); for (int i = 0; i < rowCount; i++) for (int j = 0; j < columnCount; j++) { ImageButton imageButton = imageButtons[i][j]; int index = i * columnCount + j; Bitmap image = images[permutation.get(index)]; imageButton.setImageBitmap(image); } } private Bitmap fromBase64(String base64) { byte[] bytes = Base64.decode(base64, Base64.DEFAULT); return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } public void clear() { input = new ArrayList<>(); textView.setText(""); } public String getInputString() // Should use char[] instead, for security reasons. { StringBuilder output = new StringBuilder(); for (Pair<Integer, Integer> pair : this.input) { if (pair.first.equals(pair.second)) output.append(imageHashes[pair.first]).append("_"); else output.append(imageHashes[pair.first]).append("+").append(imageHashes[pair.second]).append("_"); } return output.toString(); } }
phamhathanh/ImageAuthentication
client/app/src/main/java/com/authpro/imageauthentication/InputFragment.java
Java
gpl-3.0
8,323
#!python """Script for plotting distributions of epitopes per site for two sets of sites. Uses matplotlib. Designed to analyze output of epitopefinder_getepitopes.py. Written by Jesse Bloom.""" import os import sys import random import epitopefinder.io import epitopefinder.plot def main(): """Main body of script.""" random.seed(1) # seed random number generator in case P values are being computed if not epitopefinder.plot.PylabAvailable(): raise ImportError("Cannot import matplotlib / pylab, which are required by this script.") # output is written to out, currently set to standard out out = sys.stdout out.write("Beginning execution of epitopefinder_plotdistributioncomparison.py\n") # read input file and parse arguments args = sys.argv[1 : ] if len(args) != 1: raise IOError("Script must be called with exactly one argument specifying the input file") infilename = sys.argv[1] if not os.path.isfile(infilename): raise IOError("Failed to find infile %s" % infilename) d = epitopefinder.io.ParseInfile(open(infilename)) out.write("\nRead input arguments from %s\n" % infilename) out.write('Read the following key / value pairs:\n') for (key, value) in d.iteritems(): out.write("%s %s\n" % (key, value)) plotfile = epitopefinder.io.ParseStringValue(d, 'plotfile').strip() epitopesbysite1_list = [] epitopesbysite2_list = [] for (xlist, xf) in [(epitopesbysite1_list, 'epitopesfile1'), (epitopesbysite2_list, 'epitopesfile2')]: epitopesfile = epitopefinder.io.ParseFileList(d, xf) if len(epitopesfile) != 1: raise ValueError("%s specifies more than one file" % xf) epitopesfile = epitopesfile[0] for line in open(epitopesfile).readlines()[1 : ]: if not (line.isspace() or line[0] == '#'): (site, n) = line.split(',') (site, n) = (int(site), int(n)) xlist.append(n) if not xlist: raise ValueError("%s failed to specify information for any sites" % xf) set1name = epitopefinder.io.ParseStringValue(d, 'set1name') set2name = epitopefinder.io.ParseStringValue(d, 'set2name') title = epitopefinder.io.ParseStringValue(d, 'title').strip() if title.upper() in ['NONE', 'FALSE']: title = None pvalue = epitopefinder.io.ParseStringValue(d, 'pvalue') if pvalue.upper() in ['NONE', 'FALSE']: pvalue = None pvaluewithreplacement = None else: pvalue = int(pvalue) pvaluewithreplacement = epitopefinder.io.ParseBoolValue(d, 'pvaluewithreplacement') if pvalue < 1: raise ValueError("pvalue must be >= 1") if len(epitopesbysite2_list) >= len(epitopesbysite1_list): raise ValueError("You cannot use pvalue since epitopesbysite2_list is not a subset of epitopesbysite1_list -- it does not contain fewer sites with specified epitope counts.") ymax = None if 'ymax' in d: ymax = epitopefinder.io.ParseFloatValue(d, 'ymax') out.write('\nNow creating the plot file %s\n' % plotfile) epitopefinder.plot.PlotDistributionComparison(epitopesbysite1_list, epitopesbysite2_list, set1name, set2name, plotfile, 'number of epitopes', 'fraction of sites', title, pvalue, pvaluewithreplacement, ymax=ymax) out.write("\nScript is complete.\n") if __name__ == '__main__': main() # run the script
jbloom/epitopefinder
scripts/epitopefinder_plotdistributioncomparison.py
Python
gpl-3.0
3,447
#include <string.h> #include <sys/socket.h> #include <unistd.h> #include <errno.h> #include <cstdlib> #include <queue> #include <iostream> #include <sstream> #include "BullBenchThread.h" #include "BullBench.h" #define REQUEST_SIZE 2048 void BullBenchThread::run() { int succ = 0; for (;;) { pthread_mutex_lock(&_settings.mutex); if (succ > 0) _settings.totalSendSucc ++; if (succ < 0) _settings.totalSendFail ++; if (succ > 0 && _settings.totalSendSucc % 1000 == 0) { uint64_t time = _settings.getTimeCost(); std::cout<<"send request url succ count:" << _settings.totalSendSucc <<"\tfail count:" << _settings.totalSendFail <<"\ttime cost: " << time / 1000000 <<" seconds, " << time % 1000000 << " microseconds" <<std::endl; } succ = 0; if (_requestQueue.empty()) { if (_settings.stop) { pthread_mutex_unlock(&_settings.mutex); exit(NULL); } pthread_cond_broadcast(&_settings.emptyCond); pthread_cond_wait(&_settings.fullCond, &_settings.mutex); pthread_mutex_unlock(&_settings.mutex); continue; } std::string url = _requestQueue.front(); _requestQueue.pop(); pthread_mutex_unlock(&_settings.mutex); char request[REQUEST_SIZE]; buildRequest(request, url); int rlen = strlen(request); int sock = _getSocket(); if (sock < 0) { std::stringstream ss; ss << "Error: sock fail:" << _settings.domainName << ':' << _settings.port << "\t" << strerror(errno) << std::endl; std::cerr << ss.str(); succ = -1; continue; } if(rlen!=write(sock,request,rlen)) { close(sock); std::stringstream ss; ss << "Error: write fail :" << std::endl; std::cerr << ss.str(); succ = -1; continue; } // Read all char response[8192]; while (read(sock,response,8192) > 0) { // do nothing; } close(sock); succ = 1; } // end for } void BullBenchThread::buildRequest(char* request,std::string& uri) { //Five_comment: same as memset bytes to sezo('\0') bzero(request,REQUEST_SIZE); strcpy(request,"GET"); strcat(request," "); if (_settings.host.empty()) { strcat(request, (char *)uri.c_str()); } else { strcat(request, (char *)_settings.urlPrefix.c_str()); strcat(request, (char *)uri.c_str()); } // detemine which http version strcat(request," HTTP/1.1"); strcat(request,"\r\n"); strcat(request,"User-Agent: "PROGRAM_NAME" "PROGRAM_VERSION"\r\n"); strcat(request,"Host: "); if (_settings.host.empty()) { if (80 == _settings.port) { strcat(request, _settings.domainName.c_str()); } else { strcat(request, (_settings.domainName + ":" + _settings.portString).c_str()); } } else { strcat(request, _settings.host.c_str()); } strcat(request,"\r\n"); strcat(request,"Pragma: no-cache\r\n"); strcat(request,"Connection: close\r\n"); //strcat(request,"Connection: keep-alive\r\n"); strcat(request,"Keep-Alive: timeout=20\r\n"); strcat(request,"\r\n"); }
zuocheng-liu/BullBench
src/BullBenchThread.cpp
C++
gpl-3.0
3,451
/** * Problem 10.1 CTCI Sorted Merge * * You are given two sorted arrays, a and b, where a has a large enough buffer at the end to hold * b. Write a method to merge b into a in sorted order. * * Examples: * * a: 2, 7, 22, 44, 56, 88, 456, 5589 * b: 1, 4, 9, 23, 99, 1200 * * Result: * * result: 1, 2, 4, 7, 9, 22, 23, 44, 56, 88, 99, 456, 1200, 5589 * * Analysis: * * The merge is probably most effective if the values are inserted into the buffer starting with * the end of the input arrays. * * a == a0, a1, a2, ..., ai, ... an i.e. i is range 0..n * b == b0, b1, b2, ..., bj, ... bm i.e. j is range 0..m * * Algorithm: * * 1) Starting at the end of the arrays, compare (a, b) each descending element and place the larger * at the end of the result array (a). If the values are identical, put both elements into the * result. * * 2) Decrement the running index for each array contributing to the result on this iteration. * * 3) Repeat until the b running index (j) is 0 (all of b have been added to a). * * i = n; * j = m; * while j >= 0 do * if i < 0 * then * a[j] = b[j] * else if a[i] > b[j] * then * a[i+j+1] = a[i--] * else if b[j] > a[i] * a[i+j] = b[j--] * else * a[i+j] = b[j--] * a[i+j] = a[i--] */ import java.util.Arrays; import java.util.Locale; public class Main { /** Run the program using the command line arguments. */ public static void main(String[] args) { // Define a and b. int[] a = new int[]{2, 7, 22, 44, 56, 88, 456, 5589}; int[] b = new int[]{1, 4, 9, 23, 99, 1200}; int[] result = smerge(a, b); String format = "Result: %s"; System.out.println(String.format(Locale.US, format, Arrays.toString(result))); } /** Return the given value in the given base. */ private static int[] smerge(final int[] a, final int[] b) { final int N = a.length; final int M = b.length; int [] result = new int[N + M]; System.arraycopy(a, 0, result, 0, N); int i = N - 1; int j = M - 1; while (j >= 0) { if (i < 0) result[j] = b[j--]; else if (a[i] > b[j]) result[i + j + 1] = a[i--]; else if (b[j] > a[i]) result[i + j + 1] = b[j--]; else { result[i + j + 1] = a[i--]; result[i + j + 1] = b[j--]; } } return result; } }
pajato/java-examples
apps/misc/smerge/src/main/java/Main.java
Java
gpl-3.0
2,552
/** Eubrazil Scientific Gateway Copyright (C) 2015 CMCC 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 it.cmcc.ophidiaweb.utils.deserialization; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "node", "description" }) public class Nodelink { @JsonProperty("node") private String node; @JsonProperty("description") private String description; @JsonProperty("node") public String getNode() { return node; } @JsonProperty("node") public void setNode(String node) { this.node = node; } @JsonProperty("description") public String getDescription() { return description; } @JsonProperty("description") public void setDescription(String description) { this.description = description; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object other) { return EqualsBuilder.reflectionEquals(this, other); } }
Ophidia/eubrazilcc-uc3-gateway
src/it/cmcc/ophidiaweb/utils/deserialization/Nodelink.java
Java
gpl-3.0
2,185
/* * jQuery Fast Confirm * version: 2.1.1 (2011-03-23) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://blog.pierrejeanparra.com/jquery-plugins/fast-confirm/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function ($) { var methods = { init: function (options) { var params; if (!this.length) { return this; } $.fastConfirm = { defaults: { position: 'bottom', offset: {top: 0, left: 0}, zIndex: 10000, eventToBind: false, questionText: "Are you sure?", proceedText: "Yes", cancelText: "No", targetElement: null, unique: false, fastConfirmClass: "fast_confirm", onProceed: function ($trigger) { $trigger.fastConfirm('close'); return true; }, onCancel: function ($trigger) { $trigger.fastConfirm('close'); return false; } } }; params = $.extend($.fastConfirm.defaults, options || {}); return this.each(function () { var trigger = this, $trigger = $(this), $confirmYes = $('<button class="' + params.fastConfirmClass + '_proceed">' + params.proceedText + '</button>'), $confirmNo = $('<button class="' + params.fastConfirmClass + '_cancel">' + params.cancelText + '</button>'), $confirmBox = $('<div class="' + params.fastConfirmClass + '"><div class="' + params.fastConfirmClass + '_arrow_border"></div><div class="' + params.fastConfirmClass + '_arrow"></div>' + params.questionText + '<br/></div>'), $arrow = $('div.' + params.fastConfirmClass + '_arrow', $confirmBox), $arrowBorder = $('div.' + params.fastConfirmClass + '_arrow_border', $confirmBox), confirmBoxArrowClass, confirmBoxArrowBorderClass, $target = params.targetElement ? $(params.targetElement, $trigger) : $trigger, offset = $target.offset(), topOffset, leftOffset, displayBox = function () { if (!$trigger.data('fast_confirm.box')) { $trigger.data('fast_confirm.params.fastConfirmClass', params.fastConfirmClass); // Close all other confirm boxes if necessary if (params.unique) { $('.' + params.fastConfirmClass + '_trigger').fastConfirm('close'); } // Register actions $confirmYes.bind('click.fast_confirm', function () { // In case the DOM has been refreshed in the meantime or something... $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); params.onProceed($trigger); // If the user wants us to handle events if (params.eventToBind) { trigger[params.eventToBind](); } }); $confirmNo.bind('click.fast_confirm', function () { // In case the DOM has been refreshed in the meantime or something... $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); params.onCancel($trigger); }); $confirmBox // Makes the confirm box focusable .attr("tabIndex", -1) // Bind Escape key to close the confirm box .bind('keydown.fast_confirm', function (event) { if (event.keyCode && event.keyCode === 27) { $trigger.fastConfirm('close'); } }); // Append the confirm box to the body. It will not be visible as it is off-screen by default. Positionning will be done at the last time $confirmBox.append($confirmYes).append($confirmNo); $('body').append($confirmBox); // Calculate absolute positionning depending on the trigger-relative position switch (params.position) { case 'top': confirmBoxArrowClass = params.fastConfirmClass + '_bottom'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_bottom'; $arrow.addClass(confirmBoxArrowClass).css('left', $confirmBox.outerWidth() / 2 - $arrow.outerWidth() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('left', $confirmBox.outerWidth() / 2 - $arrowBorder.outerWidth() / 2); topOffset = offset.top - $confirmBox.outerHeight() - $arrowBorder.outerHeight() + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() / 2 + $target.outerWidth() / 2 + params.offset.left; break; case 'right': confirmBoxArrowClass = params.fastConfirmClass + '_left'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_left'; $arrow.addClass(confirmBoxArrowClass).css('top', $confirmBox.outerHeight() / 2 - $arrow.outerHeight() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('top', $confirmBox.outerHeight() / 2 - $arrowBorder.outerHeight() / 2); topOffset = offset.top + $target.outerHeight() / 2 - $confirmBox.outerHeight() / 2 + params.offset.top; leftOffset = offset.left + $target.outerWidth() + $arrowBorder.outerWidth() + params.offset.left; break; case 'bottom': confirmBoxArrowClass = params.fastConfirmClass + '_top'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_top'; $arrow.addClass(confirmBoxArrowClass).css('left', $confirmBox.outerWidth() / 2 - $arrow.outerWidth() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('left', $confirmBox.outerWidth() / 2 - $arrowBorder.outerWidth() / 2); topOffset = offset.top + $target.outerHeight() + $arrowBorder.outerHeight() + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() / 2 + $target.outerWidth() / 2 + params.offset.left; break; case 'left': confirmBoxArrowClass = params.fastConfirmClass + '_right'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_right'; $arrow.addClass(confirmBoxArrowClass).css('top', $confirmBox.outerHeight() / 2 - $arrow.outerHeight() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('top', $confirmBox.outerHeight() / 2 - $arrowBorder.outerHeight() / 2); topOffset = offset.top + $target.outerHeight() / 2 - $confirmBox.outerHeight() / 2 + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() - $arrowBorder.outerWidth() + params.offset.left; break; } // Make the confirm box appear right where it belongs $confirmBox.css({ top: topOffset, left: leftOffset, zIndex: params.zIndex }).focus(); // Link trigger and confirm box $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); } }; // If the user wants to give us complete control over event handling if (params.eventToBind) { $trigger.bind(params.eventToBind + '.fast_confirm', function () { displayBox(); return false; }); } else { // Let event handling to the user, just display the confirm box displayBox(); } }); }, // Close the confirm box close: function () { return this.each(function () { var $this = $(this); $this.data('fast_confirm.box').remove(); $this.removeData('fast_confirm.box').removeClass($this.data('fast_confirm.params.fastConfirmClass') + '_trigger'); }); } }; $.fn.fastConfirm = function (method) { if (!this.length) { return this; } // Method calling logic if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.fastConfirm'); } }; })(jQuery);
apiary/apiary-project
src/workflow/assets/js/jquery.fastconfirm.js
JavaScript
gpl-3.0
7,913
mcinif='mcini_gen2' runname='gen_test2111b' mcpick='gen_test2b.pickle' pathdir='/beegfs/work/ka_oj4748/echoRD' wdir='/beegfs/work/ka_oj4748/gen_tests' update_prec=0.04 update_mf=False update_part=500 import sys sys.path.append(pathdir) import run_echoRD as rE rE.echoRD_job(mcinif=mcinif,mcpick=mcpick,runname=runname,wdir=wdir,pathdir=pathdir,update_prec=update_prec,update_mf=update_mf,update_part=update_part,hdf5pick=False)
cojacoo/testcases_echoRD
gen_test2111b.py
Python
gpl-3.0
430
package net.fisty.packgame.client.graphics.particle; import java.awt.Graphics; import java.awt.image.ImageObserver; public abstract class Particle { public int index = 0; public abstract void render(Graphics g, ImageObserver obs); public abstract void update(); public abstract void server(); public abstract String serializeParticle(); public abstract void unserializeParticle(String s); }
fisty256/PackGame
src/net/fisty/packgame/client/graphics/particle/Particle.java
Java
gpl-3.0
402
# -*- coding: utf-8 -*- """ Created on Fri Dec 18 14:11:31 2015 @author: Martin Friedl """ from datetime import date import numpy as np from Patterns.GrowthTheoryCell import make_theory_cell from Patterns.GrowthTheoryCell_100_3BranchDevices import make_theory_cell_3br from Patterns.GrowthTheoryCell_100_4BranchDevices import make_theory_cell_4br from gdsCAD_py3.core import Cell, Boundary, CellArray, Layout, Path from gdsCAD_py3.shapes import Box, Rectangle, Label from gdsCAD_py3.templates100 import Wafer_GridStyle, dashed_line WAFER_ID = 'XXXX' # CHANGE THIS FOR EACH DIFFERENT WAFER PATTERN = 'SQ1.2' putOnWafer = True # Output full wafer or just a single pattern? HighDensity = False # High density of triangles? glbAlignmentMarks = False tDicingMarks = 10. # Dicing mark line thickness (um) rotAngle = 0. # Rotation angle of the membranes wafer_r = 25e3 waferVer = '100 Membranes Multi-Use v1.2'.format(int(wafer_r / 1000)) waferLabel = waferVer + '\n' + date.today().strftime("%d%m%Y") # Layers l_smBeam = 0 l_lgBeam = 1 l_drawing = 100 # %% Wafer template for MBE growth class MBE100Wafer(Wafer_GridStyle): """ A 2" wafer divided into square cells """ def __init__(self, name, cells=None): Wafer_GridStyle.__init__(self, name=name, cells=cells, block_gap=1200.) # The placement of the wafer alignment markers am_x = 1.5e4 am_y = 1.5e4 self.align_pts = np.array([am_x, am_y]) self.align_pts = np.vstack((self.align_pts, self.align_pts * (-1, 1))) # Reflect about y-axis self.align_pts = np.vstack((self.align_pts, self.align_pts * (1, -1))) # Reflect about x-axis self.wafer_r = 25e3 self.block_size = np.array([10e3, 10e3]) self._place_blocks(radius=self.wafer_r + 5e3) # if glbAlignmentMarks: # self.add_aligment_marks(l_lgBeam) # self.add_orientation_text(l_lgBeam) # self.add_dicing_marks() # l_lgBeam, mkWidth=mkWidth Width of dicing marks self.add_blocks() self.add_wafer_outline(layers=l_drawing) self.add_dashed_dicing_marks(layers=[l_lgBeam]) self.add_block_labels(layers=[l_lgBeam]) self.add_prealignment_markers(layers=[l_lgBeam]) self.add_tem_membranes([0.08, 0.012, 0.028, 0.044], 2000, 1, l_smBeam) self.add_theory_cells() self.add_chip_labels() # self.add_blockLabels(l_lgBeam) # self.add_cellLabels(l_lgBeam) bottom = np.array([0, -self.wafer_r * 0.9]) # top = np.array([0, -1]) * bottom self.add_waferLabel(waferLabel, l_drawing, pos=bottom) def add_block_labels(self, layers): txtSize = 800 for (i, pt) in enumerate(self.block_pts): origin = (pt + np.array([0.5, 0.5])) * self.block_size blk_lbl = self.blockcols[pt[0]] + self.blockrows[pt[1]] for l in layers: txt = Label(blk_lbl, txtSize, layer=l) bbox = txt.bounding_box offset = np.array(pt) txt.translate(-np.mean(bbox, 0)) # Center text around origin lbl_cell = Cell("lbl_" + blk_lbl) lbl_cell.add(txt) origin += np.array([0, 0]) self.add(lbl_cell, origin=origin) def add_dashed_dicing_marks(self, layers): if type(layers) is not list: layers = [layers] width = 10. / 2 dashlength = 2000 r = self.wafer_r rng = np.floor(self.wafer_r / self.block_size).astype(int) dmarks = Cell('DIC_MRKS') for l in layers: for x in np.arange(-rng[0], rng[0] + 1) * self.block_size[0]: y = np.sqrt(r ** 2 - x ** 2) vm = dashed_line([x, y], [x, -y], dashlength, width, layer=l) dmarks.add(vm) for y in np.arange(-rng[1], rng[1] + 1) * self.block_size[1]: x = np.sqrt(r ** 2 - y ** 2) hm = dashed_line([x, y], [-x, y], dashlength, width, layer=l) dmarks.add(hm) self.add(dmarks) def add_prealignment_markers(self, layers, mrkr_size=7): if mrkr_size % 2 == 0: # Number is even, but we need odd numbers mrkr_size += 1 if type(layers) is not list: layers = [layers] for l in layers: rect_size = 10. # 10 um large PAMM rectangles marker_rect = Rectangle([-rect_size / 2., -rect_size / 2.], [rect_size / 2., rect_size / 2.], layer=l) marker = Cell('10umMarker') marker.add(marker_rect) # Make one arm of the PAMM array marker_arm = Cell('PAMM_Arm') # Define the positions of the markers, they increase in spacing by 1 um each time: mrkr_positions = [75 * n + (n - 1) * n // 2 for n in range(1, (mrkr_size - 1) // 2 + 1)] for pos in mrkr_positions: marker_arm.add(marker, origin=[pos, 0]) # Build the final PAMM Marker pamm_cell = Cell('PAMM_Marker') pamm_cell.add(marker) # Center marker pamm_cell.add(marker_arm) # Right arm pamm_cell.add(marker_arm, rotation=180) # Left arm pamm_cell.add(marker_arm, rotation=90) # Top arm pamm_cell.add(marker_arm, rotation=-90) # Bottom arm for pos in mrkr_positions: pamm_cell.add(marker_arm, origin=[pos, 0], rotation=90) # Top arms pamm_cell.add(marker_arm, origin=[-pos, 0], rotation=90) pamm_cell.add(marker_arm, origin=[pos, 0], rotation=-90) # Bottom arms pamm_cell.add(marker_arm, origin=[-pos, 0], rotation=-90) # Make the 4 tick marks that mark the center of the array h = 30. w = 100. tick_mrk = Rectangle([-w / 2., -h / 2.], [w / 2, h / 2.], layer=l) tick_mrk_cell = Cell("TickMark") tick_mrk_cell.add(tick_mrk) pos = mrkr_positions[-1] + 75 + w / 2. pamm_cell.add(tick_mrk_cell, origin=[pos, 0]) pamm_cell.add(tick_mrk_cell, origin=[-pos, 0]) pamm_cell.add(tick_mrk_cell, origin=[0, pos], rotation=90) pamm_cell.add(tick_mrk_cell, origin=[0, -pos], rotation=90) center_x, center_y = (5000, 5000) for block in self.blocks: block.add(pamm_cell, origin=(center_x + 2000, center_y)) block.add(pamm_cell, origin=(center_x - 2000, center_y)) def add_tem_membranes(self, widths, length, pitch, layer): tem_membranes = Cell('TEM_Membranes') n = 5 curr_y = 0 for width in widths: membrane = Path([(-length / 2., 0), (length / 2., 0)], width=width, layer=layer) membrane_cell = Cell('Membrane_w{:.0f}'.format(width * 1000)) membrane_cell.add(membrane) membrane_array = CellArray(membrane_cell, 1, n, (0, pitch)) membrane_array_cell = Cell('MembraneArray_w{:.0f}'.format(width * 1000)) membrane_array_cell.add(membrane_array) tem_membranes.add(membrane_array_cell, origin=(0, curr_y)) curr_y += n * pitch n2 = 3 tem_membranes2 = Cell('Many_TEM_Membranes') tem_membranes2.add(CellArray(tem_membranes, 1, n2, (0, n * len(widths) * pitch))) center_x, center_y = (5000, 5000) for block in self.blocks: block.add(tem_membranes2, origin=(center_x, center_y + 2000)) def add_theory_cells(self): theory_cells = Cell('TheoryCells') theory_cells.add(make_theory_cell(wafer_orient='100'), origin=(-400, 0)) theory_cells.add(make_theory_cell_3br(), origin=(0, 0)) theory_cells.add(make_theory_cell_4br(), origin=(400, 0)) center_x, center_y = (5000, 5000) for block in self.blocks: block.add(theory_cells, origin=(center_x, center_y - 2000)) def add_chip_labels(self): wafer_lbl = PATTERN + '\n' + WAFER_ID text = Label(wafer_lbl, 20., layer=l_lgBeam) text.translate(tuple(np.array(-text.bounding_box.mean(0)))) # Center justify label chip_lbl_cell = Cell('chip_label') chip_lbl_cell.add(text) center_x, center_y = (5000, 5000) for block in self.blocks: block.add(chip_lbl_cell, origin=(center_x, center_y - 2850)) class Frame(Cell): """ Make a frame for writing to with ebeam lithography Params: -name of the frame, just like when naming a cell -size: the size of the frame as an array [xsize,ysize] """ def __init__(self, name, size, border_layers): if not (type(border_layers) == list): border_layers = [border_layers] Cell.__init__(self, name) self.size_x, self.size_y = size # Create the border of the cell for l in border_layers: self.border = Box( (-self.size_x / 2., -self.size_y / 2.), (self.size_x / 2., self.size_y / 2.), 1, layer=l) self.add(self.border) # Add border to the frame self.align_markers = None def make_align_markers(self, t, w, position, layers, joy_markers=False, camps_markers=False): if not (type(layers) == list): layers = [layers] top_mk_cell = Cell('AlignmentMark') for l in layers: if not joy_markers: am0 = Rectangle((-w / 2., -w / 2.), (w / 2., w / 2.), layer=l) rect_mk_cell = Cell("RectMarker") rect_mk_cell.add(am0) top_mk_cell.add(rect_mk_cell) elif joy_markers: crosspts = [(0, 0), (w / 2., 0), (w / 2., t), (t, t), (t, w / 2), (0, w / 2), (0, 0)] crosspts.extend(tuple(map(tuple, (-np.array(crosspts)).tolist()))) am0 = Boundary(crosspts, layer=l) # Create gdsCAD shape joy_mk_cell = Cell("JOYMarker") joy_mk_cell.add(am0) top_mk_cell.add(joy_mk_cell) if camps_markers: emw = 20. # 20 um e-beam marker width camps_mk = Rectangle((-emw / 2., -emw / 2.), (emw / 2., emw / 2.), layer=l) camps_mk_cell = Cell("CAMPSMarker") camps_mk_cell.add(camps_mk) top_mk_cell.add(camps_mk_cell, origin=[100., 100.]) top_mk_cell.add(camps_mk_cell, origin=[100., -100.]) top_mk_cell.add(camps_mk_cell, origin=[-100., 100.]) top_mk_cell.add(camps_mk_cell, origin=[-100., -100.]) self.align_markers = Cell("AlignMarkers") self.align_markers.add(top_mk_cell, origin=np.array(position) * np.array([1, -1])) self.align_markers.add(top_mk_cell, origin=np.array(position) * np.array([-1, -1])) self.align_markers.add(top_mk_cell, origin=np.array(position) * np.array([1, 1])) self.align_markers.add(top_mk_cell, origin=np.array(position) * np.array([-1, 1])) self.add(self.align_markers) def make_slit_array(self, _pitches, spacing, _widths, _lengths, rot_angle, array_height, array_width, array_spacing, layers): if not (type(layers) == list): layers = [layers] if not (type(_pitches) == list): _pitches = [_pitches] if not (type(_lengths) == list): _lengths = [_lengths] if not (type(_widths) == list): _widths = [_widths] manyslits = i = j = None for l in layers: i = -1 j = -1 manyslits = Cell("SlitArray") pitch = _pitches[0] for length in _lengths: j += 1 i = -1 for width in _widths: # for pitch in pitches: i += 1 if i % 3 == 0: j += 1 # Move to array to next line i = 0 # Restart at left pitch_v = pitch / np.cos(np.deg2rad(rot_angle)) # widthV = width / np.cos(np.deg2rad(rotAngle)) nx = int(array_width / (length + spacing)) ny = int(array_height / pitch_v) # Define the slits slit = Cell("Slits") rect = Rectangle((-length / 2., -width / 2.), (length / 2., width / 2.), layer=l) rect = rect.copy().rotate(rot_angle) slit.add(rect) slits = CellArray(slit, nx, ny, (length + spacing, pitch_v)) slits.translate((-(nx - 1) * (length + spacing) / 2., -(ny - 1) * pitch_v / 2.)) slit_array = Cell("SlitArray") slit_array.add(slits) text = Label('w/p/l\n%i/%i/%i' % (width * 1000, pitch, length), 5, layer=l) lbl_vertical_offset = 1.35 if j % 2 == 0: text.translate( tuple(np.array(-text.bounding_box.mean(0)) + np.array(( 0, -array_height / lbl_vertical_offset)))) # Center justify label else: text.translate( tuple(np.array(-text.bounding_box.mean(0)) + np.array(( 0, array_height / lbl_vertical_offset)))) # Center justify label slit_array.add(text) manyslits.add(slit_array, origin=((array_width + array_spacing) * i, ( array_height + 2. * array_spacing) * j - array_spacing / 2.)) self.add(manyslits, origin=(-i * (array_width + array_spacing) / 2, -(j + 1.5) * ( array_height + array_spacing) / 2)) # %%Create the pattern that we want to write lgField = Frame("LargeField", (2000., 2000.), []) # Create the large write field lgField.make_align_markers(20., 200., (850., 850.), l_lgBeam, joy_markers=True, camps_markers=True) # Define parameters that we will use for the slits widths = [0.004, 0.008, 0.012, 0.016, 0.028, 0.044] pitches = [1.0, 2.0] lengths = [10., 20.] smFrameSize = 400 slitColumnSpacing = 3. # Create the smaller write field and corresponding markers smField1 = Frame("SmallField1", (smFrameSize, smFrameSize), []) smField1.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) smField1.make_slit_array(pitches[0], slitColumnSpacing, widths, lengths[0], rotAngle, 100, 100, 30, l_smBeam) smField2 = Frame("SmallField2", (smFrameSize, smFrameSize), []) smField2.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) smField2.make_slit_array(pitches[0], slitColumnSpacing, widths, lengths[1], rotAngle, 100, 100, 30, l_smBeam) smField3 = Frame("SmallField3", (smFrameSize, smFrameSize), []) smField3.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) smField3.make_slit_array(pitches[1], slitColumnSpacing, widths, lengths[0], rotAngle, 100, 100, 30, l_smBeam) smField4 = Frame("SmallField4", (smFrameSize, smFrameSize), []) smField4.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) smField4.make_slit_array(pitches[1], slitColumnSpacing, widths, lengths[1], rotAngle, 100, 100, 30, l_smBeam) centerAlignField = Frame("CenterAlignField", (smFrameSize, smFrameSize), []) centerAlignField.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) # Add everything together to a top cell topCell = Cell("TopCell") topCell.add(lgField) smFrameSpacing = 400 # Spacing between the three small frames dx = smFrameSpacing + smFrameSize dy = smFrameSpacing + smFrameSize topCell.add(smField1, origin=(-dx / 2., dy / 2.)) topCell.add(smField2, origin=(dx / 2., dy / 2.)) topCell.add(smField3, origin=(-dx / 2., -dy / 2.)) topCell.add(smField4, origin=(dx / 2., -dy / 2.)) topCell.add(centerAlignField, origin=(0., 0.)) topCell.spacing = np.array([4000., 4000.]) # %%Create the layout and output GDS file layout = Layout('LIBRARY') if putOnWafer: # Fit as many patterns on a 2inch wafer as possible wafer = MBE100Wafer('MembranesWafer', cells=[topCell]) layout.add(wafer) # layout.show() else: # Only output a single copy of the pattern (not on a wafer) layout.add(topCell) layout.show() filestring = str(waferVer) + '_' + WAFER_ID + '_' + date.today().strftime("%d%m%Y") + ' dMark' + str(tDicingMarks) filename = filestring.replace(' ', '_') + '.gds' layout.save(filename) cell_layout = Layout('LIBRARY') cell_layout.add(wafer.blocks[0]) cell_layout.save(filestring.replace(' ', '_') + '_block' + '.gds') # Output up chip for doing aligned jobs layout_field = Layout('LIBRARY') layout_field.add(topCell) layout_field.save(filestring.replace(' ', '_') + '_2mmField.gds')
Martin09/E-BeamPatterns
100 Wafers - 1cm Squares/Multi-Use Pattern/v1.2/MembraneDesign_100Wafer_v1.1.py
Python
gpl-3.0
17,018
<?php /** * Posts shortcode item template * * Simple post item template * Consist of: * image, * title * * @package WebMan Amplifier * @subpackage Shortcodes * * @since 1.0 * @version 1.9.1 * * @uses array $helper Contains shortcode $atts array plus additional helper variables. */ $link_output = array( '', '' ); if ( $helper['link'] ) { $link_output = array( '<a' . $helper['link'] . wm_schema_org( 'bookmark' ) . '>', '</a>' ); } ?> <article class="<?php echo esc_attr( $helper['item_class'] ); ?>"<?php echo wm_schema_org( 'article' ); ?>> <?php if ( has_post_thumbnail( $helper['post_id'] ) ) { echo '<div class="wm-posts-element wm-html-element image image-container"' . wm_schema_org( 'image' ) . '>'; echo $link_output[0]; the_post_thumbnail( $helper['image_size'], array( 'title' => esc_attr( get_the_title( get_post_thumbnail_id( $helper['post_id'] ) ) ) ) ); echo $link_output[1]; echo '</div>'; } ?> <div class="wm-posts-element wm-html-element title"><?php echo '<' . tag_escape( $helper['atts']['heading_tag'] ) . wm_schema_org( 'name' ) . '>'; echo $link_output[0]; the_title(); echo $link_output[1]; echo '</' . tag_escape( $helper['atts']['heading_tag'] ) . '>'; ?></div> </article>
webmandesign/mustang-lite
webman-amplifier/content-shortcode-posts-post-simple.php
PHP
gpl-3.0
1,285
/* * queue.hpp * * Created on: 14 ott 2015 * Author: Marco */ #ifndef SOURCE_UTILITIES_INCLUDE_SHARED_QUEUE_HPP_ #define SOURCE_UTILITIES_INCLUDE_SHARED_QUEUE_HPP_ #include <deque> #include <condition_variable> #include <mutex> #include <utilities/include/atend.hpp> #include <utilities/include/singleton.hpp> #include <utilities/include/debug.hpp> #include <utilities/include/strings.hpp> namespace utilities { /** * Classe generale che implementa una coda condivisa da piu' thread */ template<typename T> class shared_queue : public singleton<shared_queue<T>> { std::deque<T> data; std::mutex lk; std::condition_variable cv; friend class singleton<shared_queue<T>>; shared_queue(){}; public: /** * Accoda un elemento nella coda * @param Elemento da accodare nella coda */ void enqueue(const T obj) { LOGF; std::lock_guard<std::mutex> guard(lk); data.push_back(obj); LOGD("FileName: " << utf8_encode(std::wstring(obj->FileName, obj->FileNameLength / sizeof(wchar_t))) << " Action: "<< (int)obj->Action); cv.notify_all(); } /** * Elimina il primo elemento dalla coda e lo ritorna * @return Elemento estratto dalla coda */ T dequeue(void){ std::unique_lock<std::mutex> guard(lk); on_return<> ret([this](){ data.pop_front(); });//FIXME: viene davvero poi ottimizzato? cv.wait(guard, [this](){ return !data.empty(); }); return data.front(); } inline bool empty() { //FIXME: Serve sincronizzare? std::lock_guard<std::mutex> guard(lk); return data.empty(); } }; } #endif /* SOURCE_UTILITIES_INCLUDE_SHARED_QUEUE_HPP_ */
Aleb92/PMB-PimpMyBackup
source/utilities/include/shared_queue.hpp
C++
gpl-3.0
1,643
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o 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.db4o.db4ounit.common.soda.ordered; import com.db4o.*; import com.db4o.query.*; import db4ounit.*; import db4ounit.extensions.*; /** * COR-1062 */ public class OrderedOrConstraintTestCase extends AbstractDb4oTestCase{ public static class Item{ public Item(int int_, boolean boolean_) { _int = int_; _boolean = boolean_; } public int _int; public boolean _boolean; } @Override protected void store() throws Exception { store(new Item(10, false)); store(new Item(4, true)); super.store(); } public void test(){ Query query = newQuery(Item.class); Constraint c1 = query.descend("_int").constrain(9).greater(); Constraint c2 = query.descend("_boolean").constrain(true); c1.or(c2); query.descend("_int").orderAscending(); ObjectSet<Item> objectSet = query.execute(); Assert.areEqual(2, objectSet.size()); Item item = objectSet.next(); Assert.areEqual(4, item._int); item = objectSet.next(); Assert.areEqual(10, item._int); } }
potty-dzmeia/db4o
src/db4oj.tests/src/com/db4o/db4ounit/common/soda/ordered/OrderedOrConstraintTestCase.java
Java
gpl-3.0
1,737
/* Copyright (C) 2011 Lorenzo Bernardi (fastlorenzo@gmail.com) 2010 Ben Van Daele (vandaeleben@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 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 be.bernardi.mvforandroid.data; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "mvforandroid.db"; private static final int SCHEMA_VERSION = 3; public final Usage usage; public final Credit credit; public final Topups topups; public final Msisdns msisdns; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); this.usage = new Usage(); this.credit = new Credit(); this.topups = new Topups(); this.msisdns = new Msisdns(); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS " + Usage.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "timestamp INTEGER NOT NULL, " + "duration INTEGER, " + "type INTEGER, " + "incoming INTEGER, " + "contact TEXT, " + "cost REAL);"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Topups.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "amount REAL NOT NULL, " + "method TEXT NOT NULL, " + "executed_on INTEGER NOT NULL, " + "received_on INTEGER, " + "status TEXT NOT NULL);"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Credit.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "valid_until INTEGER NULL, " + "expired INTEGER NOT NULL, " + "sms INTEGER NOT NULL, " + "data INTEGER NOT NULL, " + "credits REAL NOT NULL, " + "price_plan TEXT NOT NULL, " + "sms_son INTEGER NOT NULL);"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Msisdns.TABLE_NAME + " (msisdn TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { switch(oldVersion) { case 1: if(newVersion < 2) { return; } case 2: { db.execSQL("DROP TABLE " + Topups.TABLE_NAME + ";"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Topups.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "amount REAL NOT NULL, " + "method TEXT NOT NULL, " + "executed_on INTEGER NOT NULL, " + "received_on INTEGER, " + "status TEXT NOT NULL);"); break; } } } private static SimpleDateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static Date getDateFromAPI(String dateString) { try { return apiFormat.parse(dateString); } catch(ParseException e) { return null; } } public class Credit { private static final String TABLE_NAME = "credit"; public void update(JSONObject json, boolean data_only) throws JSONException, NumberFormatException { Cursor query = getWritableDatabase().query(TABLE_NAME, new String[] { "_id" }, null, null, null, null, null, null); ContentValues values = new ContentValues(); values.put("valid_until", getDateFromAPI(json.getString("valid_until")).getTime()); values.put("expired", (Boolean.parseBoolean(json.getString("is_expired")) ? 1 : 0)); if(Boolean.parseBoolean(json.getString("is_expired")) == true) { values.put("data", 0); values.put("credits", 0); } else { values.put("data", Long.parseLong(json.getString("data"))); } values.put("price_plan", json.getString("price_plan")); if(!data_only) { values.put("credits", Double.parseDouble(json.getString("credits"))); values.put("sms", Integer.parseInt(json.getString("sms"))); values.put("sms_son", Integer.parseInt(json.getString("sms_super_on_net"))); } else { values.put("credits", 0); values.put("sms", 0); values.put("sms_son", 0); } if(query.getCount() == 0) { // No credit info stored yet, insert a row getWritableDatabase().insert(TABLE_NAME, "valid_until", values); } else { // Credit info present already, so update it getWritableDatabase().update(TABLE_NAME, values, null, null); } query.close(); } public long getValidUntil() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); long result; if(c.moveToFirst()) result = c.getLong(1); else result = 0; c.close(); return result; } public boolean isExpired() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); boolean result; if(c.moveToFirst()) result = c.getLong(2) == 1; else result = true; c.close(); return result; } public int getRemainingSms() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); int result; if(c.moveToFirst()) result = c.getInt(3); else result = 0; c.close(); return result; } public long getRemainingData() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); long result; if(c.moveToFirst()) result = c.getLong(4); else result = 0; c.close(); return result; } public double getRemainingCredit() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); double result; if(c.moveToFirst()) result = c.getDouble(5); else result = 0; c.close(); return result; } public int getPricePlan() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); int result; if(c.moveToFirst()) result = c.getInt(6); else result = 0; c.close(); return result; } public int getRemainingSmsSuperOnNet() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); int result; if(c.moveToFirst()) result = c.getInt(7); else result = 0; c.close(); return result; } } public class Usage { private static final String TABLE_NAME = "usage"; public static final int TYPE_DATA = 0; public static final int TYPE_SMS = 1; public static final int TYPE_VOICE = 2; public static final int TYPE_MMS = 3; public static final int ORDER_BY_DATE = 1; public void update(JSONArray jsonArray) throws JSONException { getWritableDatabase().delete(TABLE_NAME, null, null); getWritableDatabase().beginTransaction(); for(int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); insert(json); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); } public void insert(JSONObject json) throws JSONException { // "timestamp INTEGER NOT NULL, " + // "duration INTEGER NOT NULL, " + // "type INTEGER NOT NULL, " + // "incoming INTEGER NOT NULL, " + // "contact TEXT NOT NULL, " + // "cost REAL NOT NULL);"); ContentValues values = new ContentValues(); values.put("timestamp", getDateFromAPI(json.getString("start_timestamp")).getTime()); values.put("duration", json.getLong("duration_connection")); if(Boolean.parseBoolean(json.getString("is_data"))) values.put("type", TYPE_DATA); if(Boolean.parseBoolean(json.getString("is_sms"))) values.put("type", TYPE_SMS); if(Boolean.parseBoolean(json.getString("is_voice"))) values.put("type", TYPE_VOICE); if(Boolean.parseBoolean(json.getString("is_mms"))) values.put("type", TYPE_MMS); values.put("incoming", (Boolean.parseBoolean(json.getString("is_incoming")) ? 1 : 0)); values.put("contact", json.getString("to")); values.put("cost", Double.parseDouble(json.getString("price"))); getWritableDatabase().insert(TABLE_NAME, "timestamp", values); } public Cursor get(long id) { return getReadableDatabase().query(TABLE_NAME, null, "_id=" + id, null, null, null, null); } /** * Returns a cursor over the Usage table. * * @param isSearch * Whether to include usage records obtained by a search, or * (xor) those obtained through auto-updating. * @param order * The constant representing the field to order the cursor * by. * @param ascending * Whether the order should be ascending or descending. */ public Cursor get(int order, boolean ascending) { String orderBy = null; switch(order) { case ORDER_BY_DATE: orderBy = "timestamp " + (ascending ? "asc" : "desc"); } return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, orderBy); } public long getTimestamp(Cursor c) { return c.getLong(1); } public long getduration(Cursor c) { return c.getLong(2); } public int getType(Cursor c) { return c.getInt(3); } public boolean isIncoming(Cursor c) { return c.getInt(4) == 1; } public String getContact(Cursor c) { return c.getString(5); } public double getCost(Cursor c) { return c.getDouble(6); } } public class Topups { private static final String TABLE_NAME = "topups"; public void update(JSONArray jsonArray, boolean b) throws JSONException { getWritableDatabase().delete(TABLE_NAME, null, null); for(int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); insert(json); } } private void insert(JSONObject json) throws JSONException { ContentValues values = new ContentValues(); values.put("amount", Double.parseDouble(json.getString("amount"))); values.put("method", json.getString("method")); values.put("executed_on", getDateFromAPI(json.getString("executed_on")).getTime()); Log.d("MVFA", json.getString("payment_received_on")); if(!json.getString("payment_received_on").equals("null")) values.put("received_on", getDateFromAPI(json.getString("payment_received_on")).getTime()); values.put("status", json.getString("status")); getWritableDatabase().insert(TABLE_NAME, "timestamp", values); } public Cursor getAll() { return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); } public double getAmount(Cursor c) { return c.getDouble(1); } public String getMethod(Cursor c) { return c.getString(2); } public long getExecutedOn(Cursor c) { return c.getLong(3); } public long getReceivedOn(Cursor c) { return c.getLong(4); } public String getStatus(Cursor c) { return c.getString(5); } } public class Msisdns { private static final String TABLE_NAME = "msisdns"; public void update(JSONArray jsonArray) throws JSONException { getWritableDatabase().delete(TABLE_NAME, null, null); for(int i = 0; i < jsonArray.length(); i++) { String msisdn = jsonArray.getString(i); insert(msisdn); } } private void insert(String msisdn) throws JSONException { ContentValues values = new ContentValues(); values.put("msisdn", msisdn); getWritableDatabase().insert(TABLE_NAME, "msisdn", values); } public Cursor getAll() { return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); } public String[] getMsisdnList() { Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null); String[] result = null; int i = 0; if(c.moveToFirst()) { do { i++; } while(c.moveToNext()); result = new String[i]; c.moveToFirst(); i = 0; do { if(c.getString(0) != null) { result[i] = c.getString(0); i++; } } while(c.moveToNext()); } c.close(); return result; } } }
fastlorenzo/mvfa
src/be/bernardi/mvforandroid/data/DatabaseHelper.java
Java
gpl-3.0
12,330
<?php namespace krFrame\Src\initTemplate; use \krFrame\Src\Error\Error; class SetCustomTaxonomies { private $taxonomies; private $taxonomy; private $name; public function __construct($array) { if (!is_array($array)) { return false; } $this->taxonomies = $array; $this->init(); } private function init() { foreach ($this->taxonomies as $this->name => $this->taxonomy) { if ($this->validate()) { register_taxonomy($this->name, $this->taxonomy['post_type'], array( 'hierarchical' => $this->taxonomy['hierarchical'], 'label' => __($this->taxonomy['label'], 'krframe'), 'query_var' => $this->taxonomy['query_var'], 'rewrite' => array( 'slug' => __($this->taxonomy['rewrite']['slug'], 'krframe'), 'with_front' => $this->taxonomy['rewrite']['with_front'] ) ) ); } } } private function validate() { if (!isset($this->taxonomy['post_type']) || !isset($this->taxonomy['hierarchical']) || !isset($this->taxonomy['label']) || !isset($this->taxonomy['hierarchical']) || !isset($this->taxonomy['query_var']) || !isset($this->taxonomy['rewrite']) || !isset($this->taxonomy['rewrite']['slug']) || !isset($this->taxonomy['rewrite']['with_front']) ) { $error = new Error(); $error->render(16); return false; } return true; } }
dawidryba/krframe_theme
krFrame/src/initTemplate/SetCustomTax.php
PHP
gpl-3.0
1,683
from rest_framework import serializers from .models import CustomerWallet class CustomerWalletSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CustomerWallet fields = ("wallet_id", "msisdn", "balance", "type", "status")
kyrelos/vitelco-mobile-money-wallet
app_dir/customer_wallet_management/serializers.py
Python
gpl-3.0
268
package omr.gui; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; /** * Menu bar of the main window. */ public class Menu extends JMenuBar implements ActionListener { private static final long serialVersionUID = 1L; private Gui gui; private JMenuItem newProject; private JMenuItem openProject; private JMenuItem saveProject; private JMenuItem saveProjectAs; private JMenuItem importSheets; private JMenuItem exportAnswers; private JMenuItem exportResults; private JMenuItem mailFeedback; public Menu(Gui gui) { this.gui = gui; UndoSupport undoSupport = gui.getUndoSupport(); // File menu JMenu fileMenu = new JMenu("Bộ Bài Thi"); fileMenu.setMnemonic(KeyEvent.VK_F); fileMenu.setForeground(new Color(48,47,95)); fileMenu.setFont(new Font("Century Gothic", Font.BOLD, 14)); add(fileMenu); // New project newProject = new JMenuItem("Tạo Bộ Bài Thi Mới", KeyEvent.VK_N); newProject.addActionListener(this); fileMenu.add(newProject); // Open project openProject = new JMenuItem("Mở Bộ Bài Thi", KeyEvent.VK_O); openProject.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)); openProject.addActionListener(this); fileMenu.add(openProject); // Save project saveProject = new JMenuItem("Lưu Bộ Bài Thi", KeyEvent.VK_A); saveProject.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); saveProject.addActionListener(this); fileMenu.add(saveProject); // Save project as saveProjectAs = new JMenuItem("Lưu Bộ Bài Thi Tại .....", KeyEvent.VK_S); //saveProjectAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); saveProjectAs.addActionListener(this); fileMenu.add(saveProjectAs); // Sheets management JMenu sheetsMenu = new JMenu("Bài Thi"); sheetsMenu.setMnemonic(KeyEvent.VK_F); sheetsMenu.setForeground(new Color(48,47,95)); sheetsMenu.setFont(new Font("Century Gothic", Font.BOLD, 14)); //menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items"); add(sheetsMenu); importSheets = new JMenuItem("Nhập Bài Thi", KeyEvent.VK_I); importSheets.getAccessibleContext().setAccessibleDescription("Nhập hình ảnh bài thi vào bộ bài thi"); importSheets.addActionListener(this); sheetsMenu.add(importSheets); // Export answers exportAnswers = new JMenuItem("Xuất Câu Trả Lời", KeyEvent.VK_C); exportAnswers.getAccessibleContext().setAccessibleDescription("Xuất Toàn Bộ Câu Trả Lời Ra Một Tệp Tin"); exportAnswers.addActionListener(this); sheetsMenu.add(exportAnswers); // Export results exportResults = new JMenuItem("Xuất Kết Quả", KeyEvent.VK_R); exportResults.getAccessibleContext().setAccessibleDescription("Xuất Toàn Bộ Kết Quả Ra Một Tệp Tin"); exportResults.addActionListener(this); sheetsMenu.add(exportResults); // Edit menu JMenu editMenu = new JMenu("Tuỳ Chỉnh"); editMenu.setMnemonic(KeyEvent.VK_E); editMenu.setForeground(new Color(48,47,95)); editMenu.setFont(new Font("Century Gothic", Font.BOLD, 14)); add(editMenu); // Undo JMenuItem undo = new JMenuItem("Undo", KeyEvent.VK_U); undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK)); undo.addActionListener(undoSupport.getUndoAction()); editMenu.add(undo); // Redo JMenuItem redo = new JMenuItem("Redo", KeyEvent.VK_R); redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)); redo.addActionListener(undoSupport.getRedoAction()); editMenu.add(redo); // Cut JMenuItem cut = new JMenuItem("Cắt", KeyEvent.VK_T); cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); //cut.addActionListener(new CutAction(undoManager)); //editMenu.add(cut); // Copy JMenuItem copy = new JMenuItem("Sao chép", KeyEvent.VK_C); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)); //copy.addActionListener(new CopyAction(undoManager)); //editMenu.add(copy); // Paste JMenuItem paste = new JMenuItem("Dán", KeyEvent.VK_P); paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK)); //paste.addActionListener(new PasteAction(undoManager)); //editMenu.add(paste); // Delete JMenuItem delete = new JMenuItem("Xoá", KeyEvent.VK_D); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); //delete.addActionListener(new DeleteAction(undoManager)); editMenu.add(delete); // // Mail feedback // JMenu mailMenu = new JMenu("Gửi Mail"); // mailMenu.setMnemonic(KeyEvent.VK_F); // //menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items"); // add(mailMenu); // // mailFeedback = new JMenuItem("Gửi Mail Kết Quả Cho Thí Sinh", KeyEvent.VK_M); // mailFeedback.getAccessibleContext().setAccessibleDescription("Gửi Mail Kết Quả Cho Thí Sinh"); // mailFeedback.addActionListener(this); // mailMenu.add(mailFeedback); } /** * Menu event listener. */ public void actionPerformed(ActionEvent event) { JMenuItem source = (JMenuItem)(event.getSource()); if (source == newProject) { gui.newProject(); } else if (source == openProject) { gui.openProject(); } else if (source == saveProject) { gui.saveProject(); } else if (source == saveProjectAs) { gui.saveProjectAs(); } else if (source == importSheets) { gui.importSheets(); } else if (source == exportAnswers) { gui.exportAnswers(); } else if (source == exportResults) { gui.exportResults(); } else if (source == mailFeedback) { gui.mailFeedback(); } } }
CaronLe/chanhthings2
src/omr/gui/Menu.java
Java
gpl-3.0
6,822
#!/usr/bin/env python2 import urllib2 import urllib from BeautifulSoup import BeautifulSoup import smtplib import ConfigParser # Retreive user information config = ConfigParser.ConfigParser() config.read('config.cfg') user = config.get('data','user') password = config.get('data','password') fromaddr = config.get('data','fromaddr') toaddr = config.get('data','toaddr') smtpserver = config.get('data','smtp_server') login_page='https://bugs.archlinux.org/index.php?do=authenticate' # Create message msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr) msg += 'Unassigned bugs \n\n' # build opener with HTTPCookieProcessor o = urllib2.build_opener( urllib2.HTTPCookieProcessor() ) urllib2.install_opener( o ) p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} ) f = o.open(login_page, p) data = f.read() # Archlinux url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index" # Community url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index" def parse_bugtrackerpage(url,count=1): print url # open bugtracker / parse page = urllib2.urlopen(url) soup = BeautifulSoup(page) data = soup.findAll('td',{'class':'task_id'}) msg = "" pages = False # Is there another page with unassigned bugs if soup.findAll('a',{'id': 'next' }) == []: page = False else: print soup.findAll('a',{'id': 'next'}) count += 1 pages = True print count # print all found bugs for f in data: title = f.a['title'].replace('Assigned |','') title = f.a['title'].replace('| 0%','') msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title) if pages == True: new = "%s&pagenum=%s" % (url,count) msg += parse_bugtrackerpage(new,count) return msg msg += '\n\nArchlinux: \n\n' msg += parse_bugtrackerpage(url) msg += '\n\nCommunity: \n\n' msg += parse_bugtrackerpage(url2) msg = msg.encode("utf8") # send mail server = smtplib.SMTP(smtpserver) server.sendmail(fromaddr, toaddr,msg) server.quit()
jelly/Utils
unassignedbugs.py
Python
gpl-3.0
2,592
/** * Balero CMS Project: Proyecto 100% Mexicano de código libre. * Página Oficial: http://www.balerocms.com * * @author Anibal Gomez <anibalgomez@icloud.com> * @copyright Copyright (C) 2015 Neblina Software. Derechos reservados. * @license Licencia BSD; vea LICENSE.txt */ package com.neblina.balero.util; import org.owasp.html.Sanitizers; public class AntiXSS { /** * Sanitize common elements b, p, etc. img and a. * @author Anibal Gomez * @param input Unsafe Input * @return Safe Output */ public String blind(String input) { org.owasp.html.PolicyFactory policy = Sanitizers.STYLES .and(Sanitizers.FORMATTING) .and(Sanitizers.IMAGES) .and(Sanitizers.LINKS); String output = policy.sanitize(input); return output; } }
neblina-software/balerocms-v2
src/main/java/com/neblina/balero/util/AntiXSS.java
Java
gpl-3.0
854
OJ.extendClass( 'NwEvent', [OjEvent], { '_get_props_' : { 'data' : null }, '_constructor' : function(type/*, bubbles = false, cancelable = false, data = null*/){ var ln = arguments.length; this._super(OjEvent, '_constructor', ln > 3 ? [].slice.call(arguments, 0, 3) : arguments); if(ln > 3){ this._data = arguments[3]; } } } );
NuAge-Solutions/NW
src/js/events/NwEvent.js
JavaScript
gpl-3.0
361
<?php /** * Catch-a spammer with a CAPTCHA. * * @package catcha * @version 1.0.1 * @author Jublo IT Solutions <support@jublo.net> * @copyright 2013-2014 Jublo IT Solutions <support@jublo.net> * * 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/>. */ /** * Main Catcha class * * @package catcha */ class Catcha { /** * Background color for the challenge image * * @access protected */ protected $_imageColorBackground; /** * Foreground color for the challenge image * * @access protected */ protected $_imageColorForeground; /** * Font file to use for challenge image * * @access protected */ protected $_imageFont; /** * Height of the challenge image canvas * * @access protected */ protected $_imageHeight; /** * Width of the challenge image canvas * * @access protected */ protected $_imageWidth; /** * Challenge equation to ask * * @access protected */ protected $_equation; /** * Challenge result * * @access protected */ protected $_result; /** * Class constructor * * @param void * * @return void */ public function __construct() { // check for required extensions $this->_checkExtensions(); // initialize member variables $this->setImageSize(100, 25); $this->setImageFont(dirname(__FILE__) . '/font/Averia-Light.ttf'); $this->setImageColorBackground('FFF'); $this->setImageColorForeground('000'); // generate the challenge data $this->newChallenge(); } /** * Get the canvas size of the challenge image * * @return array($width, $height) The canvas size */ public function getImageSize() { return array($this->_imageWidth, $this->_imageHeight); } /** * Set the canvas size of the challenge image * * @param int $width The image width (>= 30px) * @param int $height The image height (>= 10px) * * @return void */ public function setImageSize($width, $height) { // validate $width = intval($width); $height = intval($height); if ($width < 30 || $height < 10) { throw new Exception('setImageSize: invalid parameters'); } // store given values $this->_imageWidth = $width; $this->_imageHeight = $height; } /** * Get the font file to be used for drawing the challenge characters * * @return string $font_file The full path to font file (*.ttf) */ public function getImageFont() { return $this->_imageFont; } /** * Set the font file to be used for drawing the challenge characters * * @param string $font_file The full path to font file (*.ttf) * * @return void */ public function setImageFont($font_file) { // validate if (! @file_exists($font_file) || ! @is_readable($font_file) ) { throw new Exception('setImageFont: invalid parameters'); } // store given value $this->_imageFont = $font_file; } /** * Set the background color to use in the challenge image * * @param string $color_back Color to paint the canvas (HEX RGB or RRGGBB) * * @return void */ public function setImageColorBackground($color_back) { // validate if (! $color_back = $this->_validateColorHex($color_back)) { throw new Exception('setImageColorBackground: invalid parameters'); } // store given value $this->_imageColorBackground = $color_back; } /** * Set the foreground color to use in the challenge image * * @param string $color_fore Color to draw the equation (HEX RGB or RRGGBB) * * @return void */ public function setImageColorForeground($color_fore) { // validate if (! $color_fore = $this->_validateColorHex($color_fore)) { throw new Exception('setImageColorForeground: invalid parameters'); } // store given value $this->_imageColorForeground = $color_fore; } /** * Generate new challenge equation * Called implicitly in constructor * * @param void * @return void */ public function newChallenge() { // allowed operations static $operations = array( '+', '-', '*' ); // decide which operation $operation = $operations[rand(0, count($operations) - 1)]; // get some operands if ($operation == '*') { $operand1 = rand(3, 10); } else { $operand1 = rand(3, 99); } $operand2 = rand(1, $operand1 - 1); // glue the equation $equation = "$operand1 $operation $operand2"; eval('$result = ' . $equation . ';'); // use well-known sign for multiplication $equation = str_replace('*', html_entity_decode('&times;'), $equation); // add equal sign to displayed challenge $equation .= ' ='; // store all of these generated data $this->_equation = $equation; $this->_result = $result; } /** * Validate the entered result * * @param int $result The result entered by the user * * @return boolean Whether the result is correct */ public function isCorrectResult($result) { return intval($result) == $this->_result; } /** * Get the challenge image for output or conversion to text * * @param void * * @return binary $image_data The raw JPEG data */ public function getImage() { // prepare canvas and colors $canvas = $this->_prepareCanvas(); // draw the equation $this->_drawEquation($canvas); // get the drawn image data ob_start(); imagejpeg($canvas, null, 70); $image_data = ob_get_contents(); ob_end_clean(); return $image_data; } /** * Output the challenge image to the browser * * @param void * * @return void */ public function outputImage() { // get the challenge image $image_data = $this->getImage(); // did somebody already send anything to the browser? if (headers_sent()) { throw new Exception('outputImage: Call before sending data to browser'); } // send content type for the challenge image header('Content-Type: image/jpeg'); // send image data to browser echo $image_data; // the calling script should avoid sending anything additional } /** * Check if all required PHP extensions are loaded * * @param void * * @return void */ protected function _checkExtensions() { if (! extension_loaded('gd')) { throw new Exception('_checkExtensions: GD missing'); } // check for freetype $gd_info = gd_info(); if ($gd_info['FreeType Support'] !== true) { throw new Exception('_checkExtensions: GD FreeType support missing'); } } /** * Validate a given hex color * * @param string $color_hex The hex color to validate * * @return (string|FALSE) The validated color */ protected function _validateColorHex($color) { if (! preg_match('/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i', $color)) { return false; } if (substr($color, 0, 1) === '#') { $color = substr($color, 1); } // convert to uppercase $color = strtoupper($color); // if 3-digit format, expand if (strlen($color) == 3) { $color = str_repeat(substr($color, 0, 1), 2) . str_repeat(substr($color, 1, 1), 2) . str_repeat(substr($color, 2, 1), 2); } return $color; } /** * Convert HEX color to R, G, B * * @param string $color_hex The hex color * * @return array('r' => int, 'g' => int, 'b' => int) extracted color values */ protected function _colorFromHex($color_hex) { $red = hexdec(substr($color_hex, 0, 2)); $green = hexdec(substr($color_hex, 2, 2)); $blue = hexdec(substr($color_hex, 4, 2)); return array( 'r' => $red, 'g' => $green, 'b' => $blue ); } /** * Prepare the canvas, draw its background * * @param void * * @return resource $canvas The prepared canvas */ protected function _prepareCanvas() { $canvas = imagecreatetruecolor( $this->_imageWidth, $this->_imageHeight ); // extract HEX color $background_rgb = $this->_colorFromHex($this->_imageColorBackground); extract($background_rgb, EXTR_PREFIX_ALL, 'back'); // assign background color $background = imagecolorallocate($canvas, $back_r, $back_g, $back_b); imagefill($canvas, 0, 0, $background); return $canvas; } /** * Draw the equation into the canvas * * @param resource $canvas The canvas to draw onto * * @return void */ protected function _drawEquation(&$canvas) { // extract HEX color $foreground_rgb = $this->_colorFromHex($this->_imageColorForeground); extract($foreground_rgb, EXTR_PREFIX_ALL, 'fore'); // assign foreground color $foreground = imagecolorallocate($canvas, $fore_r, $fore_g, $fore_b); // starting size $font_size = 32; $fits_into_canvas = false; $canvas_width = intval(.7 * $this->_imageWidth); $canvas_height = intval(.5 * $this->_imageHeight); while (! $fits_into_canvas) { // find out equation dimensions $dimensions = imagettfbbox($font_size, 0, $this->_imageFont, $this->_equation); $equation_width = $dimensions[2] - $dimensions[0]; $equation_height = $dimensions[3] - $dimensions[5]; if ($equation_width > $canvas_width) { $font_size--; } elseif($equation_height > $canvas_height) { $font_size--; } else { $fits_into_canvas = true; } } // get margins $margin_left = rand(2, $this->_imageWidth - $equation_width - 2); $margin_top = rand(2, $this->_imageHeight - $equation_height - 2); // draw equation imagettftext( $canvas, $font_size, 0, $margin_left, $margin_top + $equation_height, $foreground, $this->_imageFont, $this->_equation ); } } ?>
jublonet/catcha
catcha.php
PHP
gpl-3.0
11,644
package com.link184.respiration; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Map; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; /** * Created by eugeniu on 3/22/18. */ public class LocalRepositoryClassGenerator { JavaFile generateRepositories(Map<Element, String> repositoriesWithPackages) { for (Map.Entry<Element, String> entry : repositoriesWithPackages.entrySet()) { if (entry.getKey().getAnnotation(LocalRepository.class) != null) { return generateRepository(entry.getKey(), entry.getValue()); } } return null; } private JavaFile generateRepository(Element element, String packageName) { Name simpleName = element.getSimpleName(); String capitalizedRepoName = simpleName.toString().substring(0, 1).toUpperCase() + simpleName.toString().substring(1); LocalRepository annotation = element.getAnnotation(LocalRepository.class); TypeName modelType = GenerationUtils.extractTypeName(annotation); ParameterizedTypeName superClass = ParameterizedTypeName.get(ClassName.bestGuess(element.asType().toString()), modelType); TypeSpec.Builder repositoryClass = TypeSpec.classBuilder(capitalizedRepoName) .addModifiers(Modifier.PUBLIC) .addAnnotation(generateRepositoryAnnotation(element)) .superclass(superClass) .addMethod(generateRepositoryConstructor(element)); return JavaFile.builder(packageName, repositoryClass.build()) .build(); } private AnnotationSpec generateRepositoryAnnotation(Element element) { LocalRepository annotation = element.getAnnotation(LocalRepository.class); AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(annotation.annotationType()); annotationBuilder .addMember("dataSnapshotType", "$T.class", GenerationUtils.extractTypeName(annotation)) .addMember("dataBaseAssetPath", "$S", annotation.dataBaseAssetPath()); if (annotation.children().length > 0 && !annotation.children()[0].isEmpty()) { annotationBuilder.addMember("children", "$L", GenerationUtils.generateChildrenArrayForAnnotations(annotation)); } if (!annotation.dataBaseName().isEmpty()) { annotationBuilder.addMember("dataBaseName", "$S", annotation.dataBaseName()); } return annotationBuilder.build(); } private MethodSpec generateRepositoryConstructor(Element element) { final ClassName configurationClass = ClassName.get("com.link184.respiration.repository.local", "LocalConfiguration"); final String configurationParameterName = "configuration"; TypeName modelType = GenerationUtils.extractTypeName(element.getAnnotation(LocalRepository.class)); ParameterizedTypeName parametrizedConfigurationClass = ParameterizedTypeName.get(configurationClass, modelType); return MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(parametrizedConfigurationClass, configurationParameterName) .addStatement("super($N)", configurationParameterName) .build(); } }
Link184/Respiration
respiration-compiler/src/main/java/com/link184/respiration/LocalRepositoryClassGenerator.java
Java
gpl-3.0
3,600
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="sl_SI"> <context> <name>AboutPage</name> <message> <source>Sources</source> <translation>Viri</translation> </message> <message> <source>If you want to create a theme compatible with UI Themer, please read the documentation.</source> <translation>Če želite ustvariti temo, združljivo z aplikacijo UI Themer, prosimo, preberite dokumentacijo</translation> </message> <message> <source>Documentation</source> <translation>Dokumentacija</translation> </message> <message> <source>Feedback</source> <translation>Povratne informacije</translation> </message> <message> <source>If you want to provide feedback or report an issue, please use GitHub.</source> <translation>Za povratne informacije in prijavo napak uporabite GitHub.</translation> </message> <message> <source>Issues</source> <translation>Napake in problemi</translation> </message> <message> <source>Support</source> <translation>Podpora</translation> </message> <message> <source>If you like my work and want to buy me a beer, feel free to do it!</source> <translation>Če podpirate moje delo in mi želite plačati pivo, nikar ne odlašajte!</translation> </message> <message> <source>Donate</source> <translation>Doniraj</translation> </message> <message> <source>Credits</source> <translation>Zasluge</translation> </message> <message> <source>Translations</source> <translation>Prevodi</translation> </message> <message> <source>Released under the &lt;a href=&apos;https://www.gnu.org/licenses/gpl-3.0&apos;&gt;GNU GPLv3&lt;/a&gt; license.</source> <translation>Izdano skladno z licenco &lt;a href=&apos;https://www.gnu.org/licenses/gpl-3.0&apos;&gt;GNU GPLv3&lt;/a&gt;.</translation> </message> <message> <source>Part of this app is based on &lt;a href=&apos;https://github.com/RikudouSage/sailfish-iconpacksupport-gui&apos;&gt;Icon pack support GUI&lt;/a&gt; by RikudouSennin.</source> <translation>Del aplikacije ima za osnovo &lt;a href=&apos;https://github.com/RikudouSage/sailfish-iconpacksupport-gui&apos;&gt;Icon pack support GUI&lt;/a&gt;, avtor RikudouSennin.</translation> </message> <message> <source>App icon by</source> <translation>Avtor ikone programa je</translation> </message> <message> <source>Thanks to Dax89 for helping with C++ and QML code, this app would not exist without him.</source> <translation>Hvala Dax89 za pomoč s C++ in QML kodo, aplikacija brez njega ne bi obstajala.</translation> </message> <message> <source>Thanks to Eugenio_g7 for helping with the &lt;i&gt;One-click restore&lt;/i&gt; service.</source> <translation>Hvala Eugenio_g7 z pomoč pri servisu &lt;i&gt;Obnovitev z enim klikom&lt;/i&gt;.</translation> </message> <message> <source>Thanks to all the testers for being brave and patient.</source> <translation>Hvala vsem preskuševalcem za pogum in potrpežljivost</translation> </message> <message> <source>Keyboard navigation based on &lt;a href=&apos;https://github.com/Wunderfitz/harbour-piepmatz&apos;&gt;Piepmatz&lt;/a&gt; by Sebastian Wolf.</source> <translation>Upravljanje s tipkovnico je povzeto po programu &lt;a href=&apos;https://github.com/Wunderfitz/harbour-piepmatz&apos;&gt;Piepmatz&lt;/a&gt;, avtor Sebastian Wolf.</translation> </message> <message> <source>About UI Themer</source> <translation>O programu UI Themer</translation> </message> <message> <source>UI Themer lets you customize icons, fonts, sounds and pixel density in Sailfish OS.</source> <translation>UI Themer vam omogoča prilagoditi ikone, pisave in gostoto pikslov sistema SailfishOS.</translation> </message> <message> <source>Thanks to LQS for helping with the Android DPI on the Xperia XA2.</source> <translation>Hvala LQS za pomoč pri Android DPI na napravah Xperia XA2.</translation> </message> <message> <source>Iconography by</source> <translation>Ikone je ustvaril</translation> </message> </context> <context> <name>ConfirmPage</name> <message> <source>Cancel</source> <translation>Prekliči</translation> </message> <message> <source>Apply icons</source> <translation>Uveljavi ikone</translation> </message> <message> <source>Apply icon overlay</source> <translation>Uveljavi prekrivanje ikon</translation> </message> <message> <source>Apply fonts</source> <translation>Uveljavi pisave</translation> </message> <message> <source>Font weight</source> <translation>Debelina pisave</translation> </message> <message> <source>Remember to restart the homescreen right after.</source> <translation>Po zaključku sprememb ne pozabite na ponovi zagon domačega zaslona.</translation> </message> <message> <source>Restart homescreen</source> <translation>Ponovni zagon domačega zaslona</translation> </message> <message> <source>Icons</source> <translation>Ikone</translation> </message> <message> <source>Fonts</source> <translation>Pisave</translation> </message> <message> <source>Apply</source> <translation>Uveljavi</translation> </message> <message> <source>Choose a font weight to preview</source> <translation>Izberite debelino pisave za predogled</translation> </message> <message> <source>Choose the main font weight for the UI.</source> <translation>Izberite debelino pisave uporabniškega vmesnika.</translation> </message> <message> <source>After confirming, your device will restart. Your currently opened apps will be closed.</source> <translation>Po potrditvi se bo vaša naprava samodejno ponovno zagnala. Vse vaše trenutno zagnane aplikacije se bodo zaprle.</translation> </message> <message> <source>Sounds</source> <translation>Zvoki</translation> </message> <message> <source>Apply sounds</source> <translation>Uveljavi zvoke</translation> </message> <message> <source>For sounds, a full restart may be needed to apply your settings.</source> <translation>Za uveljavitev sprememb zvokov potrebno ponoveno zagnati napravo.</translation> </message> <message> <source>The theme supports overlays.</source> <translation>Tema podpira prekrivanje.</translation> </message> </context> <context> <name>DensityPage</name> <message> <source>Usage guide</source> <translation>Priročnik za uporabo</translation> </message> <message> <source>Options</source> <translation>Možnosti</translation> </message> <message> <source>Restore display density</source> <translation>Obnovi gostoto zaslona</translation> </message> <message> <source>Display density</source> <translation>Gostota zaslona</translation> </message> <message> <source>Enable display density settings</source> <translation>Omogoči nastavitve gostote zaslone</translation> </message> <message> <source>Device pixel ratio</source> <translation>Razmerje pikslov naprave</translation> </message> <message> <source>Change the display pixel ratio. To a smaller value corresponds an higher density.</source> <translation>Spremeni razmerje pisklov zaslona. Manjša vrednost ustreza večji gostoti.</translation> </message> <message> <source>Android DPI</source> <translation>Android DPI</translation> </message> <message> <source>Android DPI value</source> <translation>Vrednost Android DPI</translation> </message> <message> <source>Change the Android DPI value. To a smaller value corresponds an higher density.</source> <translation>Spremeni vrednost Android DPI. Manjša vrednost ustreza večji gostoti.</translation> </message> <message> <source>Icon size</source> <translation>Velikost ikone</translation> </message> <message> <source>Change the size of UI icons. To a greater value corresponds an huger size.</source> <translation>Spremeni velikost ikon vmesnika. Večja vrednost ustreza večjim ikonam.</translation> </message> <message> <source>Remember to restart the homescreen (from the &lt;i&gt;Options&lt;/i&gt; page) right after you have changed the settings in this page.</source> <translation>Ne pozabite na ponovni zagon domačega zaslona (iz menija &lt;i&gt;Možnosti&lt;/i&gt;) takoj, ko spremenite nastavitve na tej strani.</translation> </message> <message> <source>If you have an Xperia XA2 series device, a full restart may be needed to apply your Android settings.</source> <translation>Če uporabljate Sony Xperia XA2 je po spremembah nastavitev za Android potreben ponoveni zagon.</translation> </message> </context> <context> <name>GuidePage</name> <message> <source>Usage guide</source> <translation>Priročnik za uporabo</translation> </message> <message> <source>UI Themer lets you customize icons, fonts and pixel density in Sailfish OS.</source> <translation>UI Themer vam omogoča prilagoditi ikone, pisave in gostoto pikslov sistema SailfishOS.</translation> </message> <message> <source>Themes</source> <translation>Teme</translation> </message> <message> <source>The &lt;i&gt;Themes&lt;/i&gt; page lets you customize icons and fonts via thirdy party themes. The page lists the themes you have currently installed (e.g. from OpenRepos). To apply them, tap on a theme of your choice and then select what you want to use from that theme - if the theme contains different font weights, you can choose the default one to use for the UI. You can also combine different themes, so for example you can use icons from a theme and fonts from another. To revert to the default settings, you can use the restore option from the pulley menu.</source> <translation>Na strani &lt;i&gt;Teme&lt;/i&gt; lahko s pomočjo dodatnih tem prilagodite ikone in pisave. Prikazane so trenutno nameščene teme, pridobljene (na primer) iz skladišča OpenRepos. Izberite temo in s klikom na njo se prikažejo možnosti - če tema vsebuje različne debeline pisav lahko izberete, katera naj bo privzeta za uporabniški vmesnik. Prav tako lahko kombinirate različne teme, na primer ikone iz ene in pisave iz druge. Za povrnitev na privzete nastavitve lahko uporabite možnost obnovitve iz poteznega menija.</translation> </message> <message> <source>Display density</source> <translation>Gostota zaslona</translation> </message> <message> <source>By increasing the display density, you can display more content on your screen - or less, if you prefer to have bigger UI elements. Android apps use a different setting than Sailfish OS ones. To revert to the default settings, you can use the restore options from the pulley menu.</source> <translation>S povečevanjem gostote zaslona lahko prikažete več vsebine, če želite imeti večje elemente vmesnika, pa vrednost povečajte. Android aplikacije uporabljajo drugačne nastavitve kot Sailfish. Za povrnitev na privzete nastavitve uporabite opcijo za obnovitev iz poteznega menija.</translation> </message> <message> <source>Icon updater</source> <translation>Posodobilnik ikon</translation> </message> <message> <source>Further help</source> <translation>Nadaljnja pomoč</translation> </message> <message> <source>One-click restore</source> <translation>Obnovitev z enim klikom</translation> </message> <message> <source>Recovery</source> <translation>Obnovitev</translation> </message> <message> <source>CLI tool</source> <translation>CLI orodje</translation> </message> <message> <source>If anything goes wrong or you want to manage all the options via terminal, you can recall the CLI tool by typing &lt;b&gt;themepacksupport&lt;/b&gt; as root.</source> <translation>V primeru težav ali če želite upravljati aplikacijo preko terminala, zaženite terminal kot root in vtipkajte &lt;b&gt;themepacksupport&lt;/b&gt;.</translation> </message> <message> <source>Remember to unapply themes and display density customizations before updating your system. In case you forgot, you may need to use the options provided in the &lt;i&gt;Recovery&lt;/i&gt; page or uninstall and reinstall Theme pack support e UI Themer.</source> <translation>Pred vsako nadgradnjo sistema ne pozabite odstraniti tem po meri in prilagoditve gostote zaslona. V primeru, da tega ne storite bo po nadgradnji potrebno uporabiti možnosti na strani &lt;i&gt;Obnovitev&lt;/i&gt; ter odstraniti in ponovno namestiti Theme pack support ter aplikacijo UI Themer.</translation> </message> <message> <source>UI Themer customizations must be reverted before performing a system update. With &lt;i&gt;One-click restore&lt;/i&gt; you can automate this process and restore icons, fonts and display density settings with just one click.</source> <translation>Pred vsako nadgradnjo sistema je potrebno vse prilagoditve aplikacije UI Themer povrniti na privzete nastavitve. Z možnostjo &lt;i&gt;Obnovitev z enim klikom&lt;/i&gt; lahko ta proces poenostavite in obnovite nastavitve po meri za ikone, pisave ter gostoto zaslona le z enim klikom.</translation> </message> <message> <source>Keyboard shortcuts</source> <translation>Bližnjice na fizični tipkovnici</translation> </message> <message> <source>Press &lt;b&gt;A&lt;/b&gt; for the about page.</source> <translation>Pritisnite &lt;b&gt;A&lt;/b&gt; za informacije o programu.</translation> </message> <message> <source>You can quickly restart the homescreen after you applied a setting by pressing &lt;b&gt;R&lt;/b&gt;.</source> <translation>S pritiskom na tipko &lt;b&gt;R&lt;/b&gt; lahko ponovno zaženete domači zaslon in uveljavite spremembe.</translation> </message> <message> <source>You can cancel a countdown or a dialog by pressing &lt;b&gt;C&lt;/b&gt;.</source> <translation>Odštevanje lahko prekličete s prtiskom na tipko &lt;b&gt;C&lt;/b&gt; ali preko dialoga.</translation> </message> <message> <source>Everytime an app is updated, you need to re-apply the theme in order to get the custom icon back. &lt;i&gt;Icon updater&lt;/i&gt; will automate this process, enabling automatic update of icons at a given time. You can choose between a pre-defined set of hours or a custom hour of the day.</source> <translation>Po vsaki posodobitvi aplikacije je potrebno znova naložiti temo, da se uveljavijo ikone po meri. &lt;i&gt;Posodobilnik ikon&lt;/i&gt; lahko to delo opravi samodejno in posodobi ikone ob izbranem času. Izberete lahko med vnaprej dočenimi urami ali pa nastavite čas po meri.</translation> </message> <message> <source>Press &lt;b&gt;G&lt;/b&gt; for the usage guide.</source> <translation>Za uporabniški priročnik pritisnite &lt;b&gt;G&lt;/b&gt;.</translation> </message> <message> <source>Press &lt;b&gt;W&lt;/b&gt; for restart the first run wizard.</source> <translation>Čarovnika za prvi zagon ponovno zaženete s prisitkom na tipko &lt;b&gt;W&lt;/b&gt;.</translation> </message> <message> <source>An homescreen restart may be needed to apply your settings. You can do that through the dialog or from the &lt;i&gt;Options&lt;/i&gt; page.</source> <translation>Za uveljavitev nedavnih sprememb ponovno zaženite domači zaslon kar lahko storite preko poteznega menija ali na strani &lt;i&gt;Možnosti&lt;/i&gt;.</translation> </message> <message> <source>An homescreen restart may be needed to apply your settings. You can do that from the &lt;i&gt;Options&lt;/i&gt; page.</source> <translation>Za uveljavitev nedavnih sprememb ponovno zaženite domači zaslon kar lahko storite na strani &lt;i&gt;Možnosti&lt;/i&gt;.</translation> </message> <message> <source>Press &lt;b&gt;O&lt;/b&gt; for the options page.</source> <translation>Za prikaz možnosti pritisnite &lt;b&gt;O&lt;/b&gt;.</translation> </message> <message> <source>UI Themer can be navigated via a physical keyboard, using convenient shortcuts.</source> <translation>UI Themer se lahko uporablja s fizično tipkovnico in priročnimi bližnjicami.</translation> </message> <message> <source>Press &lt;b&gt;B&lt;/b&gt; to go back to the previous page.</source> <translation>Za vrnitev na prejšnjo stran pritisnite &lt;b&gt;B&lt;/b&gt;.</translation> </message> <message> <source>If you have Storeman installed, you can quickly look for compatible themes by using the &lt;i&gt;Download&lt;/i&gt; icon in the main page.</source> <translation>Če imate nameščeno aplikacijo Storeman, lahko hitro poiščete združljive teme k klikom na ikono &lt;i&gt;Prenesi&lt;/i&gt; na glavni strani.</translation> </message> <message> <source>Press &lt;b&gt;H&lt;/b&gt; for the home page.</source> <translation>Pritisnite &lt;b&gt;H&lt;/b&gt; za domači zaslon..</translation> </message> <message> <source>Press &lt;b&gt;D&lt;/b&gt; for the display density page.</source> <translation>Pritisnite &lt;b&gt;D&lt;/b&gt; za gostoto zaslona.</translation> </message> <message> <source>Backup &amp; restore icons</source> <translation>Varnostno kopiranje in obnovitev ikon</translation> </message> <message> <source>If you are working on a theme or you want to have the default icons in a safe place, you can backup them. A compressed archive will be created and saved into &lt;i&gt;/home/nemo/&lt;/i&gt;. You can also restore a previous backup.</source> <translation>Če ustvarjate novo temo ali pa le želite imeti shranjene privzete ikone na varnem mestu, ustvarite varnostno kopijo. Kompresirana datoteka se bo ustvarila v &lt;i&gt;/home/nemo/&lt;/i&gt;. Prav tako lahko obnovite datoteke iz obstoječe varnostne kopije.</translation> </message> <message> <source>If you have an Xperia XA2 series device, a full restart may be needed may be needed to apply your Android settings.</source> <translation>Če uporabljate Sony Xperia XA2 je po spremembah nastavitev za Android potreben ponoveni zagon.</translation> </message> <message> <source>Here you can find advanced settings for UI Themer, e.g. reinstall default icons, fonts or sounds if you forget to revert to default theme before a system update or if the applying fails.</source> <translation>Tu najdete napredne nastavitve aplikacije UI Themer kot na primer ponovna namestitev privzetih ikon ali pisav za primer, ko nič drugega ne deluje ali če pozabite povrniti privzete nastavitve pred nagradnjo sistema.</translation> </message> <message> <source>If you still can&apos;t get the help you need, you can open an issue on</source> <translation>Če vam vgrajena pomoč ne zadostuje, odprite razpravo na</translation> </message> </context> <context> <name>MainPage</name> <message> <source>Uninstalling %1</source> <translation>Odstranjevanje %1</translation> </message> <message> <source>No themes yet</source> <translation>Ni tem</translation> </message> <message> <source>Install a compatible theme first</source> <translation>Najprej namestite združljivo temo</translation> </message> <message> <source>Usage guide</source> <translation>Priročnik za uporabo</translation> </message> <message> <source>Options</source> <translation>Možnosti</translation> </message> <message> <source>Display density</source> <translation>Gostota zaslona</translation> </message> <message> <source>Restore theme</source> <translation>Obnovi temo</translation> </message> <message> <source>Themes</source> <translation>Teme</translation> </message> </context> <context> <name>Notification</name> <message> <source>Settings applied.</source> <translation>Nastavitve so uveljavljene</translation> </message> </context> <context> <name>OptionsPage</name> <message> <source>Restart first run wizard</source> <translation>Ponovno zaženi čarovnika za prvi zagon</translation> </message> <message> <source>Usage guide</source> <translation>Priročnik za uporabo</translation> </message> <message> <source>Recovery</source> <translation>Obnovitev</translation> </message> <message> <source>Icon updater</source> <translation>Posodobilnik ikon</translation> </message> <message> <source>Everytime an app is updated, you need to re-apply the theme in order to get the custom icon back. &lt;i&gt;Icon updater&lt;/i&gt; will automate this process, enabling automatic update of icons at a given time.</source> <translation>Po vsaki posodobitvi aplikacije je potrebno znova naložiti temo, da se uveljavijo ikone po meri. &lt;i&gt;Posodobilnik ikon&lt;/i&gt; lahko to delo opravi samodejno in posodobi ikone ob izbranem času.</translation> </message> <message> <source>Update icons</source> <translation>Posodobi ikone</translation> </message> <message> <source>Disabled</source> <translation>Onemogočeno</translation> </message> <message> <source>30 minutes</source> <translation>30 minut</translation> </message> <message> <source>1 hour</source> <translation>1 ura</translation> </message> <message> <source>2 hours</source> <translation>2 uri</translation> </message> <message> <source>3 hours</source> <translation>3 ure</translation> </message> <message> <source>6 hours</source> <translation>6 ur</translation> </message> <message> <source>12 hours</source> <translation>12 ur</translation> </message> <message> <source>Daily</source> <translation>Dnevno</translation> </message> <message> <source>One-click restore</source> <translation>Obnovitev z enim klikom</translation> </message> <message> <source>UI Themer customizations must be reverted before performing a system update. With &lt;i&gt;One-click restore&lt;/i&gt; you can automate this process and restore icons, fonts and display density settings with just one click.</source> <translation>Pred vsako nadgradnjo sistema je potrebno vse prilagoditve aplikacije UI Themer povrniti na privzete nastavitve. Z možnostjo &lt;i&gt;Obnovitev z enim klikom&lt;/i&gt; lahko ta proces poenostavite in obnovite nastavitve po meri za ikone, pisave ter gostoto zaslona z le enim klikom.</translation> </message> <message> <source>Restore</source> <translation>Obnovi</translation> </message> <message> <source>Options</source> <translation>Možnosti</translation> </message> <message> <source>Cover</source> <translation>Naslovnica</translation> </message> <message> <source>Cover action</source> <translation>Primarno dejanje naslovnice</translation> </message> <message> <source>refresh current theme</source> <translation>osveži trenutno temo</translation> </message> <message> <source>restart homescreen</source> <translation>ponovni zagon domačega zaslona</translation> </message> <message> <source>one-click restore</source> <translation>obnovitev z enim klikom</translation> </message> <message> <source>none</source> <translation>nič</translation> </message> <message> <source>Second cover action</source> <translation>Sekundarno dejanje naslovnice</translation> </message> <message> <source>Restart homescreen</source> <translation>Ponovno zaženi domači zaslon</translation> </message> <message> <source>Restart</source> <translation>Ponovni zagon</translation> </message> <message> <source>Restarting homescreen</source> <translation>Ponovni zagon domačega zaslona</translation> </message> <message> <source>Restart the homescreen, to make your modifications effective. Your currently opened apps will be closed.</source> <translation>Za uveljavitev nedavnih sprememb ponovno zaženite domači zaslon. Vse vaše trenutno zagnane aplikacije se bodo zaprle.</translation> </message> <message> <source>Restoring</source> <translation>Obnavljanje</translation> </message> <message> <source>Choose the action to be shown on the UI Themer cover, for a quick access when the app is minimized on the homescreen.</source> <translation>Ko je aplikacija pomanjšana na domačem zaslonu, lahko na naslovnici določite dejanje</translation> </message> <message> <source>Optionally, you can choose to display a second action on the cover.</source> <translation>Če želite, lahko določite prikaz dodatnega dejanja na naslovnici.</translation> </message> <message> <source>Run before system updates</source> <translation>Zaženi pred posodobitvami sistema</translation> </message> <message> <source>Restore the default icons, fonts and display density settings before performing a system update, so you don&apos;t need to manually do it.</source> <translation>Vklop možnosti poskrbi za samodejno obnovitev privzetih ikon, pisav in vrednost gostote zaslona pred vsako nadgradnjo sistema.</translation> </message> <message> <source>Show active theme</source> <translation>Prikaži aktivno temo</translation> </message> <message> <source>Show the current theme on the cover.</source> <translation>Prikaži trenutno temo na naslovnici</translation> </message> <message> <source>UI mode</source> <translation>Način delovanja programa</translation> </message> <message> <source>easy</source> <translation>preprost</translation> </message> <message> <source>full</source> <translation>napreden</translation> </message> <message> <source>Backup icons</source> <translation>Ustvari varnostno kopijo ikon</translation> </message> <message> <source>Backup</source> <translation>Varnostna kopija</translation> </message> <message> <source>Backuping</source> <translation>Ustvarjanje varnostne kopije</translation> </message> <message> <source>Restore icons</source> <translation>Obnovi ikone</translation> </message> <message> <source>File</source> <translation>Datoteka</translation> </message> <message> <source>Select backup</source> <translation>Izberi varnostno kopijo</translation> </message> <message> <source>Restoring backup</source> <translation>Obnavljanje varnostne kopije</translation> </message> <message> <source>From here you can backup all the default icons into a compressed archive. The archive will be saved into &lt;i&gt;/home/nemo/&lt;/i&gt;.</source> <translation>Tu lahko ustvarite varnostno kopijo vseh privzetih ikon, ki se shranijo v arhivsko datoteko. Arhiv bo shranjen v &lt;i&gt;/home/nemo/&lt;/i&gt;.</translation> </message> <message> <source>Select and restore an archive previously saved via UI Themer. You will still need to perform a &lt;i&gt;Restore theme&lt;/i&gt; from the &lt;i&gt;Themes&lt;/i&gt; page in order to restore the icons in your system.</source> <translation>Izberite in obnovite datoteke iz arhiva, katerega je predhodno ustvarila aplikacija UI Themer. Še vedno bo potrebno uporabiti ukaz &lt;i&gt;Obnovi temo&lt;/i&gt; na strani &lt;i&gt;Teme&lt;/i&gt;, da se obnovijo ikone.</translation> </message> <message> <source>About UI Themer</source> <translation>O programu UI Themer</translation> </message> <message> <source>See less options and have an hassle-free experience.</source> <translation>Prikaži manj možnosti</translation> </message> <message> <source>Get full control of the app settings.</source> <translation>Pridobite popolen nadzor v nastavitvah</translation> </message> <message> <source>Enable advanced users and theme developers-tailored options.</source> <translation>Naprednim uporabnikom in razvijalcem omogoči dodatne možnosti programa</translation> </message> <message> <source>advanced</source> <translation>napredno</translation> </message> <message> <source>None</source> <translation>Nič</translation> </message> <message> <source>Here you can find advanced settings for UI Themer, e.g. reinstall default icons, fonts or sounds if you forget to revert to default theme before a system update or if the applying fails.</source> <translation>Tu najdete napredne nastavitve aplikacije UI Themer kot na primer ponovna namestitev privzetih ikon ali pisav za primer, ko nič drugega ne deluje ali če pozabite povrniti privzete nastavitve pred nagradnjo sistema.</translation> </message> </context> <context> <name>RecoveryPage</name> <message> <source>Continue</source> <translation>Nadaljuj</translation> </message> <message> <source>Cancel</source> <translation>Prekliči</translation> </message> <message> <source>Recovery</source> <translation>Obnovitev</translation> </message> <message> <source>Reinstall icons</source> <translation>Ponovna namestitev ikon</translation> </message> <message> <source>If any error occurs during themes applying/restoring, you can end up with messed up icons. From here, you can reinstall default Jolla app icons while, for thirdy party apps, you may need to reinstall/update apps to restore the default look.</source> <translation>Če med uveljavljanjem ali obnavljanjem sprememb pride do težav z ikonami, lahko tu ponovno namestite privzete Jolla ikone. Pri težavah z aplikacijami drugih ponudnikov poskusite le-te ponovno namestiti oziroma nadgraditi.</translation> </message> <message> <source>Reinstall fonts</source> <translation>Ponovno namesti pisave</translation> </message> <message> <source>Reinstall sounds</source> <translation>Ponovno namesti zvoke</translation> </message> <message> <source>Reinstall default sounds, if sounds applying/restoring fails.</source> <translation>Če je uveljavitev ali obnovitev zvokov neuspešna, poskusite ponovno namestiti privzete zvoke.</translation> </message> <message> <source>Remember to restart the homescreen right after.</source> <translation>Ne pozabite na ponovi zagon domačega zaslona po zaključku sprememb.</translation> </message> <message> <source>Restart homescreen</source> <translation>Ponovni zagon domačega zaslona</translation> </message> <message> <source>Reinstall default fonts, if fonts applying/restoring fails.</source> <translation>Če je uveljavitev ali obnovitev pisav neuspešna, poskusite ponovno namestiti privzete pisave.</translation> </message> </context> <context> <name>RestoreDDPage</name> <message> <source>Restore</source> <translation>Obnovi</translation> </message> <message> <source>Cancel</source> <translation>Prekliči</translation> </message> <message> <source>Default device pixel ratio</source> <translation>Privzeto razmerje pikslov naprave</translation> </message> <message> <source>Default Android DPI</source> <translation>Privzeti Android DPI</translation> </message> <message> <source>Remember to restart the homescreen right after.</source> <translation>Ne pozabite na ponovi zagon domačega zaslona po zaključku sprememb.</translation> </message> <message> <source>Restart homescreen</source> <translation>Ponovni zagon domačega zaslona</translation> </message> <message> <source>After confirming, your device will restart. Your currently opened apps will be closed.</source> <translation>Po potrditvi se bo vaša naprava samodejno ponovno zagnala. Vse vaše trenutno zagnane aplikacije se bodo zaprle.</translation> </message> <message> <source>If you have an Xperia XA2 series device, a full restart may be needed to apply your Android settings.</source> <translation>Če uporabljate Sony Xperia XA2 je po spremembah nastavitev za Android potreben ponoveni zagon.</translation> </message> </context> <context> <name>RestorePage</name> <message> <source>Restore</source> <translation>Obnovi</translation> </message> <message> <source>Cancel</source> <translation>Prekliči</translation> </message> <message> <source>Restart homescreen</source> <translation>Ponovni zagon domačega zaslona</translation> </message> <message> <source>Remember to restart the homescreen right after.</source> <translation>Ne pozabite na ponovni zagon domačega zaslona.</translation> </message> <message> <source>Default icons</source> <translation>Privzete ikone</translation> </message> <message> <source>Default fonts</source> <translation>Privzete pisave</translation> </message> <message> <source>After confirming, your device will restart. Your currently opened apps will be closed.</source> <translation>Po potrditvi se bo vaša naprava samodejno ponovno zagnala. Vse vaše trenutno zagnane aplikacije se bodo zaprle.</translation> </message> <message> <source>Default sounds</source> <translation>Privzeti zvoki</translation> </message> <message> <source>For sounds, a full restart may be needed to apply your settings.</source> <translation>Za uveljavitev sprememb zvokov potrebno ponoveno zagnati napravo. </translation> </message> </context> <context> <name>ThemePackItem</name> <message> <source>Uninstall</source> <translation>Odstrani</translation> </message> <message> <source>icons</source> <translation>ikone</translation> </message> <message> <source>fonts</source> <translation>pisave</translation> </message> <message> <source>sounds</source> <translation>zvoki</translation> </message> </context> <context> <name>TranslatorPage</name> <message> <source>Translations</source> <translation>Prevodi</translation> </message> <message> <source>Request a new language or contribute to existing languages on the Transifex project page.</source> <translation>Predlagajte nov jezik ali prispevajte k prevodu obstoječega na portalu Transifex .</translation> </message> <message> <source>Transifex</source> <translation>Transifex</translation> </message> </context> <context> <name>WelcomePage</name> <message> <source>Welcome to UI Themer</source> <translation>Dobrodošli v aplikaciji UI Themer</translation> </message> <message> <source>Install dependencies</source> <translation>Namesti odvisnosti</translation> </message> <message> <source>I have already installed the dependencies</source> <translation>Vse odvisnosti že imam nameščene</translation> </message> <message> <source>Donate</source> <translation>Doniraj</translation> </message> <message> <source>I don&apos;t care donating</source> <translation>Doniranje me ne zanima</translation> </message> <message> <source>Start UI Themer</source> <translation>Zaženi UI Themer</translation> </message> <message> <source>UI Themer lets you customize icons, fonts and pixel density in Sailfish OS.</source> <translation>UI Themer vam omogoča prilagoditi ikone, pisave in gostoto pikslov sistema SailfishOS.</translation> </message> <message> <source>If you like my work and want to buy me a beer, feel free to do it!</source> <translation>Če podpirate moje delo in mi želite plačati pivo, nikar ne odlašajte!</translation> </message> <message> <source>Support</source> <translation>Podpora</translation> </message> <message> <source>UI Themer needs some additional dependencies in order to function properly. Install them now if you haven&apos;t already.</source> <translation>UI Themer potrebuje za pravilno delovanje nekaj dodatnih odvisnosti. Če jih še niste namestili storite to zdaj.</translation> </message> <message> <source>It may take a while, do not quit.</source> <translation>To lahko traja nekaj časa, ne zapuščajte programa.</translation> </message> <message> <source>Usage guide</source> <translation>Priročnik za uporabo</translation> </message> <message> <source>Dependencies</source> <translation>Odvisnosti</translation> </message> <message> <source>ImageMagick</source> <translation>ImageMagick</translation> </message> <message> <source>ImageMagick is required for UI Themer overlays to work. Overlays need to be supported by the theme.</source> <translation>UI Themer potrebuje za delovanje prekrivanja ikon nameščen program ImageMagick. Prav tako mora tema podpirati prekrivanje.</translation> </message> <message> <source>Install ImageMagick</source> <translation>Namesti ImageMagick</translation> </message> <message> <source>ImageMagick installed</source> <translation>ImageMagick je nameščen</translation> </message> <message> <source>Terms and conditions</source> <translation>Splošni pogoji uporabe</translation> </message> <message> <source>By using UI Themer, you agree to the &lt;a href=&apos;https://www.gnu.org/licenses/gpl-3.0&apos;&gt;GNU GPLv3&lt;/a&gt; terms and conditions.</source> <translation>Z uporabo programa UI Themer se strinjate s pogoji licence &lt;a href=&apos;https://www.gnu.org/licenses/gpl-3.0&apos;&gt;GNU GPLv3&lt;/a&gt;.</translation> </message> <message> <source>UI Themer DOES NOT send any data. Some essential info (e.g. the current theme) are collected and stored EXCLUSIVELY locally and used only for the proper functioning of the app (e.g. to display the current theme in the app).</source> <translation>UI Themer NE POŠILJA podatkov. Nekateri nujni podatki se zbirajo in so shranjeni IZKLJUČNO na napravi ter so namenjeni pravilnemu delovanju aplikacije (na primer podatki o trenutni temi za prikaz v aplikaciji).</translation> </message> </context> </TS>
fravaccaro/sailfishos-uithemer
translations/sailfishos-uithemer-sl_SI.ts
TypeScript
gpl-3.0
40,622
#!/usr/bin/python import sys sys.path.append('/var/www/html/valumodel.com/scripts/dcf') from calc_dcf import calc_dcf def create_dcf(req, tax_rate, growth_rate_1_year_out, sga_of_sales, da_of_sales, capex_of_sales, nwc_of_sales, levered_beta, current_yield, exit_multiple, ticker): assumptions = {} try: assumptions['Tax Rate'] = float(tax_rate)/100.0 assumptions['Growth Rate 1 year out'] = float(growth_rate_1_year_out)/100.0 assumptions['SGA % of sales'] = float(sga_of_sales)/100.0 assumptions['D&A % of sales'] = float(da_of_sales)/100.0 assumptions['CAPEX % of sales'] = float(capex_of_sales)/100.0 assumptions['NWC % of sales'] = float(nwc_of_sales)/100.0 assumptions['Levered Beta'] = float(levered_beta) assumptions['Current Yield'] = float(current_yield)/100.0 assumptions['Exit Multiple'] = float(exit_multiple) except ValueError: return '<!doctype html><html><body><h1>Invalid DCF Input. Please try again.</h1></body></html>' ticker = ticker.split(' ')[0] if not ticker.isalnum(): return '<!doctype html><html><body><h1>Invalid Ticker. Please try again.</h1></body></html>' return calc_dcf(assumptions, ticker.upper())
willmarkley/valumodel.com
scripts/dcf.py
Python
gpl-3.0
1,260
using System; using System.Collections; using Server.Network; using Server.Items; using Server.Targeting; using Server.Mobiles; using Server.Engines.BuffIcons; namespace Server.Spells.Necromancy { public class PainSpikeSpell : NecromancerSpell { private static SpellInfo m_Info = new SpellInfo( "Pain Spike", "In Sar", 203, 9031, Reagent.GraveDust, Reagent.PigIron ); public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 1.0 ); } } public override double RequiredSkill { get { return 20.0; } } public override int RequiredMana { get { return 5; } } public PainSpikeSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info ) { } public override void OnCast() { Caster.Target = new InternalTarget( this ); } public override bool DelayedDamage { get { return false; } } public void Target( Mobile m ) { if ( CheckHSequence( m ) ) { SpellHelper.Turn( Caster, m ); /* Temporarily causes intense physical pain to the target, dealing direct damage. * After 10 seconds the spell wears off, and if the target is still alive, some of the Hit Points lost through Pain Spike are restored. * Damage done is ((Spirit Speak skill level - target's Resist Magic skill level) / 100) + 30. * * NOTE : Above algorithm must either be typo or using fixed point : really is / 10 : * * 100ss-0mr = 40 * 100ss-50mr = 35 * 100ss-75mr = 32 * * NOTE : If target already has a pain spike in effect, damage dealt /= 10 */ m.FixedParticles( 0x37C4, 1, 8, 9916, 39, 3, EffectLayer.Head ); m.FixedParticles( 0x37C4, 1, 8, 9502, 39, 4, EffectLayer.Head ); m.PlaySound( 0x210 ); double damage = ( ( GetDamageSkill( Caster ) - GetResistSkill( m ) ) / 10 ) + ( m.IsPlayer ? 18 : 30 ); damage += damage * ( SpellHelper.GetSpellDamage( Caster, m.IsPlayer ) / 100.0 ); Utility.FixMin( ref damage, 1 ); TimeSpan buffTime = TimeSpan.FromSeconds( 10.0 ); if ( m_Table.Contains( m ) ) { damage = Utility.RandomMinMax( 3, 7 ); Timer t = m_Table[m] as Timer; if ( t != null ) { t.Delay += TimeSpan.FromSeconds( 2.0 ); buffTime = t.Next - DateTime.Now; } } else { new InternalTimer( m, damage ).Start(); } BuffInfo.AddBuff( m, new BuffInfo( BuffIcon.PainSpike, 1075667, buffTime, m, String.Format( "{0}", (int) damage ) ) ); Misc.WeightOverloading.DFA = Misc.DFAlgorithm.PainSpike; SpellHelper.DoLeech( (int) damage, Caster, m ); m.Damage( (int) damage, Caster ); Misc.WeightOverloading.DFA = Misc.DFAlgorithm.Standard; //SpellHelper.Damage( this, m, damage, 100, 0, 0, 0, 0, Misc.DFAlgorithm.PainSpike ); } FinishSequence(); } private static Hashtable m_Table = new Hashtable(); public static bool UnderEffect( Mobile m ) { return m_Table.ContainsKey( m ); } private class InternalTimer : Timer { private Mobile m_Mobile; private int m_ToRestore; public InternalTimer( Mobile m, double toRestore ) : base( TimeSpan.FromSeconds( 10.0 ) ) { m_Mobile = m; m_ToRestore = (int) toRestore; m_Table[m] = this; } protected override void OnTick() { m_Table.Remove( m_Mobile ); if ( m_Mobile.Alive && !m_Mobile.IsDeadBondedPet ) m_Mobile.Hits += m_ToRestore; BuffInfo.RemoveBuff( m_Mobile, BuffIcon.PainSpike ); } } private class InternalTarget : Target { private PainSpikeSpell m_Owner; public InternalTarget( PainSpikeSpell owner ) : base( 12, false, TargetFlags.Harmful ) { m_Owner = owner; } protected override void OnTarget( Mobile from, object o ) { if ( o is Mobile ) m_Owner.Target( (Mobile) o ); } protected override void OnTargetFinish( Mobile from ) { m_Owner.FinishSequence(); } } } }
greeduomacro/xrunuo
Scripts/Distro/Spells/Necromancy/PainSpike.cs
C#
gpl-3.0
4,046
package fr.guiguilechat.jcelechat.model.sde.attributes; import fr.guiguilechat.jcelechat.model.sde.IntAttribute; /** * */ public class MiningDurationRoleBonus extends IntAttribute { public static final MiningDurationRoleBonus INSTANCE = new MiningDurationRoleBonus(); @Override public int getId() { return 2458; } @Override public int getCatId() { return 7; } @Override public boolean getHighIsGood() { return false; } @Override public double getDefaultValue() { return 0.0; } @Override public boolean getPublished() { return true; } @Override public boolean getStackable() { return true; } @Override public String toString() { return "MiningDurationRoleBonus"; } }
guiguilechat/EveOnline
model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/attributes/MiningDurationRoleBonus.java
Java
gpl-3.0
830
'use strict'; angular.module('MainConsole') .factory('WebSocketService', ['$rootScope', '$q', '$filter', '$location', function ($rootScope, $q, $filter, $location) { var service = {}; service.wsConnect = function() { // Websocket is at wss://hostname:port/ws var host = $location.host(); var port = $location.port(); var wsUrl = $rootScope.urlscheme.websocket + '/ws'; var ws = new WebSocket(wsUrl); ws.onopen = function(){ $rootScope.connected = 1; console.log("Socket has been opened!"); }; ws.onerror = function(){ $rootScope.connected = 0; console.log("Socket received an error!"); }; ws.onclose = function(){ $rootScope.connected = 0; console.log("Socket has been closed!"); } ws.onmessage = function(message) { //listener(JSON.parse(message.data)); service.callback(JSON.parse(message.data)); }; service.ws = ws; console.log('WebSocket Initialized'); }; service.listener = function(callback) { service.callback = callback; }; service.send = function(message) { service.ws.send(message); }; service.close = function(){ service.ws.close(); $rootScope.connected = 0; console.log("Socket has been closed!"); }; return service; }]);
bammv/sguil
server/html/sguilclient/websocketService.js
JavaScript
gpl-3.0
1,652
/* OptionsMenuData.cpp Author : Cyrielle File under GNU GPL v3.0 license */ #include "OptionsMenuData.hpp" #include "ResourceLoader.hpp" namespace OpMon { namespace Model { OptionsMenuData::OptionsMenuData(UiData *data) : uidata(data) { ResourceLoader::load(background, "backgrounds/options.png"); ResourceLoader::load(selectBar, "sprites/misc/selectBar.png"); ResourceLoader::load(langBg, "backgrounds/lang.png"); ResourceLoader::load(yesTx, "sprites/misc/yes.png"); ResourceLoader::load(creditsBg, "backgrounds/credits.png"); ResourceLoader::load(controlsBg, "backgrounds/controls.png"); ResourceLoader::load(volumeCur, "sprites/misc/cursor.png"); ResourceLoader::load(keyChange, "sprites/misc/keyChange.png"); } } // namespace Model } // namespace OpMon
jlppc/OpMon
src/opmon/model/storage/OptionsMenuData.cpp
C++
gpl-3.0
894
import os import re import gettext import locale import threading # libsearchfilter_toggle starts thread libsearchfilter_loop import operator import gtk import gobject import pango import ui import misc import formatting import mpdhelper as mpdh from consts import consts import breadcrumbs def library_set_data(album=None, artist=None, genre=None, year=None, path=None): if album is not None: album = unicode(album) if artist is not None: artist = unicode(artist) if genre is not None: genre = unicode(genre) if year is not None: year = unicode(year) if path is not None: path = unicode(path) return (album, artist, genre, year, path) def library_get_data(data, *args): name_to_index = {'album': 0, 'artist': 1, 'genre': 2, 'year': 3, 'path': 4} # Data retrieved from the gtktreeview model is not in # unicode anymore, so convert it. retlist = [unicode(data[name_to_index[arg]]) if data[name_to_index[arg]] \ else None for arg in args] if len(retlist) == 1: return retlist[0] else: return retlist class Library(object): def __init__(self, config, mpd, artwork, TAB_LIBRARY, album_filename, settings_save, filtering_entry_make_red, filtering_entry_revert_color, filter_key_pressed, on_add_item, connected, on_library_button_press, new_tab, get_multicd_album_root_dir): self.artwork = artwork self.config = config self.mpd = mpd self.librarymenu = None # cyclic dependency, set later self.album_filename = album_filename self.settings_save = settings_save self.filtering_entry_make_red = filtering_entry_make_red self.filtering_entry_revert_color = filtering_entry_revert_color self.filter_key_pressed = filter_key_pressed self.on_add_item = on_add_item self.connected = connected self.on_library_button_press = on_library_button_press self.get_multicd_album_root_dir = get_multicd_album_root_dir self.NOTAG = _("Untagged") self.VAstr = _("Various Artists") self.search_terms = [_('Artist'), _('Title'), _('Album'), _('Genre'), _('Filename'), _('Everything')] self.search_terms_mpd = ['artist', 'title', 'album', 'genre', 'file', 'any'] self.libfilterbox_cmd_buf = None self.libfilterbox_cond = None self.libfilterbox_source = None self.prevlibtodo_base = None self.prevlibtodo_base_results = None self.prevlibtodo = None self.save_timeout = None self.libsearch_last_tooltip = None self.lib_view_filesystem_cache = None self.lib_view_artist_cache = None self.lib_view_genre_cache = None self.lib_view_album_cache = None self.lib_list_genres = None self.lib_list_artists = None self.lib_list_albums = None self.lib_list_years = None self.view_caches_reset() self.libraryvbox = gtk.VBox() self.library = ui.treeview() self.library_selection = self.library.get_selection() self.breadcrumbs = breadcrumbs.CrumbBox() self.breadcrumbs.props.spacing = 2 expanderwindow2 = ui.scrollwindow(add=self.library) self.searchbox = gtk.HBox() self.searchcombo = ui.combo(items=self.search_terms) self.searchcombo.set_tooltip_text(_("Search terms")) self.searchtext = ui.entry() self.searchtext.set_tooltip_text(_("Search library")) self.searchbutton = ui.button(img=ui.image(stock=gtk.STOCK_CANCEL), h=self.searchcombo.size_request()[1]) self.searchbutton.set_no_show_all(True) self.searchbutton.hide() self.searchbutton.set_tooltip_text(_("End Search")) self.libraryview = ui.button(relief=gtk.RELIEF_NONE) self.libraryview.set_tooltip_text(_("Library browsing view")) # disabled as breadcrumbs replace this: # self.searchbox.pack_start(self.libraryview, False, False, 1) # self.searchbox.pack_start(gtk.VSeparator(), False, False, 2) self.searchbox.pack_start(ui.label(_("Search:")), False, False, 3) self.searchbox.pack_start(self.searchtext, True, True, 2) self.searchbox.pack_start(self.searchcombo, False, False, 2) self.searchbox.pack_start(self.searchbutton, False, False, 2) self.libraryvbox.pack_start(self.breadcrumbs, False, False, 2) self.libraryvbox.pack_start(expanderwindow2, True, True) self.libraryvbox.pack_start(self.searchbox, False, False, 2) self.tab = new_tab(self.libraryvbox, gtk.STOCK_HARDDISK, TAB_LIBRARY, self.library) # Assign some pixbufs for use in self.library self.openpb2 = self.library.render_icon(gtk.STOCK_OPEN, gtk.ICON_SIZE_LARGE_TOOLBAR) self.harddiskpb2 = self.library.render_icon(gtk.STOCK_HARDDISK, gtk.ICON_SIZE_LARGE_TOOLBAR) self.openpb = self.library.render_icon(gtk.STOCK_OPEN, gtk.ICON_SIZE_MENU) self.harddiskpb = self.library.render_icon(gtk.STOCK_HARDDISK, gtk.ICON_SIZE_MENU) self.albumpb = gtk.gdk.pixbuf_new_from_file_at_size( album_filename, consts.LIB_COVER_SIZE, consts.LIB_COVER_SIZE) self.genrepb = self.library.render_icon('gtk-orientation-portrait', gtk.ICON_SIZE_LARGE_TOOLBAR) self.artistpb = self.library.render_icon('artist', gtk.ICON_SIZE_LARGE_TOOLBAR) self.sonatapb = self.library.render_icon('sonata', gtk.ICON_SIZE_MENU) # list of the library views: (id, name, icon name, label) self.VIEWS = [ (consts.VIEW_FILESYSTEM, 'filesystem', gtk.STOCK_HARDDISK, _("Filesystem")), (consts.VIEW_ALBUM, 'album', 'album', _("Albums")), (consts.VIEW_ARTIST, 'artist', 'artist', _("Artists")), (consts.VIEW_GENRE, 'genre', gtk.STOCK_ORIENTATION_PORTRAIT, _("Genres")), ] self.library_view_assign_image() self.library.connect('row_activated', self.on_library_row_activated) self.library.connect('button_press_event', self.on_library_button_press) self.library.connect('key-press-event', self.on_library_key_press) self.library.connect('query-tooltip', self.on_library_query_tooltip) expanderwindow2.connect('scroll-event', self.on_library_scrolled) self.libraryview.connect('clicked', self.library_view_popup) self.searchtext.connect('key-press-event', self.libsearchfilter_key_pressed) self.searchtext.connect('activate', self.libsearchfilter_on_enter) self.searchbutton.connect('clicked', self.on_search_end) self.libfilter_changed_handler = self.searchtext.connect( 'changed', self.libsearchfilter_feed_loop) searchcombo_changed_handler = self.searchcombo.connect( 'changed', self.on_library_search_combo_change) # Initialize library data and widget self.libraryposition = {} self.libraryselectedpath = {} self.searchcombo.handler_block(searchcombo_changed_handler) self.searchcombo.set_active(self.config.last_search_num) self.searchcombo.handler_unblock(searchcombo_changed_handler) self.librarydata = gtk.ListStore(gtk.gdk.Pixbuf, gobject.TYPE_PYOBJECT, str) self.library.set_model(self.librarydata) self.library.set_search_column(2) self.librarycell = gtk.CellRendererText() self.librarycell.set_property("ellipsize", pango.ELLIPSIZE_END) self.libraryimg = gtk.CellRendererPixbuf() self.librarycolumn = gtk.TreeViewColumn() self.librarycolumn.pack_start(self.libraryimg, False) self.librarycolumn.pack_start(self.librarycell, True) self.librarycolumn.set_attributes(self.libraryimg, pixbuf=0) self.librarycolumn.set_attributes(self.librarycell, markup=2) self.librarycolumn.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE) self.library.append_column(self.librarycolumn) self.library_selection.set_mode(gtk.SELECTION_MULTIPLE) def get_libraryactions(self): return [(name + 'view', icon, label, None, None, self.on_libraryview_chosen) for _view, name, icon, label in self.VIEWS] def get_model(self): return self.librarydata def get_widgets(self): return self.libraryvbox def get_treeview(self): return self.library def get_selection(self): return self.library_selection def set_librarymenu(self, librarymenu): self.librarymenu = librarymenu self.librarymenu.attach_to_widget(self.libraryview, None) def library_view_popup(self, button): self.librarymenu.popup(None, None, self.library_view_position_menu, 1, 0, button) def library_view_position_menu(self, _menu, button): x, y, _width, height = button.get_allocation() return (self.config.x + x, self.config.y + y + height, True) def on_libraryview_chosen(self, action): if self.search_visible(): self.on_search_end(None) if action.get_name() == 'filesystemview': self.config.lib_view = consts.VIEW_FILESYSTEM elif action.get_name() == 'artistview': self.config.lib_view = consts.VIEW_ARTIST elif action.get_name() == 'genreview': self.config.lib_view = consts.VIEW_GENRE elif action.get_name() == 'albumview': self.config.lib_view = consts.VIEW_ALBUM self.library.grab_focus() self.library_view_assign_image() self.libraryposition = {} self.libraryselectedpath = {} self.library_browse(self.library_set_data(path="/")) try: if len(self.librarydata) > 0: self.library_selection.unselect_range((0,), (len(self.librarydata)-1,)) except: pass gobject.idle_add(self.library.scroll_to_point, 0, 0) def library_view_assign_image(self): _view, _name, icon, label = [v for v in self.VIEWS if v[0] == self.config.lib_view][0] self.libraryview.set_image(ui.image(stock=icon)) self.libraryview.set_label(" " + label) def view_caches_reset(self): # We should call this on first load and whenever mpd is # updated. self.lib_view_filesystem_cache = None self.lib_view_artist_cache = None self.lib_view_genre_cache = None self.lib_view_album_cache = None self.lib_list_genres = None self.lib_list_artists = None self.lib_list_albums = None self.lib_list_years = None def on_library_scrolled(self, _widget, _event): try: # Use gobject.idle_add so that we can get the visible # state of the treeview gobject.idle_add(self._on_library_scrolled) except: pass def _on_library_scrolled(self): if not self.config.show_covers: return # This avoids a warning about a NULL node in get_visible_range if not self.library.props.visible: return vis_range = self.library.get_visible_range() if vis_range is None: return try: start_row = int(vis_range[0][0]) end_row = int(vis_range[1][0]) except IndexError: # get_visible_range failed return self.artwork.library_artwork_update(self.librarydata, start_row, end_row, self.albumpb) def library_browse(self, _widget=None, root=None): # Populates the library list with entries if not self.connected(): return if root is None or (self.config.lib_view == consts.VIEW_FILESYSTEM \ and self.library_get_data(root, 'path') is None): root = self.library_set_data(path="/") if self.config.wd is None or (self.config.lib_view == \ consts.VIEW_FILESYSTEM and \ self.library_get_data(self.config.wd, 'path') is None): self.config.wd = self.library_set_data(path="/") prev_selection = [] prev_selection_root = False prev_selection_parent = False if root == self.config.wd: # This will happen when the database is updated. So, lets save # the current selection in order to try to re-select it after # the update is over. model, selected = self.library_selection.get_selected_rows() for path in selected: if model.get_value(model.get_iter(path), 2) == "/": prev_selection_root = True elif model.get_value(model.get_iter(path), 2) == "..": prev_selection_parent = True else: prev_selection.append(model.get_value(model.get_iter(path), 1)) self.libraryposition[self.config.wd] = \ self.library.get_visible_rect()[1] path_updated = True else: path_updated = False new_level = self.library_get_data_level(root) curr_level = self.library_get_data_level(self.config.wd) # The logic below is more consistent with, e.g., thunar. if new_level > curr_level: # Save position and row for where we just were if we've # navigated into a sub-directory: self.libraryposition[self.config.wd] = \ self.library.get_visible_rect()[1] model, rows = self.library_selection.get_selected_rows() if len(rows) > 0: data = self.librarydata.get_value( self.librarydata.get_iter(rows[0]), 2) if not data in ("..", "/"): self.libraryselectedpath[self.config.wd] = rows[0] elif (self.config.lib_view == consts.VIEW_FILESYSTEM and \ root != self.config.wd) \ or (self.config.lib_view != consts.VIEW_FILESYSTEM and new_level != \ curr_level): # If we've navigated to a parent directory, don't save # anything so that the user will enter that subdirectory # again at the top position with nothing selected self.libraryposition[self.config.wd] = 0 self.libraryselectedpath[self.config.wd] = None # In case sonata is killed or crashes, we'll save the library state # in 5 seconds (first removing any current settings_save timeouts) if self.config.wd != root: try: gobject.source_remove(self.save_timeout) except: pass self.save_timeout = gobject.timeout_add(5000, self.settings_save) self.config.wd = root self.library.freeze_child_notify() self.librarydata.clear() # Populate treeview with data: bd = [] while len(bd) == 0: if self.config.lib_view == consts.VIEW_FILESYSTEM: bd = self.library_populate_filesystem_data( self.library_get_data(self.config.wd, 'path')) elif self.config.lib_view == consts.VIEW_ALBUM: album, artist, year = self.library_get_data(self.config.wd, 'album', 'artist', 'year') if album is not None: bd = self.library_populate_data(artist=artist, album=album, year=year) else: bd = self.library_populate_toplevel_data(albumview=True) elif self.config.lib_view == consts.VIEW_ARTIST: artist, album, year = self.library_get_data(self.config.wd, 'artist', 'album', 'year') if artist is not None and album is not None: bd = self.library_populate_data(artist=artist, album=album, year=year) elif artist is not None: bd = self.library_populate_data(artist=artist) else: bd = self.library_populate_toplevel_data(artistview=True) elif self.config.lib_view == consts.VIEW_GENRE: genre, artist, album, year = self.library_get_data( self.config.wd, 'genre', 'artist', 'album', 'year') if genre is not None and artist is not None and album is \ not None: bd = self.library_populate_data(genre=genre, artist=artist, album=album, year=year) elif genre is not None and artist is not None: bd = self.library_populate_data(genre=genre, artist=artist) elif genre is not None: bd = self.library_populate_data(genre=genre) else: bd = self.library_populate_toplevel_data(genreview=True) if len(bd) == 0: # Nothing found; go up a level until we reach the top level # or results are found last_wd = self.config.wd self.config.wd = self.library_get_parent() if self.config.wd == last_wd: break for _sort, path in bd: self.librarydata.append(path) self.library.thaw_child_notify() # Scroll back to set view for current dir: self.library.realize() gobject.idle_add(self.library_set_view, not path_updated) if len(prev_selection) > 0 or prev_selection_root or \ prev_selection_parent: # Retain pre-update selection: self.library_retain_selection(prev_selection, prev_selection_root, prev_selection_parent) # Update library artwork as necessary self.on_library_scrolled(None, None) self.update_breadcrumbs() def update_breadcrumbs(self): # remove previous buttons for b in self.breadcrumbs: self.breadcrumbs.remove(b) # add the views button first b = ui.button(text=_(" v "), can_focus=False, relief=gtk.RELIEF_NONE) b.connect('clicked', self.library_view_popup) self.breadcrumbs.pack_start(b, False, False) b.show() # add the ellipsis explicitly XXX make this unnecessary b = ui.label("...") self.breadcrumbs.pack_start(b, False, False) b.show() # find info for current view view, _name, icon, label = [v for v in self.VIEWS if v[0] == self.config.lib_view][0] # the first crumb is the root of the current view crumbs = [(label, icon, None, self.library_set_data(path='/'))] # rest of the crumbs are specific to the view if view == consts.VIEW_FILESYSTEM: path = self.library_get_data(self.config.wd, 'path') if path and path != '/': parts = path.split('/') else: parts = [] # no crumbs for / # append a crumb for each part for i, part in enumerate(parts): partpath = '/'.join(parts[:i + 1]) target = self.library_set_data(path=partpath) crumbs.append((part, gtk.STOCK_OPEN, None, target)) else: if view == consts.VIEW_ALBUM: # We don't want to show an artist button in album view keys = 'genre', 'album' nkeys = 2 else: keys = 'genre', 'artist', 'album' nkeys = 3 parts = self.library_get_data(self.config.wd, *keys) # append a crumb for each part for i, key, part in zip(range(nkeys), keys, parts): if part is None: continue partdata = dict(zip(keys, parts)[:i + 1]) target = self.library_set_data(**partdata) pb, icon = None, None if key == 'album': # Album artwork, with self.alumbpb as a backup: artist, album, path = self.library_get_data(self.config.wd, 'artist', 'album', 'path') cache_data = self.library_set_data(artist=artist, album=album, path=path) pb = self.artwork.get_library_artwork_cached_pb(cache_data, None) if pb is None: icon = 'album' elif key == 'artist': icon = 'artist' else: icon = gtk.STOCK_ORIENTATION_PORTRAIT crumbs.append((part, icon, pb, target)) # add a button for each crumb for crumb in crumbs: text, icon, pb, target = crumb text = misc.escape_html(text) if crumb is crumbs[-1]: text = "<b>%s</b>" % text label = ui.label(markup=text) if icon: image = ui.image(stock=icon) elif pb: pb = pb.scale_simple(16, 16, gtk.gdk.INTERP_HYPER) image = ui.image(pb=pb) b = breadcrumbs.CrumbButton(image, label) if crumb is crumbs[-1]: # FIXME makes the button request minimal space: # label.props.ellipsize = pango.ELLIPSIZE_END b.props.active = True # FIXME why doesn't the tooltip show? b.set_tooltip_text(label.get_label()) b.connect('toggled', self.library_browse, target) self.breadcrumbs.pack_start(b, False, False) b.show_all() def library_populate_add_parent_rows(self): return [] # disabled as breadcrumbs replace these if self.config.lib_view == consts.VIEW_FILESYSTEM: bd = [('0', [self.harddiskpb, self.library_set_data(path='/'), '/'])] bd += [('1', [self.openpb, self.library_set_data(path='..'), '..'])] else: bd = [('0', [self.harddiskpb2, self.library_set_data(path='/'), '/'])] bd += [('1', [self.openpb2, self.library_set_data(path='..'), '..'])] return bd def library_populate_filesystem_data(self, path): # List all dirs/files at path bd = [] if path == '/' and self.lib_view_filesystem_cache is not None: # Use cache if possible... bd = self.lib_view_filesystem_cache else: for item in self.mpd.lsinfo(path): if 'directory' in item: name = mpdh.get(item, 'directory').split('/')[-1] data = self.library_set_data(path=mpdh.get(item, 'directory')) bd += [('d' + unicode(name).lower(), [self.openpb, data, misc.escape_html(name)])] elif 'file' in item: data = self.library_set_data(path=mpdh.get(item, 'file')) bd += [('f' + unicode(mpdh.get(item, 'file')).lower(), [self.sonatapb, data, formatting.parse(self.config.libraryformat, item, True)])] bd.sort(key=operator.itemgetter(0)) if path != '/' and len(bd) > 0: bd = self.library_populate_add_parent_rows() + bd if path == '/': self.lib_view_filesystem_cache = bd return bd def library_get_toplevel_cache(self, genreview=False, artistview=False, albumview=False): if genreview and self.lib_view_genre_cache is not None: bd = self.lib_view_genre_cache elif artistview and self.lib_view_artist_cache is not None: bd = self.lib_view_artist_cache elif albumview and self.lib_view_album_cache is not None: bd = self.lib_view_album_cache else: return None # Check if we can update any artwork: for _sort, info in bd: pb = info[0] if pb == self.albumpb: artist, album, path = self.library_get_data(info[1], 'artist', 'album', 'path') key = self.library_set_data(path=path, artist=artist, album=album) pb2 = self.artwork.get_library_artwork_cached_pb(key, None) if pb2 is not None: info[0] = pb2 return bd def library_populate_toplevel_data(self, genreview=False, artistview=False, albumview=False): bd = self.library_get_toplevel_cache(genreview, artistview, albumview) if bd is not None: # We have our cached data, woot. return bd bd = [] if genreview or artistview: # Only for artist/genre views, album view is handled differently # since multiple artists can have the same album name if genreview: items = self.library_return_list_items('genre') pb = self.genrepb else: items = self.library_return_list_items('artist') pb = self.artistpb if not (self.NOTAG in items): items.append(self.NOTAG) for item in items: if genreview: playtime, num_songs = self.library_return_count(genre=item) data = self.library_set_data(genre=item) else: playtime, num_songs = self.library_return_count( artist=item) data = self.library_set_data(artist=item) if num_songs > 0: display = misc.escape_html(item) display += self.add_display_info(num_songs, int(playtime) / 60) bd += [(misc.lower_no_the(item), [pb, data, display])] elif albumview: albums = [] untagged_found = False for item in self.mpd.listallinfo('/'): if 'file' in item and 'album' in item: album = mpdh.get(item, 'album') artist = mpdh.get(item, 'artist', self.NOTAG) year = mpdh.get(item, 'date', self.NOTAG) path = self.get_multicd_album_root_dir( os.path.dirname(mpdh.get(item, 'file'))) data = self.library_set_data(album=album, artist=artist, year=year, path=path) albums.append(data) if album == self.NOTAG: untagged_found = True if not untagged_found: albums.append(self.library_set_data(album=self.NOTAG)) albums = misc.remove_list_duplicates(albums, case=False) albums = self.list_identify_VA_albums(albums) for item in albums: album, artist, year, path = self.library_get_data(item, 'album', 'artist', 'year', 'path') playtime, num_songs = self.library_return_count(artist=artist, album=album, year=year) if num_songs > 0: data = self.library_set_data(artist=artist, album=album, year=year, path=path) display = misc.escape_html(album) if artist and year and len(artist) > 0 and len(year) > 0 \ and artist != self.NOTAG and year != self.NOTAG: display += " <span weight='light'>(%s, %s)</span>" \ % (misc.escape_html(artist), misc.escape_html(year)) elif artist and len(artist) > 0 and artist != self.NOTAG: display += " <span weight='light'>(%s)</span>" \ % misc.escape_html(artist) elif year and len(year) > 0 and year != self.NOTAG: display += " <span weight='light'>(%s)</span>" \ % misc.escape_html(year) display += self.add_display_info(num_songs, int(playtime) / 60) bd += [(misc.lower_no_the(album), [self.albumpb, data, display])] bd.sort(locale.strcoll, key=operator.itemgetter(0)) if genreview: self.lib_view_genre_cache = bd elif artistview: self.lib_view_artist_cache = bd elif albumview: self.lib_view_album_cache = bd return bd def list_identify_VA_albums(self, albums): for i in range(len(albums)): if i + consts.NUM_ARTISTS_FOR_VA - 1 > len(albums)-1: break VA = False for j in range(1, consts.NUM_ARTISTS_FOR_VA): if unicode(self.library_get_data(albums[i], 'album')).lower() \ != unicode(self.library_get_data(albums[i + j], 'album')).lower() or \ self.library_get_data(albums[i], 'year') != \ self.library_get_data(albums[i + j], 'year') or \ self.library_get_data(albums[i], 'path') != \ self.library_get_data(albums[i + j], 'path'): break if unicode(self.library_get_data(albums[i], 'artist')) == \ unicode(self.library_get_data(albums[i + j], 'artist')): albums.pop(i + j) break if j == consts.NUM_ARTISTS_FOR_VA - 1: VA = True if VA: album, year, path = self.library_get_data(albums[i], 'album', 'year', 'path') artist = self.VAstr albums[i] = self.library_set_data(album=album, artist=artist, year=year, path=path) j = 1 while i + j <= len(albums) - 1: if unicode(self.library_get_data(albums[i], 'album')).lower() == \ unicode(self.library_get_data(albums[i + j], 'album')).lower() \ and self.library_get_data(albums[i], 'year') == \ self.library_get_data(albums[i + j], 'year'): albums.pop(i + j) else: break return albums def get_VAstr(self): return self.VAstr def library_populate_data(self, genre=None, artist=None, album=None, year=None): # Create treeview model info bd = [] if genre is not None and artist is None and album is None: # Artists within a genre artists = self.library_return_list_items('artist', genre=genre) if len(artists) > 0: if not self.NOTAG in artists: artists.append(self.NOTAG) for artist in artists: playtime, num_songs = self.library_return_count( genre=genre, artist=artist) if num_songs > 0: display = misc.escape_html(artist) display += self.add_display_info(num_songs, int(playtime) / 60) data = self.library_set_data(genre=genre, artist=artist) bd += [(misc.lower_no_the(artist), [self.artistpb, data, display])] elif artist is not None and album is None: # Albums/songs within an artist and possibly genre # Albums first: if genre is not None: albums = self.library_return_list_items('album', genre=genre, artist=artist) else: albums = self.library_return_list_items('album', artist=artist) for album in albums: if genre is not None: years = self.library_return_list_items('date', genre=genre, artist=artist, album=album) else: years = self.library_return_list_items('date', artist=artist, album=album) if not self.NOTAG in years: years.append(self.NOTAG) for year in years: if genre is not None: playtime, num_songs = self.library_return_count( genre=genre, artist=artist, album=album, year=year) if num_songs > 0: files = self.library_return_list_items( 'file', genre=genre, artist=artist, album=album, year=year) path = os.path.dirname(files[0]) data = self.library_set_data(genre=genre, artist=artist, album=album, year=year, path=path) else: playtime, num_songs = self.library_return_count( artist=artist, album=album, year=year) if num_songs > 0: files = self.library_return_list_items( 'file', artist=artist, album=album, year=year) path = os.path.dirname(files[0]) data = self.library_set_data(artist=artist, album=album, year=year, path=path) if num_songs > 0: cache_data = self.library_set_data(artist=artist, album=album, path=path) display = misc.escape_html(album) if year and len(year) > 0 and year != self.NOTAG: display += " <span weight='light'>(%s)</span>" \ % misc.escape_html(year) display += self.add_display_info(num_songs, int(playtime) / 60) ordered_year = year if ordered_year == self.NOTAG: ordered_year = '9999' pb = self.artwork.get_library_artwork_cached_pb( cache_data, self.albumpb) bd += [(ordered_year + misc.lower_no_the(album), [pb, data, display])] # Now, songs not in albums: bd += self.library_populate_data_songs(genre, artist, self.NOTAG, None) else: # Songs within an album, artist, year, and possibly genre bd += self.library_populate_data_songs(genre, artist, album, year) if len(bd) > 0: bd = self.library_populate_add_parent_rows() + bd bd.sort(locale.strcoll, key=operator.itemgetter(0)) return bd def library_populate_data_songs(self, genre, artist, album, year): bd = [] if genre is not None: songs, _playtime, _num_songs = \ self.library_return_search_items(genre=genre, artist=artist, album=album, year=year) else: songs, _playtime, _num_songs = self.library_return_search_items( artist=artist, album=album, year=year) for song in songs: data = self.library_set_data(path=mpdh.get(song, 'file')) track = mpdh.get(song, 'track', '99', False, 2) disc = mpdh.get(song, 'disc', '99', False, 2) try: bd += [('f' + disc + track + misc.lower_no_the( mpdh.get(song, 'title')), [self.sonatapb, data, formatting.parse( self.config.libraryformat, song, True)])] except: bd += [('f' + disc + track + \ unicode(mpdh.get(song, 'file')).lower(), [self.sonatapb, data, formatting.parse(self.config.libraryformat, song, True)])] return bd def library_return_list_items(self, itemtype, genre=None, artist=None, album=None, year=None, ignore_case=True): # Returns all items of tag 'itemtype', in alphabetical order, # using mpd's 'list'. If searchtype is passed, use # a case insensitive search, via additional 'list' # queries, since using a single 'list' call will be # case sensitive. results = [] searches = self.library_compose_list_count_searchlist(genre, artist, album, year) if len(searches) > 0: for s in searches: # If we have untagged tags (''), use search instead # of list because list will not return anything. if '' in s: items = [] songs, playtime, num_songs = \ self.library_return_search_items(genre, artist, album, year) for song in songs: items.append(mpdh.get(song, itemtype)) else: items = self.mpd.list(itemtype, *s) for item in items: if len(item) > 0: results.append(item) else: if genre is None and artist is None and album is None and year \ is None: for item in self.mpd.list(itemtype): if len(item) > 0: results.append(item) if ignore_case: results = misc.remove_list_duplicates(results, case=False) results.sort(locale.strcoll) return results def library_return_count(self, genre=None, artist=None, album=None, year=None): # Because mpd's 'count' is case sensitive, we have to # determine all equivalent items (case insensitive) and # call 'count' for each of them. Using 'list' + 'count' # involves much less data to be transferred back and # forth than to use 'search' and count manually. searches = self.library_compose_list_count_searchlist(genre, artist, album, year) playtime = 0 num_songs = 0 for s in searches: if '' in s and self.mpd.version <= (0, 13): # Can't return count for empty tags, use search instead: _results, playtime, num_songs = \ self.library_return_search_items( genre=genre, artist=artist, album=album, year=year) else: count = self.mpd.count(*s) playtime += mpdh.get(count, 'playtime', 0, True) num_songs += mpdh.get(count, 'songs', 0, True) return (playtime, num_songs) def library_compose_list_count_searchlist_single(self, search, typename, cached_list, searchlist): s = [] skip_type = (typename == 'artist' and search == self.VAstr) if search is not None and not skip_type: if search == self.NOTAG: itemlist = [search, ''] else: itemlist = [] if cached_list is None: cached_list = self.library_return_list_items(typename, ignore_case=False) # This allows us to match untagged items cached_list.append('') for item in cached_list: if unicode(item).lower() == unicode(search).lower(): itemlist.append(item) if len(itemlist) == 0: # There should be no results! return None, cached_list for item in itemlist: if len(searchlist) > 0: for item2 in searchlist: s.append(item2 + (typename, item)) else: s.append((typename, item)) else: s = searchlist return s, cached_list def library_compose_list_count_searchlist(self, genre=None, artist=None, album=None, year=None): s = [] s, self.lib_list_genres = \ self.library_compose_list_count_searchlist_single( genre, 'genre', self.lib_list_genres, s) if s is None: return [] s, self.lib_list_artists = \ self.library_compose_list_count_searchlist_single( artist, 'artist', self.lib_list_artists, s) if s is None: return [] s, self.lib_list_albums = \ self.library_compose_list_count_searchlist_single( album, 'album', self.lib_list_albums, s) if s is None: return [] s, self.lib_list_years = \ self.library_compose_list_count_searchlist_single( year, 'date', self.lib_list_years, s) if s is None: return [] return s def library_compose_search_searchlist_single(self, search, typename, searchlist): s = [] skip_type = (typename == 'artist' and search == self.VAstr) if search is not None and not skip_type: if search == self.NOTAG: itemlist = [search, ''] else: itemlist = [search] for item in itemlist: if len(searchlist) > 0: for item2 in searchlist: s.append(item2 + (typename, item)) else: s.append((typename, item)) else: s = searchlist return s def library_compose_search_searchlist(self, genre=None, artist=None, album=None, year=None): s = [] s = self.library_compose_search_searchlist_single(genre, 'genre', s) s = self.library_compose_search_searchlist_single(album, 'album', s) s = self.library_compose_search_searchlist_single(artist, 'artist', s) s = self.library_compose_search_searchlist_single(year, 'date', s) return s def library_return_search_items(self, genre=None, artist=None, album=None, year=None): # Returns all mpd items, using mpd's 'search', along with # playtime and num_songs. searches = self.library_compose_search_searchlist(genre, artist, album, year) for s in searches: args_tuple = tuple(map(str, s)) playtime = 0 num_songs = 0 results = [] if '' in s and self.mpd.version <= (0, 13): # Can't search for empty tags, search broader and # filter instead: # Strip empty tag args from tuple: pos = list(args_tuple).index('') strip_type = list(args_tuple)[pos-1] new_lst = [] for i, item in enumerate(list(args_tuple)): if i != pos and i != pos-1: new_lst.append(item) args_tuple = tuple(new_lst) else: strip_type = None if len(args_tuple) == 0: return None, 0, 0 items = self.mpd.search(*args_tuple) if items is not None: for item in items: if strip_type is None or (strip_type is not None and not \ strip_type in item.keys()): match = True pos = 0 # Ensure that if, e.g., "foo" is searched, # "foobar" isn't returned too for arg in args_tuple[::2]: if arg in item and \ unicode(mpdh.get(item, arg)).upper() != \ unicode(args_tuple[pos + 1]).upper(): match = False break pos += 2 if match: results.append(item) num_songs += 1 playtime += mpdh.get(item, 'time', 0, True) return (results, int(playtime), num_songs) def add_display_info(self, num_songs, playtime): return "\n<small><span weight='light'>%s %s, %s %s</span></small>" \ % (num_songs, gettext.ngettext('song', 'songs', num_songs), playtime, gettext.ngettext('minute', 'minutes', playtime)) def library_retain_selection(self, prev_selection, prev_selection_root, prev_selection_parent): # Unselect everything: if len(self.librarydata) > 0: self.library_selection.unselect_range((0,), (len(self.librarydata) - 1,)) # Now attempt to retain the selection from before the update: for value in prev_selection: for row in self.librarydata: if value == row[1]: self.library_selection.select_path(row.path) break if prev_selection_root: self.library_selection.select_path((0,)) if prev_selection_parent: self.library_selection.select_path((1,)) def library_set_view(self, select_items=True): # select_items should be false if the same directory has merely # been refreshed (updated) try: if self.config.wd in self.libraryposition: self.library.scroll_to_point( -1, self.libraryposition[self.config.wd]) else: self.library.scroll_to_point(0, 0) except: self.library.scroll_to_point(0, 0) # Select and focus previously selected item if select_items: if self.config.wd in self.libraryselectedpath: try: if self.libraryselectedpath[self.config.wd]: self.library_selection.select_path( self.libraryselectedpath[self.config.wd]) self.library.grab_focus() except: pass def library_set_data(self, *args, **kwargs): return library_set_data(*args, **kwargs) def library_get_data(self, data, *args): return library_get_data(data, *args) def library_get_data_level(self, data): if self.config.lib_view == consts.VIEW_FILESYSTEM: # Returns the number of directories down: if library_get_data(data, 'path') == '/': # Every other path doesn't start with "/", so # start the level numbering at -1 return -1 else: return library_get_data(data, 'path').count("/") else: # Returns the number of items stored in data, excluding # the path: level = 0 album, artist, genre, year = library_get_data( data, 'album', 'artist', 'genre', 'year') for item in [album, artist, genre, year]: if item is not None: level += 1 return level def on_library_key_press(self, widget, event): if event.keyval == gtk.gdk.keyval_from_name('Return'): self.on_library_row_activated(widget, widget.get_cursor()[0]) return True def on_library_query_tooltip(self, widget, x, y, keyboard_mode, tooltip): if keyboard_mode or not self.search_visible(): widget.set_tooltip_text(None) return False bin_x, bin_y = widget.convert_widget_to_bin_window_coords(x, y) pathinfo = widget.get_path_at_pos(bin_x, bin_y) if not pathinfo: widget.set_tooltip_text(None) # If the user hovers over an empty row and then back to # a row with a search result, this will ensure the tooltip # shows up again: gobject.idle_add(self.library_search_tooltips_enable, widget, x, y, keyboard_mode, None) return False treepath, _col, _x2, _y2 = pathinfo i = self.librarydata.get_iter(treepath[0]) path = misc.escape_html(self.library_get_data( self.librarydata.get_value(i, 1), 'path')) song = self.librarydata.get_value(i, 2) new_tooltip = "<b>%s:</b> %s\n<b>%s:</b> %s" \ % (_("Song"), song, _("Path"), path) if new_tooltip != self.libsearch_last_tooltip: self.libsearch_last_tooltip = new_tooltip self.library.set_property('has-tooltip', False) gobject.idle_add(self.library_search_tooltips_enable, widget, x, y, keyboard_mode, tooltip) gobject.idle_add(widget.set_tooltip_markup, new_tooltip) return self.libsearch_last_tooltip = new_tooltip return False #api says we should return True, but this doesn't work? def library_search_tooltips_enable(self, widget, x, y, keyboard_mode, tooltip): self.library.set_property('has-tooltip', True) if tooltip is not None: self.on_library_query_tooltip(widget, x, y, keyboard_mode, tooltip) def on_library_row_activated(self, _widget, path, _column=0): if path is None: # Default to last item in selection: _model, selected = self.library_selection.get_selected_rows() if len(selected) >= 1: path = selected[0] else: return value = self.librarydata.get_value(self.librarydata.get_iter(path), 1) icon = self.librarydata.get_value(self.librarydata.get_iter(path), 0) if icon == self.sonatapb: # Song found, add item self.on_add_item(self.library) elif value == self.library_set_data(path=".."): self.library_browse_parent(None) else: self.library_browse(None, value) def library_get_parent(self): if self.config.lib_view == consts.VIEW_ALBUM: value = self.library_set_data(path="/") elif self.config.lib_view == consts.VIEW_ARTIST: album, artist = self.library_get_data(self.config.wd, 'album', 'artist') if album is not None: value = self.library_set_data(artist=artist) else: value = self.library_set_data(path="/") elif self.config.lib_view == consts.VIEW_GENRE: album, artist, genre = self.library_get_data( self.config.wd, 'album', 'artist', 'genre') if album is not None: value = self.library_set_data(genre=genre, artist=artist) elif artist is not None: value = self.library_set_data(genre=genre) else: value = self.library_set_data(path="/") else: newvalue = '/'.join( self.library_get_data(self.config.wd, 'path').split('/')[:-1])\ or '/' value = self.library_set_data(path=newvalue) return value def library_browse_parent(self, _action): if not self.search_visible(): if self.library.is_focus(): value = self.library_get_parent() self.library_browse(None, value) return True def not_parent_is_selected(self): # Returns True if something is selected and it's not # ".." or "/": model, rows = self.library_selection.get_selected_rows() for path in rows: i = model.get_iter(path) value = model.get_value(i, 2) if value != ".." and value != "/": return True return False def get_path_child_filenames(self, return_root, selected_only=True): # If return_root=True, return main directories whenever possible # instead of individual songs in order to reduce the number of # mpd calls we need to make. We won't want this behavior in some # instances, like when we want all end files for editing tags items = [] if selected_only: model, rows = self.library_selection.get_selected_rows() else: model = self.librarydata rows = [(i,) for i in range(len(model))] for path in rows: i = model.get_iter(path) pb = model.get_value(i, 0) data = model.get_value(i, 1) value = model.get_value(i, 2) if value != ".." and value != "/": album, artist, year, genre, path = self.library_get_data( data, 'album', 'artist', 'year', 'genre', 'path') if path is not None and album is None and artist is None and \ year is None and genre is None: if pb == self.sonatapb: # File items.append(path) else: # Directory if not return_root: items += self.library_get_path_files_recursive( path) else: items.append(path) else: results, _playtime, _num_songs = \ self.library_return_search_items( genre=genre, artist=artist, album=album, year=year) for item in results: items.append(mpdh.get(item, 'file')) # Make sure we don't have any EXACT duplicates: items = misc.remove_list_duplicates(items, case=True) return items def library_get_path_files_recursive(self, path): results = [] for item in self.mpd.lsinfo(path): if 'directory' in item: results = results + self.library_get_path_files_recursive( mpdh.get(item, 'directory')) elif 'file' in item: results.append(mpdh.get(item, 'file')) return results def on_library_search_combo_change(self, _combo=None): self.config.last_search_num = self.searchcombo.get_active() if not self.search_visible(): return self.prevlibtodo = "" self.prevlibtodo_base = "__" self.libsearchfilter_feed_loop(self.searchtext) def on_search_end(self, _button, move_focus=True): if self.search_visible(): self.libsearchfilter_toggle(move_focus) def search_visible(self): return self.searchbutton.get_property('visible') def libsearchfilter_toggle(self, move_focus): if not self.search_visible() and self.connected(): self.library.set_property('has-tooltip', True) ui.show(self.searchbutton) self.prevlibtodo = 'foo' self.prevlibtodo_base = "__" self.prevlibtodo_base_results = [] # extra thread for background search work, # synchronized with a condition and its internal mutex self.libfilterbox_cond = threading.Condition() self.libfilterbox_cmd_buf = self.searchtext.get_text() qsearch_thread = threading.Thread(target=self.libsearchfilter_loop) qsearch_thread.setDaemon(True) qsearch_thread.start() elif self.search_visible(): ui.hide(self.searchbutton) self.searchtext.handler_block(self.libfilter_changed_handler) self.searchtext.set_text("") self.searchtext.handler_unblock(self.libfilter_changed_handler) self.libsearchfilter_stop_loop() self.library_browse(root=self.config.wd) if move_focus: self.library.grab_focus() def libsearchfilter_feed_loop(self, editable): if not self.search_visible(): self.libsearchfilter_toggle(None) # Lets only trigger the searchfilter_loop if 200ms pass # without a change in gtk.Entry try: gobject.source_remove(self.libfilterbox_source) except: pass self.libfilterbox_source = gobject.timeout_add( 300, self.libsearchfilter_start_loop, editable) def libsearchfilter_start_loop(self, editable): self.libfilterbox_cond.acquire() self.libfilterbox_cmd_buf = editable.get_text() self.libfilterbox_cond.notifyAll() self.libfilterbox_cond.release() def libsearchfilter_stop_loop(self): self.libfilterbox_cond.acquire() self.libfilterbox_cmd_buf = '$$$QUIT###' self.libfilterbox_cond.notifyAll() self.libfilterbox_cond.release() def libsearchfilter_loop(self): while True: # copy the last command or pattern safely self.libfilterbox_cond.acquire() try: while(self.libfilterbox_cmd_buf == '$$$DONE###'): self.libfilterbox_cond.wait() todo = self.libfilterbox_cmd_buf self.libfilterbox_cond.release() except: todo = self.libfilterbox_cmd_buf searchby = self.search_terms_mpd[self.config.last_search_num] if self.prevlibtodo != todo: if todo == '$$$QUIT###': gobject.idle_add(self.filtering_entry_revert_color, self.searchtext) return elif len(todo) > 1: gobject.idle_add(self.libsearchfilter_do_search, searchby, todo) elif len(todo) == 0: gobject.idle_add(self.filtering_entry_revert_color, self.searchtext) self.libsearchfilter_toggle(False) else: gobject.idle_add(self.filtering_entry_revert_color, self.searchtext) self.libfilterbox_cond.acquire() self.libfilterbox_cmd_buf = '$$$DONE###' try: self.libfilterbox_cond.release() except: pass self.prevlibtodo = todo def libsearchfilter_do_search(self, searchby, todo): if not self.prevlibtodo_base in todo: # Do library search based on first two letters: self.prevlibtodo_base = todo[:2] self.prevlibtodo_base_results = self.mpd.search(searchby, self.prevlibtodo_base) subsearch = False else: subsearch = True # Now, use filtering similar to playlist filtering: # this make take some seconds... and we'll escape the search text # because we'll be searching for a match in items that are also escaped # # Note that the searching is not order specific. That is, "foo bar" # will match on "fools bar" and "barstool foo". todos = todo.split(" ") regexps = [] for i in range(len(todos)): todos[i] = misc.escape_html(todos[i]) todos[i] = re.escape(todos[i]) todos[i] = '.*' + todos[i].lower() regexps.append(re.compile(todos[i])) matches = [] if searchby != 'any': for row in self.prevlibtodo_base_results: is_match = True for regexp in regexps: if not regexp.match(unicode(mpdh.get(row, searchby)).lower()): is_match = False break if is_match: matches.append(row) else: for row in self.prevlibtodo_base_results: allstr = " ".join(mpdh.get(row, meta) for meta in row) is_match = True for regexp in regexps: if not regexp.match(unicode(allstr).lower()): is_match = False break if is_match: matches.append(row) if subsearch and len(matches) == len(self.librarydata): # nothing changed.. return self.library.freeze_child_notify() currlen = len(self.librarydata) bd = [[self.sonatapb, self.library_set_data(path=mpdh.get(item, 'file')), formatting.parse(self.config.libraryformat, item, True)] for item in matches if 'file' in item] bd.sort(locale.strcoll, key=operator.itemgetter(2)) for i, item in enumerate(bd): if i < currlen: j = self.librarydata.get_iter((i, )) for index in range(len(item)): if item[index] != self.librarydata.get_value(j, index): self.librarydata.set_value(j, index, item[index]) else: self.librarydata.append(item) # Remove excess items... newlen = len(bd) if newlen == 0: self.librarydata.clear() else: for i in range(currlen - newlen): j = self.librarydata.get_iter((currlen - 1 - i,)) self.librarydata.remove(j) self.library.thaw_child_notify() if len(matches) == 0: gobject.idle_add(self.filtering_entry_make_red, self.searchtext) else: gobject.idle_add(self.library.set_cursor, '0') gobject.idle_add(self.filtering_entry_revert_color, self.searchtext) def libsearchfilter_key_pressed(self, widget, event): self.filter_key_pressed(widget, event, self.library) def libsearchfilter_on_enter(self, _entry): self.on_library_row_activated(None, None) def libsearchfilter_set_focus(self): gobject.idle_add(self.searchtext.grab_focus) def libsearchfilter_get_style(self): return self.searchtext.get_style()
onto/sonata
sonata/library.py
Python
gpl-3.0
66,200
<?php /** * Redimenssionne une photo en 640x340 px pour la page d'accueil de la version mobile * * PHP Version 5.3.3 * * @category General * @package ArchiWiki * @author Pierre Rudloff <contact@rudloff.pro> * @license GNU GPL v3 https://www.gnu.org/licenses/gpl.html * @link https://archi-strasbourg.org/ * * */ require_once "includes/framework/config.class.php"; $config = new Config(); $req = " SELECT dateUpload FROM historiqueImage WHERE idHistoriqueImage = ".mysql_real_escape_string($_GET["id"]); $res =$config->connexionBdd->requete($req); $image=mysql_fetch_object($res); $path="images/grand/".$image->dateUpload."/".$_GET["id"].".jpg"; $infos=getimagesize($path); $input = imagecreatefromjpeg($path); header("Content-Type: image/jpeg"); $width=640; $height=($infos[1]*640)/$infos[0]; $output = imagecreatetruecolor(640, 340); //$output = imagecreatetruecolor($width, $height); if ($infos[1] > $infos[0]) { $x=-170; } else { $x=0; } imagecopyresampled( $output, $input, 0, $x, 0, 0, $width, $height, $infos[0], $infos[1] ); imagejpeg($output); ?>
rotagraziosi/archi-wiki-inpeople
getPhotoHome.php
PHP
gpl-3.0
1,115
from django.shortcuts import render def about(request): return render(request, "about.html", {}) def location(request): return render(request, "location.html", {}) def failure(request): return render(request, "failure.html", {})
apul1421/table-client-side-app-retake
src/ecommerce2/views.py
Python
gpl-3.0
237
package com.zanghongtu.blog.util; /** * 摘要 */ public class SummaryParser { private static final int SUMMARY_LENGTH = 256; /** * 去除info里content 所有html字符 * 截取字符串长度256 * @param sourceStr 源字符串 * @return 截取后的字符串 */ public static String getSummary(String sourceStr) { if(StringUtils.isBlank(sourceStr)){ return ""; } sourceStr= removeHTML(sourceStr); sourceStr = sourceStr.trim().replaceAll("\t", " ").replaceAll("\n", " ") .replaceAll("\r", " ").replaceAll("&nbsp;", " ") .replaceAll("\\s+", " "); if(sourceStr.length() > SUMMARY_LENGTH) { sourceStr = sourceStr.substring(0, SUMMARY_LENGTH); } return sourceStr; } /** * 除去所有html tag * * @param source 源字符串 * @return 去除HTMLisBlank标签后的字符串 */ private static String removeHTML(String source) { if (source == null || source.length() == 0) return ""; StringBuilder sb = new StringBuilder(); Character IN = '<', OUT = '>'; Character currentState = OUT; int currentIndex = 0, nextIndex = -1; for (Character c : source.toCharArray()) { currentIndex++; if (currentIndex >= nextIndex) nextIndex = -1; if (currentState == OUT && c != OUT && c != IN && c != '\"') { if (c == '&') { nextIndex = checkInHTMLCode(source, currentIndex); if (nextIndex > -1) nextIndex = currentIndex + nextIndex; } if (nextIndex == -1) sb.append(c); } if (c == OUT) currentState = OUT; if (c == IN) currentState = IN; } return sb.toString(); } /** * RemoveHTML的辅助方法,用于检测是否遇到HTML转义符,如:&nbsp; * * @param source 源字符串 * @param start 扫描开始的位置 * @return 第一个出现转义字符的位置 */ private static int checkInHTMLCode(String source, int start) { int MAX_HTMLCODE_LEN = 10; int index = 0; String substr; if ((source.length() - start - 1) < MAX_HTMLCODE_LEN) substr = source.substring(start); else { substr = source.substring(start, start + MAX_HTMLCODE_LEN); } for (Character c : substr.toCharArray()) { index++; if (index > 1 && c == ';') return index + 1; if (c > 'z' || c < 'a') return -1; } return -1; } }
zanghongtu2006/blog
src/main/java/com/zanghongtu/blog/util/SummaryParser.java
Java
gpl-3.0
2,801
// Example 4-8: Using continue in a loop. #include <cmath> #include <iostream> #include <istream> #include <limits> #include <ostream> using namespace std; int main(int argc, char *argv[]){ while(true) { cout << "Enter a number: "; double x; cin >> x; if (cin.eof() || cin.bad()) // Input error: exit. break; else if (cin.fail()) { // Invalid input: skip the rest of the line. cin.clear(); cin.ignore(numeric_limits<int>::max(), '\n'); continue; } cout << "sqrt(" << x << ")=" << sqrt(x) << endl; } }
paulmcquad/CPP
C++98/Lesson 4.2 - Statements/ex0408.cpp
C++
gpl-3.0
572
// Make screen : lists different control activities and allows to select which to use var MakeScreen = Screen.extend({ enter: function(){ // Display this screen this.display('make_screen'); // Setup button clicks this.html.find(".btn-play").off().click(function(){ fabrica.navigation.go("/make/play"); }); this.html.find(".btn-upload").off().click(function(){ fabrica.navigation.go("/make/upload"); }); }, }); screens.make = new MakeScreen();
arthurwolf/fabrica
src/interfaces/fabrica/make/make.js
JavaScript
gpl-3.0
503
package org.baeldung.persistence.model; import io.katharsis.resource.annotations.JsonApiId; import io.katharsis.resource.annotations.JsonApiRelation; import io.katharsis.resource.annotations.JsonApiResource; import io.katharsis.resource.annotations.SerializeType; import java.util.Set; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; @Entity @JsonApiResource(type = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @JsonApiId private Long id; private String username; private String email; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) @JsonApiRelation(serialize=SerializeType.EAGER) private Set<Role> roles; public User() { super(); } public User(String username, String email) { super(); this.username = username; this.email = email; } public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (email == null ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User user = (User) obj; if (!email.equals(user.email)) { return false; } return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [id=").append(id).append(", username=").append(username).append(", email=").append(email).append(", roles=").append(roles).append("]"); return builder.toString(); } }
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java
Java
gpl-3.0
2,768
import { Component } from '@angular/core'; @Component({ selector: 'app-page-not-found', templateUrl: './page-not-found.component.html' }) export class PageNotFoundComponent { }
PowerSpikeGG/PowerSpikeGG
powerspikegg/frontend/src/app/page-not-found/page-not-found.component.ts
TypeScript
gpl-3.0
182
/* * Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2006-2011 ScriptDev2 <http://www.scriptdev2.com/> * * Copyright (C) 2010-2011 VoragineCore <http://www.projectvoragine.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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ScriptPCH.h" #include "pit_of_saron.h" #define MAX_ENCOUNTER 3 /* Pit of Saron encounters: 0- Forgemaster Garfrost 1- Krick and Ick 2- Scourgelord Tyrannus */ class instance_pit_of_saron : public InstanceMapScript { public: instance_pit_of_saron() : InstanceMapScript("instance_pit_of_saron", 658) { } InstanceScript* GetInstanceScript(InstanceMap* pMap) const { return new instance_pit_of_saron_InstanceMapScript(pMap); } struct instance_pit_of_saron_InstanceMapScript : public InstanceScript { instance_pit_of_saron_InstanceMapScript(Map* pMap) : InstanceScript(pMap) {}; uint64 uiKrick; uint64 uiIck; uint64 uiGarfrost; uint64 uiTyrannus; uint64 uiRimefang; uint64 uiJainaOrSylvanas1; uint64 uiJainaOrSylvanas2; uint32 uiTeamInInstance; uint32 uiEncounter[MAX_ENCOUNTER]; void Initialize() { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) uiEncounter[i] = NOT_STARTED; uiGarfrost = 0; uiKrick = 0; uiIck = 0; uiTyrannus = 0; } bool IsEncounterInProgress() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (uiEncounter[i] == IN_PROGRESS) return true; return false; } void OnCreatureCreate(Creature* creature) { Map::PlayerList const &players = instance->GetPlayers(); if (!players.isEmpty()) { if (Player* pPlayer = players.begin()->getSource()) uiTeamInInstance = pPlayer->GetTeam(); } switch(creature->GetEntry()) { case CREATURE_KRICK: uiKrick = creature->GetGUID(); break; case CREATURE_ICK: uiIck = creature->GetGUID(); break; case CREATURE_GARFROST: uiGarfrost = creature->GetGUID(); break; case CREATURE_TYRANNUS: uiTyrannus = creature->GetGUID(); break; case CREATURE_RIMEFANG: uiRimefang = creature->GetGUID(); break; case NPC_SYLVANAS_PART1: if (uiTeamInInstance == ALLIANCE) creature->UpdateEntry(NPC_JAINA_PART1, ALLIANCE); uiJainaOrSylvanas1 = creature->GetGUID(); break; case NPC_SYLVANAS_PART2: if (uiTeamInInstance == ALLIANCE) creature->UpdateEntry(NPC_JAINA_PART2, ALLIANCE); uiJainaOrSylvanas2 = creature->GetGUID(); break; case NPC_KILARA: if (uiTeamInInstance == ALLIANCE) creature->UpdateEntry(NPC_ELANDRA, ALLIANCE); break; case NPC_KORALEN: if (uiTeamInInstance == ALLIANCE) creature->UpdateEntry(NPC_KORLAEN, ALLIANCE); break; case NPC_CHAMPION_1_HORDE: if (uiTeamInInstance == ALLIANCE) creature->UpdateEntry(NPC_CHAMPION_1_ALLIANCE, ALLIANCE); break; case NPC_CHAMPION_2_HORDE: if (uiTeamInInstance == ALLIANCE) creature->UpdateEntry(NPC_CHAMPION_2_ALLIANCE, ALLIANCE); break; case NPC_CHAMPION_3_HORDE: // No 3rd set for Alliance? if (uiTeamInInstance == ALLIANCE) creature->UpdateEntry(NPC_CHAMPION_2_ALLIANCE, ALLIANCE); break; } } uint64 GetData64(uint32 identifier) { switch(identifier) { case DATA_GARFROST: return uiGarfrost; case DATA_KRICK: return uiKrick; case DATA_ICK: return uiIck; case DATA_TYRANNUS: return uiTyrannus; case DATA_RIMEFANG: return uiRimefang; case DATA_JAINA_SYLVANAS_1: return uiJainaOrSylvanas1; case DATA_JAINA_SYLVANAS_2: return uiJainaOrSylvanas2; } return 0; } void SetData(uint32 type, uint32 data) { switch(type) { case DATA_GARFROST_EVENT: uiEncounter[0] = data; break; case DATA_TYRANNUS_EVENT: uiEncounter[1] = data; break; case DATA_KRICKANDICK_EVENT: uiEncounter[2] = data; break; } if (data == DONE) SaveToDB(); } uint32 GetData(uint32 type) { switch(type) { case DATA_GARFROST_EVENT: return uiEncounter[0]; case DATA_TYRANNUS_EVENT: return uiEncounter[1]; case DATA_KRICKANDICK_EVENT: return uiEncounter[2]; } return 0; } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::string str_data; std::ostringstream saveStream; saveStream << "P S " << uiEncounter[0] << " " << uiEncounter[1] << " " << uiEncounter[2]; str_data = saveStream.str(); OUT_SAVE_INST_DATA_COMPLETE; return str_data; } void Load(const char* in) { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); char dataHead1, dataHead2; uint16 data0, data1, data2; std::istringstream loadStream(in); loadStream >> dataHead1 >> dataHead2 >> data0 >> data1 >> data2; if (dataHead1 == 'P' && dataHead2 == 'S') { uiEncounter[0] = data0; uiEncounter[1] = data1; uiEncounter[2] = data2; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (uiEncounter[i] == IN_PROGRESS) uiEncounter[i] = NOT_STARTED; } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } }; }; void AddSC_instance_pit_of_saron() { new instance_pit_of_saron(); }
VirusOnline/VoragineCore
src/server/scripts/Instances/Icecrown_Citadel/Pit_of_Saron/instance_pit_of_saron.cpp
C++
gpl-3.0
7,735
import json import urllib import urllib2 def shorten(url): gurl = 'http://goo.gl/api/url?url=%s' % urllib.quote(url) req = urllib2.Request(gurl, data='') req.add_header('User-Agent','toolbar') results = json.load(urllib2.urlopen(req)) return results['short_url']
arjunjain/nixurl
NixURL/exlib/google.py
Python
gpl-3.0
284
const chart = { format: '{point.name}: {point.y:,.2f}', colorNames: [ 'success', 'info', 'warning', 'danger', 'primary', 'highlight', 'default' ], colors: [], patterns: [], style: {}, plotOptions: function () { return { series: { animation: false, dataLabels: { enabled: true, format: this.format }, cursor: 'pointer', borderWidth: 3, } } }, responsivePlotOptions: function () { return { series: { animation: false, dataLabels: { format: this.format } } } }, rule: function () { return { condition: { maxWidth: 500 }, chartOptions: { plotOptions: this.responsivePlotOptions() } } }, getPattern: function(index, colors) { const p = index % Highcharts.patterns.length; return { pattern: Highcharts.merge( Highcharts.patterns[p], { color: colors[index] } ) } }, cssVar: function(name) { return this.style.getPropertyValue(`--${name}`) }, init: function(decimal, thousand) { this.style = getComputedStyle(document.documentElement) for (let p = 0; p < 4; p++) { for (let n = 0; n < this.colorNames.length; n++) { const color = this.cssVar( `${this.colorNames[n]}-${p}` ) this.colors.push(color) } } this.patterns = this.colors.map( (_, index, array) => this.getPattern(index, array) ) Highcharts.setOptions({ chart: { style: { fontFamily: this.cssVar('--font-general'), }, }, lang: { decimalPoint: decimal, thousandsSep: thousand, }, }); }, draw: function(id, title, seriesName, data) { const chart = Highcharts.chart( id, { chart: { type: 'pie' }, title: { text: title, style: { color: this.cssVar('primary-0'), } }, colors: this.patterns, plotOptions: this.plotOptions(), series: [{ name: seriesName, data: data }], responsive: { rules: [this.rule()] }, } ) const that = this $('#patterns-enabled').click(function () { chart.update({ colors: this.checked ? that.patterns : that.colors }) }) }, }
darakeon/dfm
site/MVC/Assets/scripts/chart.js
JavaScript
gpl-3.0
2,100
<?php $dbname="jxj"; $con = mysql_connect("localhost","root","admin123"); mysql_query("set names 'UTF8'"); mysql_query("set character 'UTF8'"); if(!$con) { die('Could not connect: '.mysql_error()); } $db_selected = mysql_select_db($dbname, $con); if(!$db_selected) { $sql="CREATE DATABASE $dbname"; if(mysql_query($sql,$con)){ echo "Database $dbname created successfully\n"; $db_selected=mysql_select_db($dbname,$con); /////////////////// create table $sql = "CREATE TABLE IF NOT EXISTS admin ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL)"; $res = mysql_query($sql); $sql = "CREATE TABLE IF NOT EXISTS users ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, cardid VARCHAR(40) NOT NULL, name VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, phone VARCHAR(255) NOT NULL, telp VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, major VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, readway VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, teacher VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, year INT(11) NOT NULL, password VARCHAR(255) NOT NULL)"; $res = mysql_query($sql); $sql = "CREATE TABLE IF NOT EXISTS journals ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, idcard VARCHAR(40) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, journal VARCHAR(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, title VARCHAR(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, doi VARCHAR(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, ifactor REAL NOT NULL, nauthors INT NOT NULL, seq INT NOT NULL, coaffi VARCHAR(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, coauthor VARCHAR(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, weight REAL NOT NULL, award VARCHAR(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, status VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL )"; $res = mysql_query($sql); $sql = "CREATE TABLE IF NOT EXISTS impact ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, journal VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, ifactor REAL NOT NULL)"; $res = mysql_query($sql); $sql = "CREATE TABLE IF NOT EXISTS jxjkinds ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, jxjname VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, jxjid INT(4) NOT NULL, status TINYINT(1) NOT NULL, statusx TINYINT(1) NOT NULL)"; $res = mysql_query($sql); $sql = "CREATE TABLE IF NOT EXISTS students ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, idcard VARCHAR(40) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, award VARCHAR(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, nif VARCHAR(500) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL )"; $res = mysql_query($sql); $sql = "CREATE TABLE IF NOT EXISTS archived ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, cardid VARCHAR(40) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, award VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, ifactor VARCHAR(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL )"; $res = mysql_query($sql); /////////////////// create table $sql = "insert into admin (username,password) values ('admin','21232f297a57a5a743894a0e4a801fc3')"; $res = mysql_query($sql); /////////////////// create table } } ?>
kjshao/Scholarship
jxj/conn.php
PHP
gpl-3.0
3,523
# -*- coding: utf-8 -*- ################################################ ## Aplikacja wspomagajaca tworzenie bazy publikacji naukowych wpsółpracujaca z Google Scholar ## Copyright (C) 2013 Damian Baran ## ## 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/>. ################################################ import wx import os import wx.xrc import modules.baz.cDatabase as cDatabase import linecache ########################################################################### ## Class PubDialog ########################################################################### ## Dokumentacja dla klasy # # Klasa zawiera widok z zarzadzaniem publikacjami class PubDialog ( wx.Dialog ): ## Konstruktor def __init__( self ): wx.Dialog.__init__ ( self, None, id = wx.ID_ANY, title = u"Zarządzanie Publikacjami", pos = wx.DefaultPosition, size = wx.Size( 450,430 ), style = wx.DEFAULT_DIALOG_STYLE ) self.session = cDatabase.connectDatabase() self.listType = [] self.getType() ico = wx.Icon('icon/pub.ico', wx.BITMAP_TYPE_ICO) self.SetIcon(ico) self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) bSizer1 = wx.BoxSizer( wx.VERTICAL ) bSizer28 = wx.BoxSizer( wx.VERTICAL ) bSizer21 = wx.BoxSizer( wx.VERTICAL ) self.m_staticText1 = wx.StaticText( self, wx.ID_ANY, u"Dodawanie Publikacji", wx.DefaultPosition, wx.DefaultSize, wx.ALIGN_CENTRE|wx.ST_NO_AUTORESIZE ) self.m_staticText1.Wrap( -1 ) bSizer21.Add( self.m_staticText1, 0, wx.EXPAND|wx.ALL, 5 ) bSizer28.Add( bSizer21, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 5 ) bSizer1.Add( bSizer28, 0, wx.EXPAND, 5 ) bSizer26 = wx.BoxSizer( wx.HORIZONTAL ) bSizer15 = wx.BoxSizer( wx.VERTICAL ) bSizer3 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText2 = wx.StaticText( self, wx.ID_ANY, u"Tytuł:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText2.Wrap( -1 ) bSizer3.Add( self.m_staticText2, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl2 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer3.Add( self.m_textCtrl2, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer3, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 5 ) bSizer5 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText4 = wx.StaticText( self, wx.ID_ANY, u"Autorzy:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText4.Wrap( -1 ) bSizer5.Add( self.m_staticText4, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl4 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer5.Add( self.m_textCtrl4, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer5, 0, wx.EXPAND, 5 ) bSizer4 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText3 = wx.StaticText( self, wx.ID_ANY, u"Cytowania:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText3.Wrap( -1 ) bSizer4.Add( self.m_staticText3, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl3 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer4.Add( self.m_textCtrl3, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer4, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, 5 ) bSizer6 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText5 = wx.StaticText( self, wx.ID_ANY, u"Typ:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText5.Wrap( -1 ) bSizer6.Add( self.m_staticText5, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) m_choice1Choices = self.listType self.m_choice1 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 145,-1 ), m_choice1Choices, 0 ) self.m_choice1.SetSelection( 0 ) bSizer6.Add( self.m_choice1, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer6, 0, wx.EXPAND, 5 ) bSizer7 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText6 = wx.StaticText( self, wx.ID_ANY, u"Rok:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText6.Wrap( -1 ) bSizer7.Add( self.m_staticText6, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl5 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer7.Add( self.m_textCtrl5, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer7, 0, wx.EXPAND, 5 ) bSizer8 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText7 = wx.StaticText( self, wx.ID_ANY, u"DOI:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText7.Wrap( -1 ) bSizer8.Add( self.m_staticText7, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl6 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer8.Add( self.m_textCtrl6, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer8, 0, wx.EXPAND, 5 ) bSizer29 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText9 = wx.StaticText( self, wx.ID_ANY, u"Inny klucz:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText9.Wrap( -1 ) bSizer29.Add( self.m_staticText9, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl7 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer29.Add( self.m_textCtrl7, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer29, 0, wx.EXPAND, 5 ) bSizer9 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText8 = wx.StaticText( self, wx.ID_ANY, u"Wydawca:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText8.Wrap( -1 ) bSizer9.Add( self.m_staticText8, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) m_choice2Choices = cDatabase.getJournalName(self.session) self.m_choice2 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 145,-1 ), m_choice2Choices, 0 ) bSizer9.Add( self.m_choice2, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer9, 0, wx.EXPAND, 5 ) bSizer17 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText10 = wx.StaticText( self, wx.ID_ANY, u"Źródło:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText10.Wrap( -1 ) bSizer17.Add( self.m_staticText10, 1, wx.ALL, 5 ) self.m_textCtrl71 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer17.Add( self.m_textCtrl71, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer17, 1, wx.EXPAND, 5 ) bSizer18 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText99 = wx.StaticText( self, wx.ID_ANY, u"LMCP:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText99.Wrap( -1 ) bSizer18.Add( self.m_staticText99, 1, wx.ALL, 5 ) self.m_textCtrl99 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) self.m_textCtrl99.SetToolTipString( u"Ilość punktów na liście ministerialnej" ) bSizer18.Add( self.m_textCtrl99, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer18, 1, wx.EXPAND, 5 ) bSizer19 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText98 = wx.StaticText( self, wx.ID_ANY, u"JCR:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText98.Wrap( -1 ) bSizer19.Add( self.m_staticText98, 1, wx.ALL, 5 ) m_choice3Choices = ['True', 'False'] self.m_choice3 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 145,-1 ), m_choice3Choices, 0 ) bSizer19.Add( self.m_choice3, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer19, 1, wx.EXPAND, 5 ) bSizer26.Add( bSizer15, 1, wx.EXPAND, 5 ) bSizer23 = wx.BoxSizer( wx.VERTICAL ) bSizer10 = wx.BoxSizer( wx.VERTICAL ) m_checkList3Choices = cDatabase.getUserName(self.session) self.m_checkList3 = wx.CheckListBox( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 200,281 ), m_checkList3Choices, 0 ) self.m_checkList3.SetToolTipString( u"Powiąż autorów z publikacją" ) bSizer10.Add( self.m_checkList3, 0, wx.EXPAND|wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer23.Add( bSizer10, 0, wx.EXPAND, 5 ) bSizer26.Add( bSizer23, 1, wx.EXPAND, 5 ) bSizer1.Add( bSizer26, 0, wx.EXPAND, 5 ) bSizer55 = wx.BoxSizer( wx.HORIZONTAL ) self.m_textCtrl55 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( -1,50 ), wx.TE_MULTILINE ) self.m_textCtrl55.SetToolTipString( u"Notatki do publikacji" ) bSizer55.Add( self.m_textCtrl55, 1, wx.ALL|wx.EXPAND, 5 ) bSizer1.Add( bSizer55, 0, wx.EXPAND, 5 ) bSizer11 = wx.BoxSizer( wx.HORIZONTAL ) self.m_button1 = wx.Button( self, wx.ID_ANY, u"Dodaj", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer11.Add( self.m_button1, 0, wx.ALL|wx.EXPAND, 5 ) self.m_button3 = wx.Button( self, wx.ID_ANY, u"Zatwierdź", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer11.Add( self.m_button3, 0, wx.ALL, 5 ) self.m_button4 = wx.Button( self, wx.ID_ANY, u"Zamknij", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer11.Add( self.m_button4, 0, wx.ALL, 5 ) self.m_staticText11 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText11.Wrap( -1 ) bSizer11.Add( self.m_staticText11, 1, wx.ALL, 5 ) self.m_staticText12 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText12.Wrap( -1 ) bSizer11.Add( self.m_staticText12, 1, wx.ALL, 5 ) bSizer1.Add( bSizer11, 0, wx.ALIGN_RIGHT, 5 ) self.SetSizer( bSizer1 ) self.Layout() self.Centre( wx.BOTH ) self.m_button3.Hide() self.m_staticText11.Hide() self.m_staticText12.Hide() ################################################## ## Bind ################################################### self.m_button1.Bind(wx.EVT_BUTTON, self.addPubValue) self.m_button4.Bind(wx.EVT_BUTTON, self.close) self.m_button3.Bind(wx.EVT_BUTTON, self.editPubValue) ################################################### ## Metody ################################################### self.getType() ## Dokumentacja getType # @param self Wskaźnik obiektu # # @return void # Funkcja pobiera typy publikacji z pliku def getType(self): count = len(open('type.txt', 'rU').readlines()) for i in range(count): self.listType.append(linecache.getline('type.txt',i+1)) print self.listType ## Dokumentacja editPubValue # @param self Wskaźnik obiektu # @param event Wywołanie żadania # # @return void # Funkcja wysyla zadanie edycji wybranej publikacji def editPubValue(self, event): #Pobiera wartosci z kontrolek do edycji tmp = self.m_staticText1.GetLabel() tmp = tmp.split('. ', 1) t0 = tmp[1] t1 = self.m_textCtrl2.GetValue() t2 = self.m_textCtrl4.GetValue() t3 = self.m_textCtrl3.GetValue() t4 = self.m_choice1.GetStringSelection() t5 = self.m_textCtrl5.GetValue() t6 = self.m_textCtrl6.GetValue() t7 = self.m_textCtrl7.GetValue() t8 = self.m_choice2.GetStringSelection() t10 = self.m_textCtrl71.GetValue() t11 = self.m_textCtrl99.GetValue() #Lista ministerialna t12 = self.m_choice3.GetStringSelection() #czy jest w JCR t13 = self.m_textCtrl55.GetValue() #notatka #Odznacza już powiazanych autorów ch = cDatabase.editItemAuthor(self.session, t0) t9 = self.getCheckUser() #Pobiera wartosci ID dla zaznaczonych autorów tmp = cDatabase.getJournalNameID(self.session) print t8 if t8 != u'': t8 = tmp[t8] else: t8 = None t = (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) #Sprawdzenie czy obowiazkowe wartości nie sa puste if t1 != '' and t2 != '' and t3 != '' and t5 != '': cDatabase.editPubData(self.session, t, t0) wx.MessageBox(u'Zauktualizowano wartości!', u'Sukces', wx.OK | wx.ICON_INFORMATION) else: wx.MessageBox(u'Nie podana nazwy grupy \nlub nie wybrano autorów.', u'Bład', wx.OK | wx.ICON_INFORMATION) self.Destroy() ## Dokumentacja addPubValue # @param self Wskaźnik obiektu # @param event Wywołanie żadania # # @return void # Funkcja wysyla zadanie dodania nowej publikacji def addPubValue(self, event): #Pobiera wartosci z kontrolek do edycji tx1 = self.m_textCtrl2.GetValue() #tytul tx2 = self.m_textCtrl4.GetValue() #autor tx3 = self.m_textCtrl3.GetValue() #cytowania tx4 = self.m_choice1.GetStringSelection() #typ tx5 = self.m_textCtrl5.GetValue() #rok tx6 = self.m_textCtrl6.GetValue() #doi tx9 = self.m_textCtrl7.GetValue() #identy tx7 = self.m_choice2.GetStringSelection() #wydawca ID tx8 = self.getCheckUser() #autor id tx10 = self.m_textCtrl71.GetValue() #zrodlo tx11 = self.m_staticText11.GetLabel() #urlpub tx12 = self.m_staticText12.GetLabel() #urlcit tx13 = self.m_textCtrl99.GetValue() #Lista ministerialna tx14 = self.m_choice3.GetStringSelection() #jcr tx15 = self.m_textCtrl55.GetValue() #note #Pobiera wartosci ID dla zaznaczonych autorów tmp = cDatabase.getJournalNameID(self.session) if tx7 != u'': tx7 = tmp[tx7] else: tx7 = None t = (tx1, tx2, tx3, tx4, tx5, tx6, tx9, tx7, tx8, tx11, tx12, tx10, tx13, tx14, tx15) #Sprawdzenie czy obowiazkowe wartości nie sa puste if tx1 != '' and tx2 != '' and tx3 != '' and tx5 != '': cDatabase.addPubData(self.session, t) else: wx.MessageBox(u'Pola "Tytuł, Autor, Cytowania, Rok" sa wymagane!', u'Bład', wx.OK | wx.ICON_INFORMATION) self.Destroy() ## Dokumentacja getCheckUser # @param self Wskaźnik obiektu # # @return list Lista ID autorow powiazanych z publikacja # Funkcja pobiera id wszystkich powiazanych autorów do publikacji def getCheckUser(self): result = [] guser = cDatabase.getUserName(self.session) t = cDatabase.getUserNameID(self.session) for i in range(len(guser)): if self.m_checkList3.IsChecked(i): id = t[guser[i]] result.append(id) return result ## Dokumentacja close # @param self Wskaźnik obiektu # @param event Wywołanie żadania # # @return void # Funkcja zamyka okienko z zarzadzaniem publikacjami def close(self, event): """Zamyka okienko publikacji""" self.Destroy() if __name__ == "__main__": app = wx.App(False) controller = PubDialog() controller.Show() app.MainLoop()
damianbaran/inz
popup/publikacja.py
Python
gpl-3.0
16,876
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2016 Wandora Team * * 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.wandora.application.tools.extractors.europeana; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.contexts.Context; /** * * @author nlaitinen */ public class EuropeanaExtractor extends AbstractEuropeanaExtractor { private EuropeanaExtractorUI ui = null; @Override public void execute(Wandora wandora, Context context) { try { if(ui == null) { ui = new EuropeanaExtractorUI(); } ui.open(wandora, context); if(ui.wasAccepted()) { WandoraTool[] extrs = null; try{ extrs = ui.getExtractors(this); } catch(Exception e) { log(e.getMessage()); return; } if(extrs != null && extrs.length > 0) { setDefaultLogger(); int c = 0; log("Performing Europeana API query..."); for(int i=0; i<extrs.length && !forceStop(); i++) { try { WandoraTool e = extrs[i]; e.setToolLogger(getDefaultLogger()); e.execute(wandora); setState(EXECUTE); c++; } catch(Exception e) { log(e); } } log("Ready."); } else { log("Couldn't find a suitable subextractor to perform or there was an error with an extractor."); } } } catch(Exception e) { singleLog(e); } if(ui != null && ui.wasAccepted()) setState(WAIT); else setState(CLOSE); } }
wandora-team/wandora
src/org/wandora/application/tools/extractors/europeana/EuropeanaExtractor.java
Java
gpl-3.0
2,752
/** * * Copyright (c) 2014, Openflexo * * This file is part of Gina, a component of the software infrastructure * developed at Openflexo. * * * Openflexo is dual-licensed under the European Union Public License (EUPL, either * version 1.1 of the License, or any later version ), which is available at * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * and the GNU General Public License (GPL, either version 3 of the License, or any * later version), which is available at http://www.gnu.org/licenses/gpl.html . * * You can redistribute it and/or modify under the terms of either of these licenses * * If you choose to redistribute it and/or modify under the terms of the GNU GPL, you * must include the following additional permission. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with software containing parts covered by the terms * of EPL 1.0, the licensors of this Program grant you additional permission * to convey the resulting work. * * * This software is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.openflexo.org/license.html for details. * * * Please contact Openflexo (openflexo-contacts@openflexo.org) * or visit www.openflexo.org if you need additional information. * */ package org.openflexo.gina.model.bindings; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Type; import java.util.logging.Logger; import org.openflexo.connie.BindingEvaluationContext; import org.openflexo.connie.BindingModel; import org.openflexo.connie.binding.IBindingPathElement; import org.openflexo.connie.binding.SimplePathElement; import org.openflexo.connie.exception.NullReferenceException; import org.openflexo.connie.exception.TypeMismatchException; import org.openflexo.connie.type.TypeUtils; import org.openflexo.gina.model.FIBVariable; import org.openflexo.gina.view.FIBView; public class FIBVariablePathElement extends SimplePathElement implements PropertyChangeListener { private static final Logger logger = Logger.getLogger(FIBVariablePathElement.class.getPackage().getName()); private Type lastKnownType = null; private final FIBVariable<?> fibVariable; public FIBVariablePathElement(IBindingPathElement parent, FIBVariable<?> fibVariable) { super(parent, fibVariable.getName(), fibVariable.getType()); this.fibVariable = fibVariable; lastKnownType = fibVariable.getType(); } @Override public void activate() { super.activate(); if (fibVariable != null && fibVariable.getPropertyChangeSupport() != null) { fibVariable.getPropertyChangeSupport().addPropertyChangeListener(this); } } @Override public void desactivate() { if (fibVariable != null && fibVariable.getPropertyChangeSupport() != null) { fibVariable.getPropertyChangeSupport().removePropertyChangeListener(this); } super.desactivate(); } public FIBVariable<?> getFIBVariable() { return fibVariable; } @Override public String getLabel() { return getPropertyName(); } @Override public String getTooltipText(Type resultingType) { return fibVariable.getDescription(); } @Override public Type getType() { return getFIBVariable().getType(); } @Override public Object getBindingValue(Object target, BindingEvaluationContext context) throws TypeMismatchException, NullReferenceException { // System.out.println("j'evalue " + fibVariable + " pour " + target); // System.out.println("il s'agit de " + fibVariable.getValue()); if (target instanceof FIBView) { Object returned = ((FIBView<?, ?>) target).getVariableValue(fibVariable); // System.out.println("returned=" + returned); if (returned == null || TypeUtils.isOfType(returned, getType())) { // System.out.println("Et je retourne"); return returned; } else { // System.out.println("Ouhlala, on me demande " + getType() + " mais j'ai " + returned.getClass()); // System.out.println("On s'arrete"); return null; } // System.out.println("je retourne " + ((FIBView) // target).getVariableValue(fibVariable)); // return ((FIBView) target).getVariableValue(fibVariable); } logger.warning("Please implement me, target=" + target + " context=" + context); return null; } @Override public void setBindingValue(Object value, Object target, BindingEvaluationContext context) throws TypeMismatchException, NullReferenceException { if (target instanceof FIBView) { ((FIBView) target).setVariableValue(fibVariable, value); return; } logger.warning("Please implement me, target=" + target + " context=" + context); } @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getSource() == getFIBVariable()) { if (evt.getPropertyName().equals(FIBVariable.NAME_KEY)) { // System.out.println("Notify name changing for " + // getFlexoProperty() + " new=" + getVariableName()); getPropertyChangeSupport().firePropertyChange(NAME_PROPERTY, evt.getOldValue(), getLabel()); fibVariable.getOwner().getBindingModel().getPropertyChangeSupport() .firePropertyChange(BindingModel.BINDING_PATH_ELEMENT_NAME_CHANGED, evt.getOldValue(), getLabel()); } if (evt.getPropertyName().equals(FIBVariable.TYPE_KEY)) { Type newType = getFIBVariable().getType(); if (lastKnownType == null || !lastKnownType.equals(newType)) { getPropertyChangeSupport().firePropertyChange(TYPE_PROPERTY, lastKnownType, newType); fibVariable.getOwner().getBindingModel().getPropertyChangeSupport() .firePropertyChange(BindingModel.BINDING_PATH_ELEMENT_TYPE_CHANGED, lastKnownType, newType); lastKnownType = newType; } } if (lastKnownType != getType()) { // We might arrive here only in the case of a FIBVariable does // not correctely notify // its type change. We warn it to 'tell' the developper that // such notification should be done // in FlexoProperty (see IndividualProperty for example) logger.warning("Detecting un-notified type changing for FIBVariable " + fibVariable + " from " + lastKnownType + " to " + getType() + ". Trying to handle case."); getPropertyChangeSupport().firePropertyChange(TYPE_PROPERTY, lastKnownType, getType()); fibVariable.getOwner().getBindingModel().getPropertyChangeSupport() .firePropertyChange(BindingModel.BINDING_PATH_ELEMENT_TYPE_CHANGED, lastKnownType, getType()); lastKnownType = getType(); } } } }
openflexo-team/gina
gina-api/src/main/java/org/openflexo/gina/model/bindings/FIBVariablePathElement.java
Java
gpl-3.0
6,703
/* * This file is part of QuarterBukkit-Plugin. * Copyright (c) 2012 QuarterCode <http://www.quartercode.com/> * * QuarterBukkit-Plugin 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. * * QuarterBukkit-Plugin 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 QuarterBukkit-Plugin. If not, see <http://www.gnu.org/licenses/>. */ package com.quartercode.quarterbukkit.util; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import com.quartercode.quarterbukkit.api.exception.InstallException; import com.quartercode.quarterbukkit.api.exception.InternalException; public class QuarterBukkitExceptionListener implements Listener { private final Plugin plugin; public QuarterBukkitExceptionListener(Plugin plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, plugin); } @EventHandler public void installException(InstallException exception) { if (exception.getCauser() != null) { exception.getCauser().sendMessage(ChatColor.RED + "Can't update " + plugin.getName() + ": " + exception.getMessage()); if (exception.getCause() != null) { exception.getCauser().sendMessage(ChatColor.RED + "Reason: " + exception.getCause().toString()); } } else { plugin.getLogger().warning("Can't update " + plugin.getName() + ": " + exception.getMessage()); if (exception.getCause() != null) { plugin.getLogger().warning("Reason: " + exception.getCause().toString()); } } } @EventHandler public void internalException(InternalException exception) { exception.getCause().printStackTrace(); } }
QuarterCode/QuarterBukkit
plugin/src/main/java/com/quartercode/quarterbukkit/util/QuarterBukkitExceptionListener.java
Java
gpl-3.0
2,265
#include "h17disk.h" #include <stdio.h> static int usage(char *progName) { fprintf(stderr,"Usage: %s old_h17disk_file new_h17disk_file\n",progName); return 1; } int main(int argc, char *argv[]) { H17Disk *image = new(H17Disk); if (argc < 2 || argc > 3) { usage(argv[0]); return 1; } std::string infile(argv[1]); image->loadFile(infile.c_str()); std::string outfile; if (argc == 2) { outfile.assign(argv[1], infile.rfind(".")); outfile.append(".h17raw"); } else { outfile.assign(argv[2]); } printf("------------------------\n"); printf(" Read Complete\n"); printf("------------------------\n"); image->analyze(); image->saveAsRaw(outfile.c_str()); if (image) { delete image; } return 0; }
mgarlanger/heath-imager
src/cmd/h17d_raw.cpp
C++
gpl-3.0
850
__author__ = 'xiaoxiaol' import numpy as np import pylab as pl import scipy import pandas as pd import seaborn as sns import os import sys, getopt from scipy.cluster import hierarchy import platform from scipy.stats.stats import pearsonr import scipy.stats as stats from PIL import Image import glob from sklearn.metrics import silhouette_samples, silhouette_score import math from sklearn.cluster import AffinityPropagation from sklearn import metrics from itertools import cycle #################################### ZSCORE_OUTLIER_THRESHOLD = 5 #################################### sns.set_context("poster") def zscore(features, remove_outlier=0): zscores = scipy.stats.zscore(features, 0) # zscores = normalizeFeatures(features) return zscores # def normalizeFeatures(features): # meanFeatures = np.median(features, 0) # stdFeatures = np.std(features, 0) # if np.count_nonzero(stdFeatures) < len(stdFeatures): # print "zero detected" # print stdFeatures # normalized = (features - meanFeatures) / stdFeatures # return normalized #### need to be updated # def distance_matrix(df_all, feature_names, out_distanceMatrix_file, REMOVE_OUTLIER=0): # feature_array = df_all[feature_names].astype(float) # distanceMatrix = [] # normalized = zscore(feature_array) # #normalized = normalizeFeatures(feature_array) # # if num_outliers > 0: # if not REMOVE_OUTLIER: # only clp # normalized[normalized < -ZSCORE_OUTLIER_THRESHOLD] = -ZSCORE_OUTLIER_THRESHOLD # normalized[normalized > ZSCORE_OUTLIER_THRESHOLD] = ZSCORE_OUTLIER_THRESHOLD # # for i in range(len(normalized)): # queryFeature = normalized[i] # each row is a feature vector # scores = np.exp(-np.sum(abs(normalized - queryFeature) ** 2, 1) / 100) #similarity # #scores = np.sum(np.abs(normalized - queryFeature) ** 2, 1) # distance # distanceMatrix.append(scores) # # df_dist = pd.DataFrame(distanceMatrix) # df_dist.to_csv(out_distanceMatrix_file, index=False) # print("score sim matrix is saved to : " + out_distanceMatrix_file + "\n") # return df_dist def copySnapshots(df_in, snapshots_dir, output_dir): if not os.path.exists(output_dir): os.mkdir(output_dir) swc_files = df_in['swc_file_name'] if len(swc_files) > 0: for afile in swc_files: filename = snapshots_dir + '/' + afile.split('/')[-1] + '.BMP' if os.path.exists(filename): os.system("cp " + filename + " " + output_dir + "/\n") return def assemble_screenshots(input_dir, output_image_file_name, size): files = glob.glob(input_dir + "/*.BMP") assemble_image = Image.new("RGB", (size * len(files),size)) y = 0 for infile in files: im = Image.open(infile) im.thumbnail((size, size), Image.ANTIALIAS) assemble_image.paste(im, (y, 0)) y += size assemble_image.save(output_image_file_name) return def generateLinkerFileFromDF(df_in, output_ano_file, strip_path=False, swc_path=None): swc_files = df_in['swc_file_name'] if len(swc_files) > 0: with open(output_ano_file, 'w') as outf: for afile in swc_files: if swc_path is not None: filename = swc_path + '/'+afile else: filename = afile if strip_path: filename = afile.split('/')[-1] line = 'SWCFILE=' + filename + '\n' outf.write(line) outf.close() return ############## heatmap plot: hierachical clustering ######## # # def heatmap_plot_distancematrix(df_distanceMatrix, merged, output_dir, title=None): # pl.figure() # # # Create a custom palette for creline colors # cre_lines = np.unique(merged['cre_line']) # cre_line_pal = sns.color_palette("hls", len(cre_lines)) # cre_line_lut = dict(zip(cre_lines, cre_line_pal)) # map creline type to color # creline_colors = merged['cre_line'].map(cre_line_lut) # # # Create a custom palette for dendrite_type colors thre colors # dendrite_types = np.unique(merged['dendrite_type']) # dendrite_type_pal = sns.color_palette(['white','gray','black']) # dendrite_type_lut = dict(zip(dendrite_types, dendrite_type_pal)) # dendritetype_colors = merged['dendrite_type'].map(dendrite_type_lut) # # # Create a custom colormap for the heatmap values # #cmap = sns.diverging_palette(240, 10, as_cmap=True) # # g = sns.clustermap(df_distanceMatrix, method='ward', metric='euclidean', linewidths=0.0, # row_colors=dendritetype_colors, col_colors=creline_colors, cmap=cmap, xticklabels=False, # yticklabels=False) # if title: # pl.title(title) # # Legend for row and col colors # # for label in dendrite_types: # pl.bar(0, 0, color=dendrite_type_lut[label], label=label, linewidth=0) # pl.legend(loc="center", ncol=1) # # for label in cre_lines: # g.ax_col_dendrogram.bar(0, 0, color=cre_line_lut[label], label=label, linewidth=0) # g.ax_col_dendrogram.legend(loc="center", ncol=3) # # pl.title('Similarities') # # filename = output_dir + '/similarity_heatmap.png' # pl.savefig(filename, dpi=300) # print("save similarity matrix heatmap figure to :" + filename) # pl.close() return g def plot_confusion_matrix(cm, xlabel, ylabel, xnames, ynames, title='Confusion matrix', cmap=pl.cm.Blues): pl.grid(False) pl.imshow(cm, interpolation = 'none',cmap=cmap) pl.title(title) pl.colorbar() tick_marksx = np.arange(len(xnames)) tick_marksy = np.arange(len(ynames)) pl.xticks(tick_marksx, xnames) pl.yticks(tick_marksy, ynames) pl.tight_layout() pl.ylabel(ylabel) pl.xlabel(xlabel) def heatmap_plot_zscore_ivscc(df_zscore_features, df_all, output_dir, title=None): # Create a custom palette for dendrite_type colors dendrite_types = [np.nan, 'aspiny', 'sparsely spiny', 'spiny'] # dendrite_type_pal = sns.color_palette("coolwarm", len(dendrite_types)) dendrite_type_pal = sns.color_palette(["gray","black","purple","red"]) dendrite_type_lut = dict(zip(dendrite_types, dendrite_type_pal)) dendrite_type_colors = df_all['dendrite_type'].map(dendrite_type_lut) # Create a custom palette for creline colors cre_lines = np.unique(df_all['cre_line']) print cre_lines cre_lines = ['Pvalb-IRES-Cre','Sst-IRES-Cre','Gad2-IRES-Cre', 'Htr3a-Cre_NO152', 'Nr5a1-Cre', 'Ntsr1-Cre','Rbp4-Cre_KL100' ,'Rorb-IRES2-Cre-D', 'Scnn1a-Tg2-Cre', 'Scnn1a-Tg3-Cre','Slc17a6-IRES-Cre','Cux2-CreERT2'] cre_line_pal = sns.color_palette("BrBG", len(cre_lines)) cre_line_lut = dict(zip(cre_lines, cre_line_pal)) # map creline type to color cre_line_colors = df_all['cre_line'].map(cre_line_lut) # layers = np.unique(df_all['layer']) # layer_pal = sns.light_palette("green", len(layers)) # layer_lut = dict(zip(layers, layer_pal)) # layer_colors = df_all['layer'].map(layer_lut) # # only if types are available # types = np.unique(df_all['types']) # #reorder # types = ['NGC','multipolar','symm', 'bitufted','bipolar','tripod', 'Martinotti','cortico-cortical', 'cortico-thal','non-tufted', 'short-thick-tufted', 'tufted','thick-tufted'] # type_pal = sns.color_palette("coolwarm", len(types))# sns.diverging_palette(220, 20, n=len(types))# sns.color_palette("husl", len(types)) # type_lut = dict(zip(types, type_pal)) # type_colors = df_all['types'].map(type_lut) # Create a custom colormap for the heatmap values #cmap = sns.diverging_palette(240, 10, as_cmap=True) linkage = hierarchy.linkage(df_zscore_features, method='ward', metric='euclidean') data = df_zscore_features.transpose() row_linkage = hierarchy.linkage(data, method='ward', metric='euclidean') feature_order = hierarchy.leaves_list(row_linkage) #print data.index matchIndex = [data.index[x] for x in feature_order] #print matchIndex data = data.reindex(matchIndex) g = sns.clustermap(data, row_cluster = False, col_linkage=linkage, method='ward', metric='euclidean', linewidths = 0.0,col_colors = [cre_line_colors,dendrite_type_colors], cmap = sns.cubehelix_palette(light=1, as_cmap=True),figsize=(40,20)) #g.ax_heatmap.xaxis.set_xticklabels() pl.setp(g.ax_heatmap.xaxis.get_majorticklabels(), rotation=90 ) pl.setp(g.ax_heatmap.yaxis.get_majorticklabels(), rotation=0) pl.subplots_adjust(left=0.1, bottom=0.5, right=0.9, top=0.95) # !!!!! #pl.tight_layout( fig, h_pad=20.0, w_pad=20.0) if title: pl.title(title) location ="best" num_cols=1 # Legend for row and col colors for label in cre_lines: g.ax_row_dendrogram.bar(0, 0, color=cre_line_lut[label], label=label, linewidth=0.0) g.ax_row_dendrogram.legend(loc=location, ncol=num_cols,borderpad=0) for i in range(3): g.ax_row_dendrogram.bar(0, 0, color = "white", label=" ", linewidth=0) g.ax_row_dendrogram.legend(loc=location, ncol=num_cols, borderpad=0.0) # for label in layers: # pl.bar(0, 0, color=layer_lut[label], label=label, linewidth=1) # pl.legend(loc="left", ncol=2,borderpad=0.5) # # for label in types: # g.ax_row_dendrogram.bar(0, 0, color=type_lut[label], label=label,linewidth=0) # g.ax_row_dendrogram.legend(loc=location, ncol=num_cols,borderpad=0.0) # # # g.ax_row_dendrogram.bar(0, 0, color = "white", label=" ", linewidth=0) # g.ax_row_dendrogram.legend(loc=location, ncol=num_cols, borderpad=0.0) for label in dendrite_types: g.ax_row_dendrogram.bar(0, 0, color = dendrite_type_lut[label], label=label, linewidth=0) g.ax_row_dendrogram.legend(loc=location, ncol= num_cols, borderpad=0.0) filename = output_dir + '/zscore_feature_heatmap.png' pl.savefig(filename, dpi=300) #pl.show() print("save zscore matrix heatmap figure to :" + filename) pl.close() return linkage def heatmap_plot_zscore_bbp(df_zscore_features, df_all, output_dir, title=None): print "heatmap plot" metric ='m-type' mtypes = np.unique(df_all[metric]) print mtypes mtypes_pal = sns.color_palette("hls", len(mtypes)) mtypes_lut = dict(zip(mtypes, mtypes_pal)) # map creline type to color mtypes_colors = df_all[metric].map(mtypes_lut) layers = np.unique(df_all['layer']) layer_pal = sns.light_palette("green", len(layers)) layers_lut = dict(zip(layers, layer_pal)) layer_colors = df_all['layer'].map(layers_lut) # Create a custom colormap for the heatmap values #cmap = sns.diverging_palette(240, 10, as_cmap=True) linkage = hierarchy.linkage(df_zscore_features, method='ward', metric='euclidean') data = df_zscore_features.transpose() row_linkage = hierarchy.linkage(data, method='ward', metric='euclidean') feature_order = hierarchy.leaves_list(row_linkage) #print data.index matchIndex = [data.index[x] for x in feature_order] #print matchIndex data = data.reindex(matchIndex) g = sns.clustermap(data, row_cluster = False, col_linkage=linkage, method='ward', metric='euclidean', linewidths = 0.0,col_colors = [mtypes_colors,layer_colors], cmap = sns.cubehelix_palette(light=1, as_cmap=True),figsize=(40,20)) #g.ax_heatmap.xaxis.set_xticklabels() pl.setp(g.ax_heatmap.xaxis.get_majorticklabels(), rotation=90 ) pl.setp(g.ax_heatmap.yaxis.get_majorticklabels(), rotation=0) pl.subplots_adjust(left=0.1, bottom=0.5, right=0.9, top=0.95) # !!!!! #pl.tight_layout( fig, h_pad=20.0, w_pad=20.0) if title: pl.title(title) location ="best" num_cols=1 # Legend for row and col colors for label in mtypes: g.ax_row_dendrogram.bar(0, 0, color=mtypes_lut[label], label=label, linewidth=0.0) g.ax_row_dendrogram.legend(loc=location, ncol=num_cols,borderpad=0) for i in range(3): g.ax_row_dendrogram.bar(0, 0, color = "white", label=" ", linewidth=0) g.ax_row_dendrogram.legend(loc=location, ncol=num_cols, borderpad=0.0) for label in layers: g.ax_row_dendrogram.bar(0, 0, color=layers_lut[label], label=label, linewidth=0.0) g.ax_row_dendrogram.legend(loc=location, ncol=num_cols,borderpad=0) filename = output_dir + '/zscore_feature_heatmap.png' pl.savefig(filename, dpi=300) #pl.show() print("save zscore matrix heatmap figure to :" + filename) pl.close() return linkage ########################## feature selection ######################## def remove_correlated_features(df_all, feature_names, coef_threshold=0.98): num_features = len(feature_names) removed_names = [] for i in range(num_features): if not feature_names[i] in removed_names: a = df_all[feature_names[i]].astype(float) for j in range(i + 1, num_features): if not feature_names[j] in removed_names: b = df_all[feature_names[j]].astype(float) corrcoef = pearsonr(a, b) if (corrcoef[0] > coef_threshold): removed_names.append(feature_names[j]) print("highly correlated:[" + feature_names[i] + ", " + feature_names[j] + " ]") subset_features_names = feature_names.tolist() for i in range(len(removed_names)): if removed_names[i] in subset_features_names: print ("remove " + removed_names[i]) subset_features_names.remove(removed_names[i]) return np.asarray(subset_features_names) ####################################### cluster evaluations ################## def delta(ck, cl): values = np.ones([len(ck), len(cl)]) * 10000 for i in range(0, len(ck)): for j in range(0, len(cl)): values[i, j] = np.linalg.norm(ck[i] - cl[j]) return np.min(values) def big_delta(ci): values = np.zeros([len(ci), len(ci)]) for i in range(0, len(ci)): for j in range(0, len(ci)): values[i, j] = np.linalg.norm(ci[i] - ci[j]) return np.max(values) def dunn(k_list): """ Dunn index [CVI] Parameters ---------- k_list : list of np.arrays A list containing a numpy array for each cluster |c| = number of clusters c[K] is np.array([N, p]) (N : number of samples in cluster K, p : sample dimension) """ deltas = np.ones([len(k_list), len(k_list)]) * 1000000 big_deltas = np.zeros([len(k_list), 1]) l_range = range(0, len(k_list)) for k in l_range: for l in (l_range[0:k] + l_range[k + 1:]): deltas[k, l] = delta(k_list[k], k_list[l]) big_deltas[k] = big_delta(k_list[k]) di = np.min(deltas) / np.max(big_deltas) return di ############################### cluster specific features ##### def cluster_specific_features(df_all, assign_ids, feature_names, output_csv_fn): #student t to get cluster specific features labels=[] clusters = np.unique(assign_ids) num_cluster = len(clusters) df_pvalues = pd.DataFrame(index = feature_names, columns = clusters) for cluster_id in clusters: ids_a = np.nonzero(assign_ids == cluster_id)[0] # starting from 0 ids_b = np.nonzero(assign_ids != cluster_id)[0] # starting from 0 labels.append("C"+str(cluster_id) + "("+ str(len(ids_a))+")" ) for feature in feature_names: a = df_all.iloc[ids_a][feature] b = df_all.iloc[ids_b][feature] t_stats,pval = stats.ttest_ind(a,b,equal_var=False) df_pvalues.loc[feature,cluster_id] = -np.log10(pval) df_pvalues.to_csv(output_csv_fn) ### visulaize df_pvalues.index.name = "Features" df_pvalues.columns.name ="Clusters" d=df_pvalues[df_pvalues.columns].astype(float) g = sns.heatmap(data=d,linewidths=0.1) # cmap =sns.color_palette("coolwarm",7, as_cmap=True)) g.set_xticklabels(labels) pl.yticks(rotation=0) pl.xticks(rotation=90) pl.subplots_adjust(left=0.5, right=0.9, top=0.9, bottom=0.1) pl.title('-log10(P value)') filename = output_csv_fn + '.png' pl.savefig(filename, dpi=300) #pl.show() pl.close() return df_pvalues ############################################################################################# def get_zscore_features(df_all, feature_names, out_file, REMOVE_OUTLIER=0, zscore_threshold=ZSCORE_OUTLIER_THRESHOLD): # if remove_outlier ==0 , just clip at threshold featureArray = df_all[feature_names].astype(float) featureArray.fillna(0,inplace=True) ### might introduce some bias normalized = zscore(featureArray) # normalized = featureArray # normalized[~np.isnan(featureArray)] = zscore(featureArray[~np.isnan(featureArray)]) num_outliers = np.count_nonzero(normalized < -zscore_threshold) + np.count_nonzero( normalized > zscore_threshold) print("Found %d |z score| > %f in zscore matrix :" % (num_outliers, zscore_threshold) ) df_all_modified = df_all df_outliers = pd.DataFrame() if num_outliers > 0: if not REMOVE_OUTLIER: # just clip normalized[normalized < -zscore_threshold] = -zscore_threshold normalized[normalized > zscore_threshold] = zscore_threshold # else: # outliers_l = np.nonzero(normalized < -zscore_threshold) # outliers_h = np.nonzero(normalized > zscore_threshold) # outlier_index = np.unique((np.append(outliers_l[0], outliers_h[0]))) # # # remove outlier rows # df_all_modified = df_all_modified.drop(df_all_modified.index[outlier_index]) # normalized = np.delete(normalized, outlier_index, 0) # # # re-zscoring and clipping # # m_featureArray = df_all_modified[feature_names].astype(float) # # normalized = zscore(m_featureArray) # # normalized[normalized < -zscore_threshold] = -zscore_threshold # # normalized[normalized > zscore_threshold] = zscore_threshold # # # print("Removed %d outlier neurons" % len(outlier_index)) # # df_outliers = df_all.iloc[outlier_index] df_z = pd.DataFrame(normalized) df_z.columns = feature_names df_z.index = df_all['swc_file_name'] if out_file: df_z.to_csv(out_file, index=True) print("save to " + out_file ) if (df_z.shape[0] != df_all_modified.shape[0]): print ("error: the sample size of the zscore and the original table does not match!") return df_z, df_all_modified, df_outliers ############################################################################################# def output_single_cluster_results(df_cluster, output_dir, output_prefix, snapshots_dir=None, swc_path = None): csv_file = output_dir + '/' + output_prefix + '.csv' df_cluster.to_csv(csv_file, index=False) ano_file = output_dir + '/' + output_prefix + '.ano' generateLinkerFileFromDF(df_cluster, ano_file, False, swc_path) # copy bmp vaa3d snapshots images over if (snapshots_dir): copySnapshots(df_cluster, snapshots_dir, output_dir + '/' + output_prefix) assemble_screenshots(output_dir + '/' + output_prefix, output_dir + '/' + output_prefix + '_assemble.png', 128) else: print "no bmp copying from:", snapshots_dir return def output_clusters(assign_ids, df_zscores, df_all, feature_names, output_dir, snapshots_dir=None): if not os.path.exists(output_dir): os.mkdir(output_dir) df_assign_id = pd.DataFrame() df_assign_id['specimen_name'] = df_all['specimen_name'] df_assign_id['cluster_id'] = assign_ids df_assign_id.to_csv(output_dir + "/cluster_id.csv", index=False) clusters = np.unique(assign_ids) num_cluster = len(clusters) cluster_list = [] # for dunn index calculation print("There are %d clusters in total" % num_cluster) df_cluster = pd.DataFrame() df_zscore_cluster = pd.DataFrame() for i in clusters: ids = np.nonzero(assign_ids == i)[0] # starting from 0 df_cluster = df_all.iloc[ids] print(" %d neurons in cluster %d" % (df_cluster.shape[0], i)) output_single_cluster_results(df_cluster, output_dir, "/cluster_" + str(i), snapshots_dir) df_zscore_cluster = df_zscores.iloc[ids] csv_file2 = output_dir + '/cluster_zscore_' + str(i) + '.csv' df_zscore_cluster.to_csv(csv_file2, index=False) cluster_list.append(df_zscore_cluster.values) ## pick the cluster specific feature and plot histogram cluster_specific_features(df_all, assign_ids, feature_names, output_dir+'/pvalues.csv') return cluster_list ####### ward hierachichal clustering ########### def ward_cluster(df_all, feature_names, max_cluster_num, output_dir, snapshots_dir= None, RemoveOutliers = 0, datasetType='ivscc'): print("\n\n\n *************** ward computation, max_cluster = %d *************:" % max_cluster_num) if not os.path.exists(output_dir): os.mkdir(output_dir) else: os.system("rm -r " + output_dir + '/*') #### similarity plots # df_simMatrix = distance_matrix(df_all, feature_names, output_dir + "/morph_features_similarity_matrix.csv", 1) # # visualize heatmap using ward on similarity matrix # out = heatmap_plot_distancematrix(df_simMatrix, df_all, output_dir, "Similarity") # linkage = out.dendrogram_row.calculated_linkage ##### zscores featuer plots df_zscores, df_all_outlier_removed, df_outliers = get_zscore_features(df_all, feature_names, output_dir + '/zscore.csv', RemoveOutliers) if (df_outliers.shape[0] > 0 ): output_single_cluster_results(df_outliers, output_dir, "outliers", snapshots_dir) if datasetType =='ivscc': linkage = heatmap_plot_zscore_ivscc(df_zscores, df_all_outlier_removed, output_dir, "feature zscores") if datasetType =='bbp': linkage = heatmap_plot_zscore_bbp(df_zscores, df_all_outlier_removed, output_dir, "feature zscores") assignments = hierarchy.fcluster(linkage, max_cluster_num, criterion="maxclust") #hierarchy.dendrogram(linkage) ## put assignments into ano files and csv files clusters_list = output_clusters(assignments, df_zscores, df_all_outlier_removed, feature_names, output_dir, snapshots_dir) dunn_index = dunn(clusters_list) print("dunn index is %f" % dunn_index) return linkage,df_zscores def silhouette_clusternumber(linkage,df_zscores,output_dir ="."): #Silhouette analysis for determining the number of clusters print("Silhouettee analysis:") scores=[] for n_clusters in range(2,30): assignments = hierarchy.fcluster(linkage, n_clusters, criterion="maxclust") silhouette_avg = silhouette_score(df_zscores, assignments) print("For n_clusters =", n_clusters,"The average silhouette_score is :", silhouette_avg) scores.append(silhouette_avg) # plot sihouettee and cut pl.figure() pl.plot(range(2,30),scores,"*-") pl.xlabel("cluster number") pl.ylabel("average sihouettee coefficient") pl.savefig(output_dir+'/sihouettee_clusternumber.pdf') #pl.show() pl.close() return def dunnindex_clusternumber(linkage,df_zscores, output_dir ="."): index_list=[] for n_clusters in range(2,30): assignments = hierarchy.fcluster(linkage, n_clusters, criterion="maxclust") df_assign_id = pd.DataFrame() df_assign_id['cluster_id'] = assignments clusters = np.unique(assignments) num_cluster = len(clusters) cluster_list = [] # for dunn index calculation df_cluster = pd.DataFrame() df_zscore_cluster = pd.DataFrame() for i in clusters: ids = np.nonzero(assignments == i)[0] # starting from 0 df_zscore_cluster = df_zscores.iloc[ids] cluster_list.append(df_zscore_cluster.values) dunn_index = dunn(cluster_list) index_list.append(dunn_index) pl.figure() pl.plot(range(2,30),index_list,"*-") pl.xlabel("cluster number") pl.ylabel("dunn index") pl.savefig(output_dir+'/dunnindex_clusternumber.pdf') #pl.show() return def affinity_propagation(df_all, feature_names, output_dir, snapshots_dir=None, RemoveOutliers=0): ###### Affinity Propogation ############## print("\n\n\n *************** affinity propogation computation ****************:") redundancy_removed_features_names = remove_correlated_features(df_all, feature_names, 0.95) print(" The %d features that are not closely correlated are %s" % ( len(redundancy_removed_features_names), redundancy_removed_features_names)) if not os.path.exists(output_dir): os.mkdir(output_dir) else: os.system("rm -r " + output_dir + '/*') # Compute Affinity Propagation df_zscores, df_all_outlier_removed, df_outliers = get_zscore_features(df_all, redundancy_removed_features_names, None, RemoveOutliers) if (df_outliers.shape[0] > 0 ): output_single_cluster_results(df_outliers, output_dir, "outliers", snapshots_dir) X = df_zscores.as_matrix() af = AffinityPropagation().fit(X) cluster_centers_indices = af.cluster_centers_indices_ labels = af.labels_ labels = labels + 1 # the default labels start from 0, to be consistent with ward, add 1 so that it starts from 1 clusters_list = output_clusters(labels, df_zscores, df_all_outlier_removed, redundancy_removed_features_names, output_dir, snapshots_dir) dunn_index = dunn(clusters_list) print("dunn index is %f" % dunn_index) return len(np.unique(labels)), dunn_index def run_ward_cluster(df_features, feature_names, num_clusters,output_dir,output_postfix): redundancy_removed_features_names = remove_correlated_features(df_features, feature_names, 0.95) print(" The %d features that are not closely correlated are %s" % ( len(redundancy_removed_features_names), redundancy_removed_features_names)) #num_clusters, dunn_index1 = affinity_propagation(merged, redundancy_removed_features_names, output_dir + '/ap' + postfix, swc_screenshot_folder, REMOVE_OUTLIERS) linkage, df_zscore = ward_cluster(df_features, redundancy_removed_features_names, num_clusters, output_dir + '/ward' + output_postfix) silhouette_clusternumber(linkage, df_zscore, output_dir + '/ward' + output_postfix) return redundancy_removed_features_names def main(): ###################################################################################################################### data_DIR = "/data/mat/xiaoxiaol/data/lims2/pw_aligned_1223" #default_all_feature_merged_file = data_DIR + '/keith_features_23dec.csv' #drop outliers, edit dendrite_type, creline #df_features = pd.read_csv(data_DIR +'/0107_new_features.csv') #df_features = df_features[df_features['QC status'] != "Outlier"] # #parse creline info from specimen_name #df_features.dropnas() # crelines=[] # swc_file_names=[] # for i in range(df_features.shape[0]): # sn=df_features['specimen_name'][i] # fn = df_features['specimen_name'][i].split('/')[-1] # cl=sn.split(';')[0] # crelines.append(cl) # swc_file_names.append(fn) # df_features['cre_line'] = pd.Series(crelines) # df_features['swc_file_name'] = pd.Series(swc_file_names) # df_features.to_csv(data_DIR+'/filtered_w_cre.csv') input_csv_file = data_DIR + '/0108/0108_features.csv' out_dir = data_DIR + '/0108/clustering_results/no_GMI' default_swc_screenshot_folder = data_DIR + "/figures/pw_aligned_bmps" ####################################################################################################################### swc_screenshot_folder = default_swc_screenshot_folder method = "all" SEL_FEATURE = "all" if not os.path.exists(out_dir): os.mkdir(out_dir) ######################################################## all_feature_file = input_csv_file ######################################################### meta_feature_names = np.array(['specimen_name','specimen_id','dendrite_type','cre_line','region_info','filename','swc_file_name']) basal_feature_names = np.array(['basal_average_bifurcation_angle_local','basal_average_bifurcation_angle_remote','basal_average_contraction','basal_average_fragmentation', 'basal_max_branch_order','basal_max_euclidean_distance','basal_max_path_distance', 'basal_nodes_over_branches','basal_number_of_bifurcations', 'basal_number_of_branches','basal_number_of_stems','basal_number_of_tips','basal_overall_depth','basal_overall_height', 'basal_overall_width','basal_total_length','bb_first_moment_x_basal','bb_first_moment_y_basal','bb_first_moment_z_basal', 'kg_soma_depth', 'basal_moment1','basal_moment10','basal_moment11','basal_moment12','basal_moment13','basal_moment2', 'basal_moment3','basal_moment4', 'basal_moment5','basal_moment6','basal_moment7','basal_moment8','basal_moment9']) #'basal_total_surface','basal_total_volume','basal_soma_surface','basal_number_of_nodes','basal_average_diameter', # 'basal_moment1','basal_moment10','basal_moment11','basal_moment12','basal_moment13','basal_moment14','basal_moment2','basal_moment3','basal_moment4', #'basal_moment5','basal_moment6','basal_moment7','basal_moment8','basal_moment9','basal_average_parent_daughter_ratio' apical_feature_names = np.array(['apical_average_bifurcation_angle_local','apical_average_bifurcation_angle_remote','apical_average_contraction', 'apical_average_fragmentation','apical_max_branch_order','apical_max_euclidean_distance', 'apical_max_path_distance', 'apical_nodes_over_branches','apical_number_of_bifurcations','apical_number_of_branches', 'apical_number_of_tips','apical_overall_depth','apical_overall_height','apical_overall_width','apical_total_length', 'kg_branch_mean_from_centroid_z_apical', 'kg_branch_stdev_from_centroid_z_apical', 'kg_centroid_over_farthest_branch_apical', 'kg_centroid_over_farthest_neurite_apical', 'kg_centroid_over_radial_dist_apical', 'kg_mean_over_centroid', 'kg_mean_over_farthest_branch_apical', 'kg_mean_over_farthest_neurite_apical', 'kg_mean_over_radial_dist_apical', 'kg_mean_over_stdev', 'kg_num_branches_over_radial_dist_apical', 'kg_num_outer_apical_branches', 'kg_outer_mean_from_center_z_apical', 'kg_outer_mean_over_stdev', 'kg_outer_stdev_from_center_z_apical', 'kg_peak_over_moment_z_apical', 'kg_radial_dist_over_moment_z_apical', 'kg_soma_depth']) #, 'apical_number_of_nodes' # ])#'apical_soma_surface', 'apical_total_surface','apical_total_volume','apical_average_diameter','apical_moment1','apical_moment10','apical_moment11','apical_moment12','apical_moment13','apical_moment14', # 'apical_moment2','apical_moment3','apical_moment4','apical_moment5','apical_moment6','apical_moment7','apical_moment8','apical_moment9','apical_average_parent_daughter_ratio','apical_number_of_stems?? always 1', bbp_feature_names = np.array(['bb_first_moment_apical','bb_first_moment_basal','bb_first_moment_dendrite','bb_first_moment_x_apical','bb_first_moment_x_basal', 'bb_first_moment_x_dendrite','bb_first_moment_y_apical','bb_first_moment_y_basal','bb_first_moment_y_dendrite','bb_first_moment_z_apical', 'bb_first_moment_z_basal','bb_first_moment_z_dendrite','bb_max_branch_order_apical','bb_max_branch_order_basal','bb_max_branch_order_dendrite', 'bb_max_path_length_apical','bb_max_path_length_basal','bb_max_path_length_dendrite','bb_max_radial_distance_apical','bb_max_radial_distance_basal', 'bb_max_radial_distance_dendrite','bb_mean_trunk_diameter_apical','bb_mean_trunk_diameter_basal','bb_mean_trunk_diameter_dendrite', 'bb_number_branches_apical','bb_number_branches_basal','bb_number_branches_dendrite','bb_number_neurites_apical','bb_number_neurites_basal', 'bb_number_neurites_dendrite','bb_second_moment_apical','bb_second_moment_basal','bb_second_moment_dendrite','bb_second_moment_x_apical', 'bb_second_moment_x_basal','bb_second_moment_x_dendrite','bb_second_moment_y_apical','bb_second_moment_y_basal','bb_second_moment_y_dendrite', 'bb_second_moment_z_apical','bb_second_moment_z_basal','bb_second_moment_z_dendrite','bb_total_length_apical','bb_total_length_basal', 'bb_total_length_dendrite']) #'bb_total_surface_area_apical','bb_total_volume_basal','bb_total_volume_apical','bb_total_volume_dendrite','bb_total_surface_area_basal','bb_total_surface_area_dendrite' #selected_features = ['max_euclidean_distance', 'num_stems', 'num_bifurcations', 'average_contraction', #'parent_daughter_ratio'] #tmp = np.append(meta_feature_names, basal_feature_names) all_dendritic_feature_names = np.append(basal_feature_names, apical_feature_names) #bbp_feature_names spiny_feature_names = apical_feature_names aspiny_feature_names = basal_feature_names df_features = pd.read_csv(all_feature_file) print df_features.columns df_features[all_dendritic_feature_names]= df_features[all_dendritic_feature_names].astype(float) print "There are %d neurons in this dataset" % df_features.shape[0] print "Dendrite types: ", np.unique(df_features['dendrite_type']) # df_features_all = df_features[np.append(meta_feature_names,all_dendritic_feature_names)] # df_features_all.to_csv(data_DIR+'/0108/all_dendrite_features.csv') df_groups = df_features.groupby(['dendrite_type']) df_spiny = df_groups.get_group('spiny') # df_w_spiny = df_spiny[np.append(meta_feature_names,spiny_feature_names)] # df_w_spiny.to_csv(data_DIR +'/0108/spiny_features.csv', index=False) df_aspiny = pd.concat([df_groups.get_group('aspiny'),df_groups.get_group('sparsely spiny')],axis=0) # df_w_aspiny = df_aspiny[np.append(meta_feature_names,aspiny_feature_names)] # df_w_aspiny.to_csv(data_DIR +'/0108/aspiny_features.csv', index=False) print "There are %d neurons are aspiny " % df_aspiny.shape[0] print "There are %d neurons are spiny\n\n" % df_spiny.shape[0] feature_names = all_dendritic_feature_names method = "ward" REMOVE_OUTLIERS = 0 postfix = "_" + SEL_FEATURE postfix += "_ol_clipped" #run_ward_cluster(df_features, feature_names, num_clusters,output_postfix): # num_clusters, dunn_index1 = affinity_propagation(df_aspiny, aspiny_feature_names, # out_dir + '/ap_aspiny' + postfix, # None, REMOVE_OUTLIERS) # print "spiny ap:" # print num_clusters # # num_clusters, dunn_index1 = affinity_propagation(df_spiny, spiny_feature_names, # out_dir + '/ap_spiny' + postfix, # None, REMOVE_OUTLIERS) # print "aspiny ap:" # print num_clusters # exit() redundancy_removed_features = run_ward_cluster(df_aspiny, aspiny_feature_names, num_clusters = 6 ,output_dir = out_dir,output_postfix= '_aspiny'+postfix) df_w_aspiny = df_aspiny[np.append(meta_feature_names,redundancy_removed_features)] df_w_aspiny.to_csv(data_DIR +'/0108/aspiny_selected_features.csv', index=False) # # # df_spiny.fillna(0,inplace=True) # redundancy_removed_features = run_ward_cluster(df_spiny, spiny_feature_names, num_clusters = 9 ,output_dir = out_dir, output_postfix='_spiny'+ postfix) # df_w_spiny = df_spiny[np.append(meta_feature_names,redundancy_removed_features)] # df_w_spiny.to_csv(data_DIR +'/0108/spiny_selected_features.csv', index=False) # if __name__ == "__main__": main()
XiaoxiaoLiu/morphology_analysis
IVSCC/morph_clustering_on_bbp_features_old_example.py
Python
gpl-3.0
37,767
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /*************************************************************************** * drumkitparser.cc * * Tue Jul 22 16:24:59 CEST 2008 * Copyright 2008 Bent Bisballe Nyeng * deva@aasimon.org ****************************************************************************/ /* * This file is part of DrumGizmo. * * DrumGizmo 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. * * DrumGizmo 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 DrumGizmo; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include "drumkitparser.h" #include <string.h> #include <stdio.h> #include <hugin.hpp> #include "instrumentparser.h" #include "path.h" DrumKitParser::DrumKitParser(const std::string &kitfile, DrumKit &k) : kit(k) { // instr = NULL; path = getPath(kitfile); fd = fopen(kitfile.c_str(), "r"); // DEBUG(kitparser, "Parsing drumkit in %s\n", kitfile.c_str()); if(!fd) return; kit._file = kitfile; } DrumKitParser::~DrumKitParser() { if(fd) fclose(fd); } void DrumKitParser::startTag(std::string name, std::map<std::string, std::string> attr) { if(name == "drumkit") { if(attr.find("name") != attr.end()) kit._name = attr["name"]; if(attr.find("samplerate") != attr.end()) { kit._samplerate = atoi(attr["samplerate"].c_str()); } else { // If 'samplerate' attribute is missing, assume 44k1Hz // TODO: Ask instrument what samplerate is in the audiofiles... kit._samplerate = 44100; } if(attr.find("description") != attr.end()) kit._description = attr["description"]; if(attr.find("version") != attr.end()) { try { kit._version = VersionStr(attr["version"]); } catch(const char *err) { ERR(kitparser, "Error parsing version number: %s, using 1.0\n", err); kit._version = VersionStr(1,0,0); } } else { WARN(kitparser, "Missing version number, assuming 1.0\n"); kit._version = VersionStr(1,0,0); } } if(name == "channels") {} if(name == "channel") { if(attr.find("name") == attr.end()) { DEBUG(kitparser, "Missing channel name.\n"); return; } Channel c(attr["name"]); c.num = kit.channels.size(); kit.channels.push_back(c); } if(name == "instruments") { } if(name == "instrument") { if(attr.find("name") == attr.end()) { DEBUG(kitparser, "Missing name in instrument tag.\n"); return; } if(attr.find("file") == attr.end()) { DEBUG(kitparser, "Missing file in instrument tag.\n"); return; } instr_name = attr["name"]; instr_file = attr["file"]; if(attr.find("group") != attr.end()) instr_group = attr["group"]; else instr_group = ""; } if(name == "channelmap") { if(attr.find("in") == attr.end()) { DEBUG(kitparser, "Missing 'in' in channelmap tag.\n"); return; } if(attr.find("out") == attr.end()) { DEBUG(kitparser, "Missing 'out' in channelmap tag.\n"); return; } channelmap[attr["in"]] = attr["out"]; } } void DrumKitParser::endTag(std::string name) { if(name == "instrument") { Instrument *i = new Instrument(); i->setGroup(instr_group); // Instrument &i = kit.instruments[kit.instruments.size() - 1]; InstrumentParser parser(path + "/" + instr_file, *i); parser.parse(); kit.instruments.push_back(i); // Assign kit channel numbers to instruments channels. std::vector<InstrumentChannel*>::iterator ic = parser.channellist.begin(); while(ic != parser.channellist.end()) { InstrumentChannel *c = *ic; std::string cname = c->name; if(channelmap.find(cname) != channelmap.end()) cname = channelmap[cname]; for(size_t cnt = 0; cnt < kit.channels.size(); cnt++) { if(kit.channels[cnt].name == cname) c->num = kit.channels[cnt].num; } if(c->num == NO_CHANNEL) { DEBUG(kitparser, "Missing channel '%s' in instrument '%s'\n", c->name.c_str(), i->name().c_str()); } else { /* DEBUG(kitparser, "Assigned channel '%s' to number %d in instrument '%s'\n", c->name.c_str(), c->num, i.name().c_str()); */ } ic++; } channelmap.clear(); } } int DrumKitParser::readData(char *data, size_t size) { if(!fd) return -1; return fread(data, 1, size, fd); } #ifdef TEST_DRUMKITPARSER //deps: drumkit.cc saxparser.cc instrument.cc sample.cc audiofile.cc channel.cc //cflags: $(EXPAT_CFLAGS) $(SNDFILE_CFLAGS) //libs: $(EXPAT_LIBS) $(SNDFILE_LIBS) #include "test.h" const char xml[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<drumkit name=\"The Aasimonster\"\n" " description=\"A large deathmetal drumkit\">\n" " <channels>\n" " <channel name=\"Alesis\"/>\n" " <channel name=\"Kick-L\"/>\n" " <channel name=\"Kick-R\"/>\n" " <channel name=\"SnareTop\"/>\n" " <channel name=\"SnareTrigger\"/>\n" " <channel name=\"SnareBottom\"/>\n" " <channel name=\"OH-L\"/>\n" " <channel name=\"OH-R\"/>\n" " <channel name=\"Hihat\"/>\n" " <channel name=\"Ride\"/>\n" " <channel name=\"Tom1\"/>\n" " <channel name=\"Tom2\"/>\n" " <channel name=\"Tom3\"/>\n" " <channel name=\"Tom4\"/>\n" " <channel name=\"Amb-R\"/>\n" " <channel name=\"Amb-L\"/>\n" " </channels>\n" " <instruments>\n" " <instrument name=\"Ride\" file=\"ride.xml\">\n" " <channelmap in=\"Alesis\" out=\"Alesis\" gain=\"1.5\"/>\n" " <channelmap in=\"Kick-L\" out=\"Kick-L\" gain=\"0.5\"/>\n" " <channelmap in=\"Kick-R\" out=\"Kick-R\"/>\n" " <channelmap in=\"SnareTop\" out=\"SnareTop\" gain=\"0.5\"/>\n" " <channelmap in=\"SnareTrigger\" out=\"SnareTrigger\" gain=\"0.5\"/>\n" " <channelmap in=\"SnareBottom\" out=\"SnareBottom\" gain=\"0.5\"/>\n" " <channelmap in=\"OH-L\" out=\"OH-L\"/>\n" " <channelmap in=\"OH-R\" out=\"OH-R\"/>\n" " <channelmap in=\"Hihat\" out=\"Hihat\" gain=\"0.5\"/>\n" " <channelmap in=\"Ride\" out=\"Ride\" gain=\"0.5\"/>\n" " <channelmap in=\"Tom1\" out=\"Tom1\" gain=\"0.5\"/>\n" " <channelmap in=\"Tom2\" out=\"Tom2\" gain=\"0.5\"/>\n" " <channelmap in=\"Tom3\" out=\"Tom3\" gain=\"0.5\"/>\n" " <channelmap in=\"Tom4\" out=\"Tom4\" gain=\"0.5\"/>\n" " <channelmap in=\"Amb-R\" out=\"Amb-R\"/>\n" " <channelmap in=\"Amb-L\" out=\"Amb-L\"/>\n" " </instrument>\n" " <instrument name=\"Snare\" file=\"snare.xml\">\n" " <channelmap in=\"Alesis\" out=\"Alesis\" gain=\"1.5\"/>\n" " <channelmap in=\"Kick-L\" out=\"Kick-L\" gain=\"0.5\"/>\n" " <channelmap in=\"Kick-R\" out=\"Kick-R\"/>\n" " <channelmap in=\"SnareTop\" out=\"SnareTop\" gain=\"0.5\"/>\n" " <channelmap in=\"SnareTrigger\" out=\"SnareTrigger\" gain=\"0.5\"/>\n" " <channelmap in=\"SnareBottom\" out=\"SnareBottom\" gain=\"0.5\"/>\n" " <channelmap in=\"OH-L\" out=\"OH-L\"/>\n" " <channelmap in=\"OH-R\" out=\"OH-R\"/>\n" " <channelmap in=\"Hihat\" out=\"Hihat\" gain=\"0.5\"/>\n" " <channelmap in=\"Ride\" out=\"Ride\" gain=\"0.5\"/>\n" " <channelmap in=\"Tom1\" out=\"Tom1\" gain=\"0.5\"/>\n" " <channelmap in=\"Tom2\" out=\"Tom2\" gain=\"0.5\"/>\n" " <channelmap in=\"Tom3\" out=\"Tom3\" gain=\"0.5\"/>\n" " <channelmap in=\"Tom4\" out=\"Tom4\" gain=\"0.5\"/>\n" " <channelmap in=\"Amb-R\" out=\"Amb-R\"/>\n" " <channelmap in=\"Amb-L\" out=\"Amb-L\"/>\n" " </instrument>\n" " </instruments>\n" "</drumkit>\n" ; #define FNAME "/tmp/drumkittest.xml" TEST_BEGIN; FILE *fp = fopen(FNAME, "w"); fprintf(fp, "%s", xml); fclose(fp); DrumKit kit; DrumKitParser p(FNAME, kit); TEST_EQUAL_INT(p.parse(), 0, "Parsing went well?"); TEST_EQUAL_STR(kit.name(), "The Aasimonster", "Compare name"); TEST_EQUAL_INT(kit.instruments.size(), 2, "How many instruments?"); unlink(FNAME); TEST_END; #endif/*TEST_DRUMKITPARSER*/
joulez/drumgizmo
src/drumkitparser.cc
C++
gpl-3.0
8,523
/******************************************************************************* * Signavio Core Components * Copyright (C) 2012 Signavio GmbH * * 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 de.hpi.bpmn2_0.factory.node; import org.oryxeditor.server.diagram.generic.GenericShape; import de.hpi.bpmn2_0.annotations.StencilId; import de.hpi.bpmn2_0.exceptions.BpmnConverterException; import de.hpi.bpmn2_0.factory.AbstractShapeFactory; import de.hpi.bpmn2_0.model.BaseElement; import de.hpi.bpmn2_0.model.data_object.DataState; import de.hpi.bpmn2_0.model.data_object.DataStore; import de.hpi.bpmn2_0.model.data_object.DataStoreReference; import de.hpi.diagram.SignavioUUID; /** * Factory for DataStores * * @author Philipp Giese * @author Sven Wagner-Boysen * */ @StencilId("DataStore") public class DataStoreFactory extends AbstractShapeFactory { /* (non-Javadoc) * @see de.hpi.bpmn2_0.factory.AbstractBpmnFactory#createProcessElement(org.oryxeditor.server.diagram.Shape) */ // @Override protected BaseElement createProcessElement(GenericShape shape) throws BpmnConverterException { DataStoreReference dataStoreRef = new DataStoreReference(); this.setCommonAttributes(dataStoreRef, shape); dataStoreRef.setDataStoreRef(new DataStore()); this.setDataStoreRefAttributes(dataStoreRef, shape); return dataStoreRef; } /** * Sets the attributes related to a data store element. * * @param dataStoreRef * The @link {@link DataStoreReference}. * @param shape * The data store {@link GenericShape} */ private void setDataStoreRefAttributes(DataStoreReference dataStoreRef, GenericShape shape) { DataStore dataStore = dataStoreRef.getDataStoreRef(); String dataStateName = shape.getProperty("state"); /* Set attributes of the global data store */ if(dataStore != null) { dataStore.setId(SignavioUUID.generate()); dataStore.setName(shape.getProperty("name")); if(shape.getProperty("capacity") != null && !(shape.getProperty("capacity").length() == 0)) dataStore.setCapacity(Integer.valueOf(shape.getProperty("capacity")).intValue()); /* Set isUnlimited attribute */ String isUnlimited = shape.getProperty("isunlimited"); if(isUnlimited != null && isUnlimited.equalsIgnoreCase("true")) dataStore.setUnlimited(true); else dataStore.setUnlimited(false); /* Define DataState element */ if(dataStateName != null && !(dataStateName.length() == 0)) { DataState dataState = new DataState(dataStateName); dataStore.setDataState(dataState); } } /* Set attributes of the data store reference */ dataStoreRef.setName(shape.getProperty("name")); dataStoreRef.setId(shape.getResourceId()); /* Define DataState element */ if(dataStateName != null && !(dataStateName.length() == 0)) { DataState dataState = new DataState(dataStateName); dataStoreRef.setDataState(dataState); } } }
KarnYong/BPaaS-modeling
platform extensions/bpmn20xmlbasic/src/de/hpi/bpmn2_0/factory/node/DataStoreFactory.java
Java
gpl-3.0
3,603
from xboxdrv_parser import Controller from time import sleep import argparse import os import sys sys.path.append(os.path.abspath("../../..")) from util.communication.grapevine import Communicator from robosub_settings import settings def main (args): com = Communicator (args.module_name) controller = Controller (["X1", "Y1", "X2", "Y2", "R2", "L2"], ["right/left", "forward/backward", "yaw", "pitch", "up", "down"], (0, 255), (-1, 1)) while True: control_packet = controller.get_values () try: outgoing_packet = {"right/left": 0.0, "forward/backward": 0.0, "yaw": 0.0, "pitch": 0.0, "up/down": 0.0, "roll": 0.0} # Further parse controller values here # Controller's sticks Y axis are switched control_packet["forward/backward"] = -control_packet["forward/backward"] control_packet["pitch"] = -control_packet["pitch"] # Up and Down are not -1 to 1. Just 0 - 1 control_packet["up"] = controller.map_range(control_packet["up"], -1, 1, 0, 1) control_packet["down"] = controller.map_range(control_packet["down"], -1, 1, 0, -1) # Transferring to outgoing packet outgoing_packet["forward/backward"] = control_packet["forward/backward"] outgoing_packet["right/left"] = control_packet["right/left"] outgoing_packet["up/down"] = control_packet["up"] + control_packet["down"] outgoing_packet["yaw"] = control_packet["yaw"] outgoing_packet["pitch"] = control_packet["pitch"] #outgoing_packet["roll"] = control_packet["roll"] outgoing_packet["roll"] = 0.0 # Controller sticks are not centered very well. # TODO: Find a better way to do this (short of getting a new controller) for key in outgoing_packet.keys (): if abs (outgoing_packet[key]) < .10: outgoing_packet[key] = 0.0 print outgoing_packet Fuzzy_Sets = {"Fuzzy_Sets": outgoing_packet} com.publish_message (Fuzzy_Sets) except KeyError as i: pass sleep (args.epoch) def commandline(): parser = argparse.ArgumentParser(description='Mock module.') parser.add_argument('-e', '--epoch', type=float, default=0.1, help='Sleep time per cycle.') parser.add_argument('-m', '--module_name', type=str, default='movement/fuzzification', help='Module name.') return parser.parse_args() if __name__ == '__main__': args = commandline() main(args)
pi19404/robosub-1
src/movement/fuzzification/test/xbox_controller.py
Python
gpl-3.0
2,612
package com.bonepeople.android.sdcardcleaner.basic; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Message; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.bonepeople.android.sdcardcleaner.R; import java.util.LinkedList; /** * 集成对Handler控制的基类 * <p> * Created by bonepeople on 2017/12/25. */ public abstract class BaseAppCompatActivity extends AppCompatActivity { private LinkedList<BaseHandler> handlers = null; protected final BaseHandler createHandler() { if (handlers == null) handlers = new LinkedList<>(); BaseHandler handler = new BaseHandler(this); handlers.add(handler); return handler; } protected void handleMessage(Message msg) { } @Override public final void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); onRequestPermission(requestCode, grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED); } /** * 权限申请的回调函数 * * @param requestCode 权限申请的请求ID * @param granted 权限请求的结果 true-获得权限,false-拒绝权限 */ protected void onRequestPermission(int requestCode, boolean granted) { } /** * 检查权限是否已被授权 * * @param permission android.Manifest.permission * @return boolean 是否拥有对应权限 */ protected boolean checkPermission(@NonNull String permission) { return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED; } /** * 申请指定权限 * <p> * 申请某一权限,如需提示用户会创建AlertDialog对用户进行提示,权限申请的结果需要重写{@link #onRequestPermission(int, boolean)}接收 * </p> * * @param permission android.Manifest.permission * @param rationale 提示信息 */ protected void requestPermission(@NonNull final String permission, @Nullable String rationale, final int requestCode) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(rationale); builder.setPositiveButton(R.string.caption_button_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(BaseAppCompatActivity.this, new String[]{permission}, requestCode); } }); builder.setNegativeButton(R.string.caption_button_negative, null); builder.create().show(); } else ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode); } @Override protected void onDestroy() { if (handlers != null) { for (BaseHandler handler : handlers) { handler.destroy(); } handlers.clear(); handlers = null; } super.onDestroy(); } }
bonepeople/SDCardCleaner
app/src/main/java/com/bonepeople/android/sdcardcleaner/basic/BaseAppCompatActivity.java
Java
gpl-3.0
3,515
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- // // Simple test for the AP_AHRS interface // #include <AP_AHRS/AP_AHRS.h> #include <AP_HAL/AP_HAL.h> const AP_HAL::HAL& hal = AP_HAL::get_HAL(); // INS and Baro declaration AP_InertialSensor ins; Compass compass; AP_GPS gps; AP_Baro baro; AP_SerialManager serial_manager; // choose which AHRS system to use AP_AHRS_DCM ahrs(ins, baro, gps); #define HIGH 1 #define LOW 0 void setup(void) { ins.init(AP_InertialSensor::RATE_100HZ); ahrs.init(); serial_manager.init(); if( compass.init() ) { hal.console->printf("Enabling compass\n"); ahrs.set_compass(&compass); } else { hal.console->printf("No compass detected\n"); } gps.init(NULL, serial_manager); } void loop(void) { static uint16_t counter; static uint32_t last_t, last_print, last_compass; uint32_t now = AP_HAL::micros(); float heading = 0; if (last_t == 0) { last_t = now; return; } last_t = now; if (now - last_compass > 100*1000UL && compass.read()) { heading = compass.calculate_heading(ahrs.get_dcm_matrix()); // read compass at 10Hz last_compass = now; #if WITH_GPS g_gps->update(); #endif } ahrs.update(); counter++; if (now - last_print >= 100000 /* 100ms : 10hz */) { Vector3f drift = ahrs.get_gyro_drift(); hal.console->printf( "r:%4.1f p:%4.1f y:%4.1f " "drift=(%5.1f %5.1f %5.1f) hdg=%.1f rate=%.1f\n", ToDeg(ahrs.roll), ToDeg(ahrs.pitch), ToDeg(ahrs.yaw), ToDeg(drift.x), ToDeg(drift.y), ToDeg(drift.z), compass.use_for_yaw() ? ToDeg(heading) : 0.0f, (1.0e6f*counter)/(now-last_print)); last_print = now; counter = 0; } } AP_HAL_MAIN();
kwikius/ardupilot
libraries/AP_AHRS/examples/AHRS_Test/AHRS_Test.cpp
C++
gpl-3.0
2,026
/* * Copyright (C) 2010---2013 星星(wuweixing)<349446658@qq.com> * * This file is part of Wabacus * * Wabacus 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/>. */ package com.wabacus.system.datatype; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.wabacus.config.database.type.AbsDatabaseType; public class IntType extends AbsNumberType { private final static Log log=LogFactory.getLog(IntType.class); private final static Map<String,AbsNumberType> mIntTypeObjects=new HashMap<String,AbsNumberType>(); public Object getColumnValue(ResultSet rs,String column,AbsDatabaseType dbtype) throws SQLException { return Integer.valueOf(rs.getInt(column)); } public Object getColumnValue(ResultSet rs,int iindex,AbsDatabaseType dbtype) throws SQLException { return Integer.valueOf(rs.getInt(iindex)); } public void setPreparedStatementValue(int iindex,String value,PreparedStatement pstmt, AbsDatabaseType dbtype) throws SQLException { log.debug("setInt("+iindex+","+value+")"); Object objTmp=label2value(value); if(objTmp==null) { pstmt.setObject(iindex,null,java.sql.Types.INTEGER); }else { pstmt.setInt(iindex,(Integer)objTmp); } } public Class getJavaTypeClass() { return Integer.class; } public Object label2value(String label) { if(label==null||label.trim().equals("")) return null; if(this.numberformat!=null&&!this.numberformat.trim().equals("")) { return Integer.valueOf(this.getNumber(label.trim()).intValue()); }else { int idxdot=label.indexOf("."); if(idxdot==0) { label="0"; }else if(idxdot>0) { label=label.substring(0,idxdot).trim(); if(label.equals("")) label="0"; } return Integer.valueOf(label.trim()); } } public String value2label(Object value) { if(value==null) return ""; if(!(value instanceof Integer)) return String.valueOf(value); if(this.numberformat!=null&&!this.numberformat.trim().equals("")) { DecimalFormat df=new DecimalFormat(this.numberformat); return df.format((Integer)value); }else { return String.valueOf(value); } } protected Map<String,AbsNumberType> getAllMNumberTypeObjects() { return mIntTypeObjects; } }
foxerfly/Wabacus4.1src
src/com/wabacus/system/datatype/IntType.java
Java
gpl-3.0
3,450
package com.piron1991.builder_tools.reference; public class Reference { public static final String MOD_ID = "builder_tools"; public static final String VERSION = "0.1"; public static final String MOD_NAME = "Builder tools"; public static final String CPROXY = "com.piron1991.builder_tools.proxy.clientProxy"; public static final String SPROXY = "com.piron1991.builder_tools.proxy.serverProxy"; public static final String SIZE_CATEGORY="Ranges of block placings for tools: "; public static final String RECIPE_CATEGORY="Recipes for tools: "; }
Piron1991/Builder_tools
src/main/java/com/piron1991/builder_tools/reference/Reference.java
Java
gpl-3.0
575
<?php /** * Classes for dealing with devices * * PHP Version 5 * * <pre> * HUGnetLib is a library of HUGnet code * Copyright (C) 2014 Hunt Utilities Group, LLC * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * </pre> * * @category Libraries * @package HUGnetLib * @subpackage Sensors * @author Scott Price <prices@hugllc.com> * @copyright 2014 Hunt Utilities Group, LLC * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link http://dev.hugllc.com/index.php/Project:HUGnetLib * */ /** This is the HUGnet namespace */ namespace HUGnet\devices\inputTable\drivers\virtual; /** This keeps this file from being included unless HUGnetSystem.php is included */ defined('_HUGNET') or die('HUGnetSystem not found'); /** This is my base class */ require_once dirname(__FILE__)."/../../DriverVirtual.php"; /** * Driver for reading voltage based pressure sensors * * @category Libraries * @package HUGnetLib * @subpackage Sensors * @author Scott Price <prices@hugllc.com> * @copyright 2014 Hunt Utilities Group, LLC * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @version Release: 0.14.3 * @link http://dev.hugllc.com/index.php/Project:HUGnetLib * @since 0.9.8 * * @SuppressWarnings(PHPMD.ShortVariable) */ class CloneVirtual extends \HUGnet\devices\inputTable\DriverVirtual implements \HUGnet\devices\inputTable\DriverInterface { /** * This is the sensor we are cloning */ private $_clone = null; /** * This is where the data for the driver is stored. This array must be * put into all derivative classes, even if it is empty. */ protected $params = array( "shortName" => "CloneVirtual", "virtual" => true, // This says if we are a virtual sensor "extraText" => array( "Device ID", "Input" ), // Integer is the size of the field needed to edit // Array is the values that the extra can take // Null nothing "extraValues" => array(8, 3), "extraDefault" => array("", ""), "extraDesc" => array( "The DeviceID of the board (in hexidecimal)", "The INPUT to clone. Zero based." ), "extraNames" => array( "deviceid" => 0, "datachan" => 1, ), "requires" => array(), // We don't require anything. ); /** * This is the routine that gets the sensor that we are cloning * * @return object The object for the sensor we are cloning */ private function _clone() { if (!is_object($this->_clone)) { $did = hexdec($this->getExtra(0)); $sen = $this->getExtra(1); if ($did == 0) { $sensor = $this->input(); $this->_clone = parent::factory("SDEFAULT", $sensor); } else { $sensor = $this->input()->system()->device($did)->input($sen); // Set our location the same as the other sensors and lock it there if ($sensor->get("driver") == "EmptySensor") { $loc = sprintf("(Input %06X.%d does not exist)", $did, $sen); } else { $loc = $sensor->get("location"); if (empty($loc)) { $loc = "(No Input Label)"; } } $this->params["location"] = $loc; $this->input()->set("location", $loc); // Create our clone. $this->_clone = parent::factory( $sensor->get("driver"), $sensor ); } } return $this->_clone; } /** * Returns all of the parameters and defaults in an array * * @return array of data from the sensor * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function toArray() { return array_merge($this->_clone()->toArray(), $this->params); } /** * Gets an item * * @param string $name The name of the property to get * * @return null */ public function get($name) { $value = parent::get($name); if (isset($this->params[$name]) || is_null($value)) { return $value; } else { return $this->_clone()->get($name); } } /** * This builds the class from a setup string * * @return Array of channel information */ public function channels() { $ret = $this->_clone()->channels(); if (empty($ret)) { $input = $this->getExtra(0).".".$this->getExtra(1); $ret = array( array( "units" => "Unknown", "unitType" => "Unknown", "dataType" => \HUGnet\devices\datachan\Driver::TYPE_IGNORE, "index" => 0, "error" => "Input Not Found", ) ); } else { foreach (array_keys((array)$ret) as $key) { $ret[$key]["epChannel"] = false; } } return $ret; } /** * Gets the direction from a direction sensor made out of a POT. * * @param string &$hist The history object or array * @param int $chan The channel this input starts at * @param float $deltaT The time delta in seconds between this record * @param array &$prev The previous reading * @param array &$data The data from the other sensors that were crunched * * @return float The direction in degrees * * @SuppressWarnings(PHPMD.ShortVariable) */ public function decodeData( &$hist, $chan, $deltaT = 0, &$prev = null, &$data = array() ) { $ret = $this->channels(); $oid = $this->_clone()->input()->channelStart(); foreach (array_keys((array)$ret) as $key) { $sen = $oid + $key; if (is_object($hist)) { $ret[$key]["value"] = $hist->get("Data".$sen); } else if (is_array($hist)) { $ret[$key]["value"] = $hist["Data".$sen]; } else { $ret[$key]["value"] = null; } $ret[$key]["raw"] = null; } return $ret; } } ?>
hugllc/HUGnetLib
src/php/devices/inputTable/drivers/virtual/CloneVirtual.php
PHP
gpl-3.0
7,072
<?php /** * @package Arastta eCommerce * @copyright 2015-2018 Arastta Association. All rights reserved. * @copyright See CREDITS.txt for credits and other copyright notices. * @license GNU GPL version 3; see LICENSE.txt * @link https://arastta.org */ class ModelSettingApi extends Model { public function login($username, $password) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "api WHERE username = '" . $this->db->escape($username) . "' AND password = '" . $this->db->escape($password) . "'"); return $query->row; } }
arastta/arastta
catalog/model/setting/api.php
PHP
gpl-3.0
585
<?php require_once(__DIR__.'/../../../lib/common.php'); // Here are the individual SQL queries for each phase for clarity and // below it is a mash-up of them for effectiveness // // SELECT mac FROM visit WHERE ip=:ip ORDER BY leave DESC LIMIT 1; // SELECT id,changed FROM user_mac WHERE mac=:mac AND changed<:leave ORDER BY changed DESC LIMIT 1; // SELECT nick FROM user WHERE id=:id // Get person info by querying by latest IP $get_user = $db->prepare(" SELECT v.mac, hostname, nick, changed FROM visit v LEFT JOIN user_mac m ON (SELECT rowid FROM user_mac WHERE mac=v.mac AND changed<v.leave ORDER BY changed DESC LIMIT 1 )=m.rowid LEFT JOIN user u ON m.id=u.id WHERE ip=? ORDER BY leave DESC LIMIT 1 "); // Insert device by UID. This can be used for deleting as well when :id is NULL $insert_by_uid = $db->prepare(" INSERT INTO user_mac (id, mac, changed) SELECT :id, mac, :now FROM visit WHERE ip=:ip ORDER BY leave DESC LIMIT 1 "); $insert_by_uid->bindValue('now', time()-$merge_window_sec); // Find user ID by nick $find_uid = $db->prepare(" SELECT id FROM user WHERE nick=? "); // Insert user ID if possible $insert_user = $db->prepare(" INSERT INTO user (nick) VALUES (?) "); $ip = $_SERVER['REMOTE_ADDR']; $outerror = [ "error" => "You are outside the lab network ($ip)", "errorcode" => "OUT" ]; $nickmissing = [ "error" => "You must specify your nickname as parameter 'nick'", "errorcode" => "EMPTY" ]; switch ($_SERVER['REQUEST_METHOD']) { case 'GET': // Allow IP queries for everybody if (array_key_exists('ip', $_GET)) { $o = db_execute($get_user, [$_GET['ip']])->fetchArray(SQLITE3_ASSOC) ?: $outerror; unset($o['mac']); unset($o['changed']); } else { $o = db_execute($get_user, [$ip])->fetchArray(SQLITE3_ASSOC) ?: $outerror; } break; case 'DELETE': db_execute($insert_by_uid, [ 'id' => NULL, 'ip' => $ip ]); $o = $db->changes() === 1 ? ["success" => TRUE] : $outerror; break; case 'PUT': if (!array_key_exists('nick', $_GET) || $_GET['nick'] === '') { $o = $nickmissing; break; } $db->exec('BEGIN'); $row = db_execute($find_uid, [$_GET['nick']])->fetchArray(SQLITE3_ASSOC); if ($row === FALSE) { db_execute($insert_user, [$_GET['nick']]); $uid = $db->lastInsertRowid(); } else { $uid = $row['id']; } // We know uid by now, let's insert db_execute($insert_by_uid, [ 'id' => $uid, 'ip' => $ip ]); if ($db->changes() === 1) { $o = ["success" => TRUE]; $db->exec('END'); } else { $o = $outerror; // Do not allow trolling outside the lab network $db->exec('ROLLBACK'); } break; default: $o = ["error" => "Unsupported method"]; } header('Content-Type: application/json; charset=utf-8'); print(json_encode($o)."\n");
HacklabJKL/visitors
dist/api/v1/nick.php
PHP
gpl-3.0
3,047
<?php $username = ""; $errors = array(); if ($_SERVER["REQUEST_METHOD"] == "POST") { if (!isset($_POST["username"]) || !trim($_POST["username"])) { $errors["password"] = "Nom d'utilisateur ou mot de passe incorrecte."; } else { $username = $_POST["username"]; } if (empty($errors)) { $password = isset($_POST["password"])?$_POST["password"]:""; $auth->setUsername($username) ->setPassword(sha1($password)); if ($auth->authenticate()) { if ($module == "default" && $action == "login") { $redirect = "./"; } else { $redirect = $_SERVER["REQUEST_URI"]; } header("LOCATION: ".$redirect); exit; } $errors["password"] = "Nom d'utilisateur ou mot de passe incorrecte."; } }
C-Duv/LBCAlerte
app/default/scripts/login.php
PHP
gpl-3.0
846
#include "underlying_type.hpp" TC_UNDERLYING_TYPE aUNDERLYING_TYPE; void TC_UNDERLYING_TYPE::finish_type (tree t) { cerr << "finish_type: UNDERLYING_TYPE" << t << endl; }; void TC_UNDERLYING_TYPE::finish_decl (tree t) { cerr << "finish_decl: UNDERLYING_TYPE" << t << endl; }; void TC_UNDERLYING_TYPE::finish_unit (tree t) { cerr << "finish_unit: UNDERLYING_TYPE" << t << endl; };
h4ck3rm1k3/gcc-plugin-cpp-template
tree-nodes/underlying_type.cpp
C++
gpl-3.0
390
if (Meteor.isClient) { Session.setDefault('degF',-40); Session.setDefault('degC',-40); Template.temperatureBoxes.helpers({ degF: function(){ return Session.get('degF'); }, degC: function(){ return Session.get('degC'); } }); Template.temperatureBoxes.events({ 'keyup #c': function(e){ if(e.which === 13) { var degC = e.target.value; var degF = Math.round(degC*9/5 + 32); Session.set('degF',degF); } }, 'keyup #f': function(e){ if(e.which === 13) { var degF = e.target.value; var degC = Math.round((degF-32)* 5/9); Session.set('degC',degC); } } }); } if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); }
a2life/meteor-temp-converter
tempconv.js
JavaScript
gpl-3.0
786
/* * Twidere - Twitter client for Android * * Copyright (C) 2012 Mariotaku Lee <mariotaku.lee@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 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.pahans.kichibichiya.loader; import java.util.ArrayList; import java.util.List; import com.pahans.kichibichiya.model.ParcelableUser; import twitter4j.ResponseList; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.User; import android.content.Context; public class UserSearchLoader extends ParcelableUsersLoader { private final String mQuery; private final int mPage; private final long mAccountId; public UserSearchLoader(final Context context, final long account_id, final String query, final int page, final List<ParcelableUser> users_list) { super(context, account_id, users_list); mQuery = query; mPage = page; mAccountId = account_id; } @Override public List<ParcelableUser> getUsers() throws TwitterException { final Twitter twitter = getTwitter(); if (twitter == null) return null; final ResponseList<User> users = twitter.searchUsers(mQuery, mPage); final List<ParcelableUser> result = new ArrayList<ParcelableUser>(); final int size = users.size(); for (int i = 0; i < size; i++) { result.add(new ParcelableUser(users.get(i), mAccountId, (mPage - 1) * 20 + i)); } return result; } }
pahans/Kichibichiya
src/com/pahans/kichibichiya/loader/UserSearchLoader.java
Java
gpl-3.0
1,944
<?php /************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2021 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko * Website: https://www.espocrm.com * * EspoCRM 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. * * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ namespace Espo\Core\Hooks; use Espo\Core\Interfaces\Injectable; /** @deprecated */ abstract class Base implements Injectable { protected $injections = []; public static $order = 9; protected $dependencyList = [ 'container', 'entityManager', 'config', 'metadata', 'aclManager', 'user', 'serviceFactory', ]; protected $dependencies = []; // for backward compatibility public function __construct() { $this->init(); } protected function init() { } public function getDependencyList() { return array_merge($this->dependencyList, $this->dependencies); } protected function addDependencyList(array $list) { foreach ($list as $item) { $this->addDependency($item); } } protected function addDependency($name) { $this->dependencyList[] = $name; } protected function getInjection($name) { return $this->injections[$name] ?? $this->$name ?? null; } public function inject($name, $object) { $this->injections[$name] = $object; } protected function getContainer() { return $this->getInjection('container'); } protected function getEntityManager() { return $this->getInjection('entityManager'); } protected function getUser() { return $this->getInjection('user'); } protected function getAcl() { return $this->getContainer()->get('acl'); } protected function getAclManager() { return $this->getInjection('aclManager'); } protected function getConfig() { return $this->getInjection('config'); } protected function getMetadata() { return $this->getInjection('metadata'); } protected function getServiceFactory() { return $this->getInjection('serviceFactory'); } }
ayman-alkom/espocrm
application/Espo/Core/Hooks/Base.php
PHP
gpl-3.0
3,319
# -*- coding: utf-8 -*- # Copyright © 2013, 2014, 2017, 2020 Tom Most <twm@freecog.net> # # 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/>. # # Additional permission under GNU GPL version 3 section 7 # # If you modify this Program, or any covered work, by linking or # combining it with OpenSSL (or a modified version of that library), # containing parts covered by the terms of the OpenSSL License, the # licensors of this Program grant you additional permission to convey # the resulting work. Corresponding Source for a non-source form of # such a combination shall include the source code for the parts of # OpenSSL used as well as that of the covered work. from __future__ import absolute_import import argparse import os import sys import yarrharr def main(argv=sys.argv[1:]): parser = argparse.ArgumentParser(description="Yarrharr feed reader") parser.add_argument("--version", action="version", version=yarrharr.__version__) parser.parse_args(argv) os.environ["DJANGO_SETTINGS_MODULE"] = "yarrharr.settings" from yarrharr.application import run run()
twm/yarrharr
yarrharr/scripts/yarrharr.py
Python
gpl-3.0
1,676
package com.teckcoder.crashengine.file; import com.teckcoder.crashengine.utils.logger.Logger; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class FileStream { File file = null; FileLocationType locationType = null; private FileStream(String path, FileLocationType locationType){ this.locationType = locationType; file = new File(path); } public static FileStream loadInternalFile(String path){ FileStream file = new FileStream(path, FileLocationType.INTERNAL); return file; } public static FileStream loadExternalFile(String path){ FileStream file = new FileStream(path, FileLocationType.EXTERNAL); return file; } public InputStream getInputStream() { if(locationType == FileLocationType.EXTERNAL) try { return new FileInputStream(file.getPath().replace("\\", "/")); } catch (FileNotFoundException e) { e.printStackTrace(); Logger.logError("file missing", "Le fichier n'existe pas!"); } else if(locationType == FileLocationType.INTERNAL) return FileStream.class.getResourceAsStream("/"+file.getPath().replace("\\", "/")); Logger.logError("file location", "FileLocationType erreur"); return null; } public File getFile(){ return file; } public FileLocationType getFileLocationType(){ return locationType; } }
Techwave-dev/OpenGlModernGameEngine
src/com/teckcoder/crashengine/file/FileStream.java
Java
gpl-3.0
1,379
/** * This file is part of tera-api. * * tera-api 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. * * tera-api 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 tera-api. If not, see <http://www.gnu.org/licenses/>. */ package com.tera.common.database.dao; import java.util.Map; import com.tera.common.model.context.Context; import com.tera.common.model.context.ContextType; /** * @author ATracer */ @Context(type = ContextType.DAO) public interface ServerPropertiesDAO extends ContextDAO { /** * @param name * @return */ String loadProperty(String name); /** * @return */ Map<String, String> loadProperties(); /** * @param name * @return */ boolean hasProperty(String name); /** * @param name * @param value */ void saveProperty(String name, String value, boolean isNew); }
xGamers665/tera-emu
com.tera.common.database/src/main/java/com/tera/common/database/dao/ServerPropertiesDAO.java
Java
gpl-3.0
1,348
//----------------------------------------------------------------------------- // Class implementation: Input_Value::Line //----------------------------------------------------------------------------- #include "../pragmas.h" #include "Input_Value_Line.h" #include "Input_Text_File.h" #include "Assert_That.h" //---------------------------------------------------------------------------- Input_Value::Line::Line() : str_(""), name_(""), name_pos_(0), unmatched_() { } //---------------------------------------------------------------------------- bool Input_Value::Line::name_matches(const std::string & name, Str_Equal_Func str_equal_func, std::string & rest_of_line) { ASSERT_THAT(str_equal_func != 0) if (str_equal_func(name, name_)) { rest_of_line = str_.substr(name_pos_ + name_.size()); return true; } else { unmatched_.push_back(name); return false; } } //---------------------------------------------------------------------------- bool Input_Value::Line::read(Input::Text_File & file) { if (file.read_line(str_)) { std::istringstream strm(str_); if (strm >> name_) { name_pos_ = str_.find(name_); } else { name_ = ""; name_pos_ = 0; } unmatched_.clear(); return true; } else { str_ = ""; name_ = ""; name_pos_ = 0; return false; } }
geoSpacer/SUE
libs/common/Input_Value_Line.cpp
C++
gpl-3.0
1,416
from django.core.management.base import BaseCommand, CommandError from django.core import management from django.db.models import Count from scoping.models import * class Command(BaseCommand): help = 'check a query file - how many records' def add_arguments(self, parser): parser.add_argument('qid',type=int) def handle(self, *args, **options): qid = options['qid'] q = Query.objects.get(pk=qid) p = 'TY - ' if q.query_file.name is not '': fpath = q.query_file.path else: if q.database=="scopus": fname = 's_results.txt' else: fname = 'results.txt' fpath = f'{settings.QUERY_DIR}/{qid}/{fname}' with open(fpath, 'r') as f: c = f.read().count(p) print('\n{} documents in downloaded file\n'.format(c)) if q.doc_set.count() > 0: yts = q.doc_set.values('PY').annotate( n = Count('pk') ) for y in yts: print('{} documents in {}'.format(y['n'],y['PY']))
mcallaghan/tmv
BasicBrowser/scoping/management/commands/check_query_file.py
Python
gpl-3.0
1,107
package com.watabou.pixeldungeon.windows; import com.nyrds.pixeldungeon.game.GameLoop; import com.nyrds.pixeldungeon.game.GamePreferences; import com.nyrds.pixeldungeon.ml.R; import com.nyrds.pixeldungeon.utils.ModDesc; import com.nyrds.pixeldungeon.windows.DownloadProgressWindow; import com.nyrds.pixeldungeon.windows.ScrollableList; import com.nyrds.pixeldungeon.windows.WndHelper; import com.nyrds.platform.game.RemixedDungeon; import com.nyrds.platform.storage.FileSystem; import com.nyrds.platform.util.StringsManager; import com.nyrds.util.DownloadStateListener; import com.nyrds.util.DownloadTask; import com.nyrds.util.GuiProperties; import com.nyrds.util.ModdingMode; import com.nyrds.util.Mods; import com.nyrds.util.UnzipStateListener; import com.nyrds.util.UnzipTask; import com.nyrds.util.Util; import com.watabou.noosa.Text; import com.watabou.noosa.ui.Component; import com.watabou.pixeldungeon.SaveUtils; import com.watabou.pixeldungeon.scenes.PixelScene; import com.watabou.pixeldungeon.ui.Icons; import com.watabou.pixeldungeon.ui.RedButton; import com.watabou.pixeldungeon.ui.SimpleButton; import com.watabou.pixeldungeon.ui.Window; import com.watabou.pixeldungeon.utils.Utils; import java.io.File; import java.util.Map; public class WndModSelect extends Window implements DownloadStateListener.IDownloadComplete, UnzipStateListener { private String selectedMod; private String downloadTo; private final Map<String, ModDesc> modsList; public WndModSelect() { super(); resizeLimited(120); modsList = Mods.buildModsList(); boolean haveInternet = Util.isConnectedToInternet(); Text tfTitle = PixelScene.createMultiline(StringsManager.getVar(R.string.ModsButton_SelectMod), GuiProperties.titleFontSize()); tfTitle.hardlight(TITLE_COLOR); tfTitle.x = tfTitle.y = GAP; tfTitle.maxWidth(width - GAP * 2); add(tfTitle); ScrollableList list = new ScrollableList(new Component()); add(list); float pos = 0; for (Map.Entry<String, ModDesc> entry : modsList.entrySet()) { final ModDesc desc = entry.getValue(); float additionalMargin = Icons.get(Icons.CLOSE).width() + GAP; if (desc.installed && !ModdingMode.REMIXED.equals(desc.name)) { SimpleButton deleteBtn = new SimpleButton(Icons.get(Icons.CLOSE)) { protected void onClick() { onDelete(desc.installDir); } }; deleteBtn.setPos(width - (deleteBtn.width() * 2) - GAP, pos + (BUTTON_HEIGHT - deleteBtn.height())/2); list.content().add(deleteBtn); } String option = desc.name; if (desc.needUpdate && haveInternet) { option = "Update " + option; } if (desc.installed || haveInternet) { RedButton btn = new RedButton(option) { @Override protected void onClick() { hide(); onSelect(desc.installDir); } }; btn.setRect(GAP, pos, width - GAP * 2 - (additionalMargin * 2), BUTTON_HEIGHT); list.content().add(btn); pos += BUTTON_HEIGHT + GAP; } } resize(WndHelper.getLimitedWidth(120), WndHelper.getFullscreenHeight() - WINDOW_MARGIN); list.content().setSize(width, pos); list.setRect(0, tfTitle.bottom() + GAP, width, height - tfTitle.height() - GAP); list.scrollTo(0,0); } private void onDelete(String name) { File modDir = FileSystem.getExternalStorageFile(name); if (modDir.exists() && modDir.isDirectory()) { FileSystem.deleteRecursive(modDir); } if (GamePreferences.activeMod().equals(name)) { SaveUtils.deleteGameAllClasses(); SaveUtils.copyAllClassesFromSlot(ModdingMode.REMIXED); GamePreferences.activeMod(ModdingMode.REMIXED); RemixedDungeon.instance().doRestart(); } if (getParent() != null) { hide(); } GameLoop.addToScene(new WndModSelect()); } protected void onSelect(String option) { ModDesc desc = modsList.get(option); if (!option.equals(ModdingMode.REMIXED) || desc.needUpdate) { if (desc.needUpdate) { FileSystem.deleteRecursive(FileSystem.getExternalStorageFile(desc.installDir)); selectedMod = desc.installDir; downloadTo = FileSystem.getExternalStorageFile(selectedMod+".tmp").getAbsolutePath(); desc.needUpdate = false; GameLoop.execute(new DownloadTask(new DownloadProgressWindow(Utils.format("Downloading %s", selectedMod),this), desc.url, downloadTo)); return; } } String prevMod = GamePreferences.activeMod(); if (option.equals(prevMod)) { return; } if (getParent() != null) { hide(); } GameLoop.addToScene(new WndModDescription(option, prevMod)); } @Override public void DownloadComplete(String url, final Boolean result) { GameLoop.pushUiTask(() -> { if (result) { GameLoop.execute(new UnzipTask(WndModSelect.this, downloadTo, true)); } else { GameLoop.addToScene(new WndError(Utils.format("Downloading %s failed", selectedMod))); } }); } private WndMessage unzipProgress; @Override public void UnzipComplete(final Boolean result) { GameLoop.pushUiTask(() -> { if(unzipProgress!=null) { unzipProgress.hide(); unzipProgress = null; } if (result) { GameLoop.addToScene(new WndModSelect()); } else { GameLoop.addToScene(new WndError(Utils.format("unzipping %s failed", downloadTo))); } }); } @Override public void UnzipProgress(Integer unpacked) { GameLoop.pushUiTask(() -> { if (unzipProgress == null) { unzipProgress = new WndMessage(Utils.EMPTY_STRING); GameLoop.addToScene(unzipProgress); } if (unzipProgress.getParent() == GameLoop.scene()) { unzipProgress.setText(Utils.format("Unpacking: %d", unpacked)); } }); } }
NYRDS/pixel-dungeon-remix
RemixedDungeon/src/main/java/com/watabou/pixeldungeon/windows/WndModSelect.java
Java
gpl-3.0
5,619
/* * 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.sql.element; import org.openconcerto.sql.Log; import org.openconcerto.sql.TM; import org.openconcerto.sql.model.DBStructureItemNotFound; import org.openconcerto.sql.model.SQLName; import org.openconcerto.sql.model.SQLTable; import org.openconcerto.utils.CollectionUtils; import org.openconcerto.utils.SetMap; import org.openconcerto.utils.cc.ITransformer; import org.openconcerto.utils.i18n.LocalizedInstances; import org.openconcerto.utils.i18n.Phrase; import org.openconcerto.utils.i18n.TranslationManager; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.jdom.JDOMException; /** * Directory of SQLElement by table. * * @author Sylvain CUAZ */ public final class SQLElementDirectory { public static final String BASENAME = SQLElementNames.class.getSimpleName(); private static final LocalizedInstances<SQLElementNames> LOCALIZED_INSTANCES = new LocalizedInstances<SQLElementNames>(SQLElementNames.class, TranslationManager.getControl()) { @Override protected SQLElementNames createInstance(String bundleName, Locale candidate, Class<?> cl) throws IOException { final InputStream ins = cl.getResourceAsStream('/' + getControl().toResourceName(bundleName, "xml")); if (ins == null) return null; final SQLElementNamesFromXML res = new SQLElementNamesFromXML(candidate); try { res.load(ins); } catch (JDOMException e) { throw new IOException("Invalid XML", e); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } finally { ins.close(); } return res; } }; private final Map<SQLTable, SQLElement> elements; private final SetMap<String, SQLTable> tableNames; private final SetMap<String, SQLTable> byCode; private final SetMap<Class<? extends SQLElement>, SQLTable> byClass; private final List<DirectoryListener> listeners; private String phrasesPkgName; private final Map<String, SQLElementNames> elementNames; public SQLElementDirectory() { this.elements = new HashMap<SQLTable, SQLElement>(); // to mimic elements behaviour, if we add twice the same table // the second one should replace the first one this.tableNames = new SetMap<String, SQLTable>(); this.byCode = new SetMap<String, SQLTable>(); this.byClass = new SetMap<Class<? extends SQLElement>, SQLTable>(); this.listeners = new ArrayList<DirectoryListener>(); this.phrasesPkgName = null; this.elementNames = new HashMap<String, SQLElementNames>(); } private static <K> SQLTable getSoleTable(SetMap<K, SQLTable> m, K key) throws IllegalArgumentException { final Collection<SQLTable> res = m.getNonNull(key); if (res.size() > 1) throw new IllegalArgumentException(key + " is not unique: " + CollectionUtils.join(res, ",", new ITransformer<SQLTable, SQLName>() { @Override public SQLName transformChecked(SQLTable input) { return input.getSQLName(); } })); return CollectionUtils.getSole(res); } public synchronized final void putAll(SQLElementDirectory o) { for (final SQLElement elem : o.getElements()) { if (!this.contains(elem.getTable())) this.addSQLElement(elem); } } /** * Add an element by creating it with the no-arg constructor. If the element cannot find its * table and thus raise DBStructureItemNotFound, the exception is logged. * * @param element the element to add. */ public final void addSQLElement(final Class<? extends SQLElement> element) { try { this.addSQLElement(element.getConstructor().newInstance()); } catch (InvocationTargetException e) { if (e.getCause() instanceof DBStructureItemNotFound) { Log.get().config("ignore inexistent tables: " + e.getCause().getLocalizedMessage()); return; } throw new IllegalArgumentException("ctor failed", e); } catch (Exception e) { throw new IllegalArgumentException("no-arg ctor failed", e); } } /** * Adds an already instantiated element. * * @param elem the SQLElement to add. * @return the previously added element. */ public synchronized final SQLElement addSQLElement(SQLElement elem) { final SQLElement res = this.removeSQLElement(elem.getTable()); this.elements.put(elem.getTable(), elem); this.tableNames.add(elem.getTable().getName(), elem.getTable()); this.byCode.add(elem.getCode(), elem.getTable()); this.byClass.add(elem.getClass(), elem.getTable()); for (final DirectoryListener dl : this.listeners) { dl.elementAdded(elem); } elem.setDirectory(this); return res; } public synchronized final boolean contains(SQLTable t) { return this.elements.containsKey(t); } public synchronized final SQLElement getElement(SQLTable t) { return this.elements.get(t); } /** * Search for a table whose name is <code>tableName</code>. * * @param tableName a table name, e.g. "ADRESSE". * @return the corresponding SQLElement, or <code>null</code> if there is no table named * <code>tableName</code>. * @throws IllegalArgumentException if more than one table match. */ public synchronized final SQLElement getElement(String tableName) { return this.getElement(getSoleTable(this.tableNames, tableName)); } /** * Search for an SQLElement whose class is <code>clazz</code>. * * @param <S> type of SQLElement * @param clazz the class. * @return the corresponding SQLElement, or <code>null</code> if none can be found. * @throws IllegalArgumentException if there's more than one match. */ public synchronized final <S extends SQLElement> S getElement(Class<S> clazz) { return clazz.cast(this.getElement(getSoleTable(this.byClass, clazz))); } public synchronized final SQLElement getElementForCode(String code) { return this.getElement(getSoleTable(this.byCode, code)); } public synchronized final Set<SQLTable> getTables() { return this.getElementsMap().keySet(); } public synchronized final Collection<SQLElement> getElements() { return this.getElementsMap().values(); } public final Map<SQLTable, SQLElement> getElementsMap() { return Collections.unmodifiableMap(this.elements); } /** * Remove the passed instance. NOTE: this method only remove the specific instance passed, so * it's a conditional <code>removeSQLElement(elem.getTable())</code>. * * @param elem the instance to remove. * @see #removeSQLElement(SQLTable) */ public synchronized void removeSQLElement(SQLElement elem) { if (this.getElement(elem.getTable()) == elem) this.removeSQLElement(elem.getTable()); } /** * Remove the element for the passed table. * * @param t the table to remove. * @return the removed element, can be <code>null</code>. */ public synchronized SQLElement removeSQLElement(SQLTable t) { final SQLElement elem = this.elements.remove(t); if (elem != null) { this.tableNames.remove(elem.getTable().getName(), elem.getTable()); this.byCode.remove(elem.getCode(), elem.getTable()); this.byClass.remove(elem.getClass(), elem.getTable()); // MAYBE only reset neighbours. for (final SQLElement otherElem : this.elements.values()) otherElem.resetRelationships(); elem.setDirectory(null); for (final DirectoryListener dl : this.listeners) { dl.elementRemoved(elem); } } return elem; } public synchronized final void initL18nPackageName(final String baseName) { if (this.phrasesPkgName != null) throw new IllegalStateException("Already initialized : " + this.getL18nPackageName()); this.phrasesPkgName = baseName; } public synchronized final String getL18nPackageName() { return this.phrasesPkgName; } protected synchronized final SQLElementNames getElementNames(final String pkgName, final Locale locale, final Class<?> cl) { if (pkgName == null) return null; final char sep = ' '; final String key = pkgName + sep + locale.toString(); assert pkgName.indexOf(sep) < 0 : "ambiguous key : " + key; SQLElementNames res = this.elementNames.get(key); if (res == null) { final List<SQLElementNames> l = LOCALIZED_INSTANCES.createInstances(pkgName + "." + BASENAME, locale, cl).get1(); if (!l.isEmpty()) { for (int i = 1; i < l.size(); i++) { l.get(i - 1).setParent(l.get(i)); } res = l.get(0); } this.elementNames.put(key, res); } return res; } /** * Search a name for the passed instance and the {@link TM#getTranslationsLocale() current * locale}. Search for {@link SQLElementNames} using {@link LocalizedInstances} and * {@link SQLElementNamesFromXML} first in {@link SQLElement#getL18nPackageName()} then in * {@link #getL18nPackageName()}. E.g. this could load SQLElementNames_en.class and * SQLElementNames_en_UK.xml. * * @param elem the element. * @return the name if found, <code>null</code> otherwise. */ public final Phrase getName(final SQLElement elem) { final String elemBaseName = elem.getL18nPackageName(); final String pkgName = elemBaseName == null ? getL18nPackageName() : elemBaseName; final SQLElementNames elementNames = getElementNames(pkgName, TM.getInstance().getTranslationsLocale(), elem.getL18nClass()); return elementNames == null ? null : elementNames.getName(elem); } public synchronized final void addListener(DirectoryListener dl) { this.listeners.add(dl); } public synchronized final void removeListener(DirectoryListener dl) { this.listeners.remove(dl); } static public interface DirectoryListener { void elementAdded(SQLElement elem); void elementRemoved(SQLElement elem); } }
mbshopM/openconcerto
OpenConcerto/src/org/openconcerto/sql/element/SQLElementDirectory.java
Java
gpl-3.0
11,868
/* Exploit smf when computing the intersection of NNC dual hypercubes. Copyright (C) 2001-2009 Roberto Bagnara <bagnara@cs.unipr.it> This file is part of the Parma Polyhedra Library (PPL). The PPL 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. The PPL 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1307, USA. For the most up-to-date information see the Parma Polyhedra Library site: http://www.cs.unipr.it/ppl/ . */ #include "ppl_test.hh" #include "timings.hh" #include <vector> #include <map> // Define EXP_EVAL to 1 if you want to reproduce the results // of the experimental evaluation reported in Table 2 of the paper: // R. Bagnara, P.M. Hill, E. Zaffanella // Not Necessarily Closed Convex Polyhedra and the Double Description Method. // Formal Aspects of Computing, 17, 2 (2005), pp. 222-257. #ifndef EXP_EVAL #define EXP_EVAL 0 #endif namespace { void closure_points_dual_hypercube(const dimension_type dims, const Linear_Expression& weight_center, const Coefficient& half_diagonal, Generator_System& gs) { // An ill-formed (it has no points at all) generator system // for a dual hypercube. for (dimension_type axis = dims; axis-- > 0; ) { gs.insert(closure_point(weight_center + half_diagonal * Variable(axis))); gs.insert(closure_point(weight_center - half_diagonal * Variable(axis))); } } void add_facets(dimension_type& to_be_added, Generator_System& gs, const Linear_Expression& expr, const dimension_type axis, const dimension_type dims, const Linear_Expression& weight_center, const Coefficient& half_diagonal) { // Return if we have already added all facets. if (to_be_added == 0) return; Linear_Expression expr1 = expr; expr1 += half_diagonal * Variable(axis); Linear_Expression expr2 = expr; expr2 -= half_diagonal * Variable(axis); if (axis == 0) { gs.insert(point(dims * weight_center + expr1, dims)); --to_be_added; if (to_be_added == 0) return; gs.insert(point(dims * weight_center + expr2, dims)); --to_be_added; return; } // Here axis > 0. // First recursive call with variable with index `axis' // having coordinate 1/dims. add_facets(to_be_added, gs, expr1, axis-1, dims, weight_center, half_diagonal); if (to_be_added == 0) return; // Second recursive call with variable with index `axis' // having coordinate -1/dims. add_facets(to_be_added, gs, expr2, axis-1, dims, weight_center, half_diagonal); } NNC_Polyhedron NNC_dual_hypercube(const dimension_type dims, const Linear_Expression& weight_center, const Coefficient& half_diagonal, const int facet_percentage) { Generator_System gs; closure_points_dual_hypercube(dims, weight_center, half_diagonal, gs); // Number of facets in the closed dual hypercube. dimension_type num_facets = 1; for (dimension_type axis = dims; axis-- > 0; ) num_facets *= 2; dimension_type facets_to_be_added = (num_facets * facet_percentage) / 100; if (facets_to_be_added == 0) // There has to be a point, at least. gs.insert(point(weight_center)); else add_facets(facets_to_be_added, gs, Linear_Expression(0), dims-1, dims, weight_center, half_diagonal); // Actually build the polyhedron. return NNC_Polyhedron(gs); } void build_polyhedra(const dimension_type dims, const int percentage, std::vector<NNC_Polyhedron>& ph) { Linear_Expression weight_center; // 1st-polyhedron. weight_center = Linear_Expression(0); for (dimension_type axis = dims; axis-- > 0; ) weight_center += Variable(axis); ph.push_back(NNC_dual_hypercube(dims, weight_center, 5, percentage)); // 2nd-polyhedron. weight_center = Linear_Expression(0); for (dimension_type axis = dims; axis-- > 0; ) weight_center += 2*Variable(axis); ph.push_back(NNC_dual_hypercube(dims, weight_center, 4, percentage)); // 3rd-polyhedron. weight_center = Linear_Expression(0); for (dimension_type axis = dims; axis-- > 0; ) if (axis % 2 == 0) weight_center += 10*Variable(axis); else weight_center += 2*Variable(axis); ph.push_back(NNC_dual_hypercube(dims, weight_center, 5, percentage)); // 4th-polyhedron. weight_center = Linear_Expression(0); for (dimension_type axis = dims; axis-- > 0; ) if (axis % 2 == 0) weight_center += 10*Variable(axis); else weight_center += Variable(axis); ph.push_back(NNC_dual_hypercube(dims, weight_center, 4, percentage)); } long computation(std::vector<NNC_Polyhedron>& ph, bool enhanced) { nout << endl; if (enhanced) nout << "Enhanced computation: "; else nout << "Standard computation: "; nout << "working with 4 NNC dual hypercubes of dimension " << ph[0].space_dimension() << endl; start_clock(); /**** Compute the intersection of ph[0] and ph[1]. ****/ // Print cardinalities of arguments. nout << " - Computing intersection of ph[0] and ph[1]:" << endl; const Generator_System& gs_0 = ph[0].generators(); nout << " # ph[0].generators() = " << std::distance(gs_0.begin(), gs_0.end()) << endl; const Generator_System& gs_1 = ph[1].generators(); nout << " # ph[1].generators() = " << std::distance(gs_1.begin(), gs_1.end()) << endl; // Very noisy dump of arguments. vnout << "*** ph[0] generators ***" << endl; gs_0.ascii_dump(vnout); vnout << "*** ph[1] generators ***" << endl; gs_1.ascii_dump(vnout); vnout << endl; const Constraint_System& cs_0 = enhanced ? ph[0].minimized_constraints() : ph[0].constraints(); const Constraint_System& cs_1 = enhanced ? ph[1].minimized_constraints() : ph[1].constraints(); // Print cardinalities of constraint systems. nout << " # ph[0].constraints() = " << std::distance(cs_0.begin(), cs_0.end()) << endl; nout << " # ph[1].constraints() = " << std::distance(cs_1.begin(), cs_1.end()) << endl; // Very noisy dump of arguments. vnout << "*** ph[0] constraints ***" << endl; cs_0.ascii_dump(vnout); vnout << "*** ph[1] constraints ***" << endl; cs_1.ascii_dump(vnout); vnout << endl; ph[0].intersection_assign(ph[1]); /**** Compute the intersection of ph[2] and ph[3]. ****/ // Print cardinalities of arguments. nout << " - Computing intersection of ph[2] and ph[3]:" << endl; const Generator_System& gs_2 = ph[2].generators(); nout << " # ph[2].generators() = " << std::distance(gs_2.begin(), gs_2.end()) << endl; const Generator_System& gs_3 = ph[3].generators(); nout << " # ph[3].generators() = " << std::distance(gs_3.begin(), gs_3.end()) << endl; // Very noisy dump of arguments. vnout << "*** ph[2] generators ***" << endl; gs_2.ascii_dump(vnout); vnout << "*** ph[3] generators ***" << endl; gs_3.ascii_dump(vnout); vnout << endl; const Constraint_System& cs_2 = enhanced ? ph[2].minimized_constraints() : ph[2].constraints(); const Constraint_System& cs_3 = enhanced ? ph[3].minimized_constraints() : ph[3].constraints(); // Print cardinalities of constraint systems. nout << " # ph[2].constraints() = " << std::distance(cs_2.begin(), cs_2.end()) << endl; nout << " # ph[3].constraints() = " << std::distance(cs_3.begin(), cs_3.end()) << endl; // Very noisy dump of arguments. vnout << "*** ph[2] constraints ***" << endl; cs_2.ascii_dump(vnout); vnout << "*** ph[3] constraints ***" << endl; cs_3.ascii_dump(vnout); vnout << endl; ph[2].intersection_assign(ph[3]); /**** Compute the poly-hull of ph[0] and ph[2]. ****/ const Generator_System& gs_01 = enhanced ? ph[0].minimized_generators() : ph[0].generators(); const Generator_System& gs_23 = enhanced ? ph[2].minimized_generators() : ph[2].generators(); // Print cardinalities of arguments. nout << " - Computing poly-hull of ph[0] and ph[2]:" << endl; nout << " # ph[0].generators() = " << std::distance(gs_01.begin(), gs_01.end()) << endl; nout << " # ph[2].generators() = " << std::distance(gs_23.begin(), gs_23.end()) << endl; // Very noisy dump of arguments. vnout << "*** ph[0] generators ***" << endl; gs_01.ascii_dump(vnout); vnout << "*** ph[2] generators ***" << endl; gs_23.ascii_dump(vnout); vnout << endl; ph[0].upper_bound_assign(ph[2]); /**** Final conversion ****/ const Constraint_System& cs = ph[0].constraints(); nout << "Wmf final result timing: "; print_clock(nout); nout << endl; // How many constraints obtained? const long cs_cardinality = std::distance(cs.begin(), cs.end()); // Print cardinality of weakly-minimized final result. nout << " - Final (wmf) result is ph[0]:" << endl; nout << " # ph[0].constraints() = " << cs_cardinality << endl; // Very noisy dump of weakly-minimized final result. vnout << "*** ph[0] constraints ***" << endl; cs.ascii_dump(vnout); vnout << endl; /**** Final strong minimization ****/ nout << "Smf (cons) final result timing: "; start_clock(); const Constraint_System& min_cs = ph[0].minimized_constraints(); print_clock(nout); nout << endl; // How many constraints obtained? const long min_cs_cardinality = std::distance(min_cs.begin(), min_cs.end()); // Print cardinality of strongly-minimized final result. nout << " - Final (smf) result is ph[0]:" << endl; nout << " # ph[0].minimized_constraints() = " << min_cs_cardinality << endl; // Very noisy dump of strongly-minimized final result. vnout << "*** ph[0] minimized constraints ***" << endl; min_cs.ascii_dump(vnout); vnout << endl; return enhanced ? min_cs_cardinality : cs_cardinality; } bool test01() { std::vector<NNC_Polyhedron> ph; #if EXP_EVAL dimension_type first_dim = 4; dimension_type last_dim = 5; #else dimension_type first_dim = 2; dimension_type last_dim = 4; #endif // Storing cardinalities of known results. // NOTE: the numbers reported here differ a little bit from those // in the FAC paper in that here we do not count low-level constraints // related to the epsilon dimension. The difference is at most 2 // (the eps_geq_zero and eps_leq_one constraints). typedef std::map<std::pair<dimension_type, int>, long> My_Map; My_Map::const_iterator known_result; My_Map standard_cardinalities; My_Map enhanced_cardinalities; using std::make_pair; standard_cardinalities[make_pair(4, 25)] = 331; // FAC 332 enhanced_cardinalities[make_pair(4, 25)] = 31; // FAC 33 standard_cardinalities[make_pair(4, 50)] = 519; // FAC 520 enhanced_cardinalities[make_pair(4, 50)] = 41; // FAC 43 standard_cardinalities[make_pair(5, 25)] = 2692; // FAC 2693 enhanced_cardinalities[make_pair(5, 25)] = 125; // FAC 127 standard_cardinalities[make_pair(5, 50)] = 4993; // FAC 4994 enhanced_cardinalities[make_pair(5, 50)] = 150; // FAC 152 int num_errors = 0; for (dimension_type dims = first_dim; dims <= last_dim; dims++) for (int percentage = 25; percentage <= 50; percentage += 25) { nout << endl << "++++++++ DIMENSIONS = " << dims << " ++++++++" << endl << "++++++++ PERCENTAGE = " << percentage << " ++++++++" << endl; // Standard evaluation strategy. ph.clear(); build_polyhedra(dims, percentage, ph); const long standard_eval_card = computation(ph, false); // Check if there is a known result. known_result = standard_cardinalities.find(make_pair(dims, percentage)); if (known_result != standard_cardinalities.end() && known_result->second != standard_eval_card) { ++num_errors; nout << "Cardinality mismatch: " << "expected " << known_result->second << ", " << "obtained " << standard_eval_card << ".\n"; } // Enhanced evaluation strategy. ph.clear(); build_polyhedra(dims, percentage, ph); const long enhanced_eval_card = computation(ph, true); // Check if there is a known result. known_result = enhanced_cardinalities.find(make_pair(dims, percentage)); if (known_result != enhanced_cardinalities.end() && known_result->second != enhanced_eval_card) { ++num_errors; nout << "Cardinality mismatch: " << "expected " << known_result->second << ", " << "obtained " << enhanced_eval_card <<".\n"; } } return (num_errors == 0); } } // namespace BEGIN_MAIN DO_TEST_F64A(test01); END_MAIN
OpenInkpot-archive/iplinux-ppl
tests/Polyhedron/dualhypercubes.cc
C++
gpl-3.0
12,977
<div id="intro"> <h1>ABOUT US</h1> </div> <div class="content_page"> <div id="left"> <p>Sed eu molestie purus. Maecenas convallis faucibus viverra. Nulla malesuada vestibulum leo, non pharetra lacus cursus sed. Nam semper sagittis leo, vitae pharetra magna ultricies a. Vivamus blandit, tortor et vehicula fringilla, lectus est pellentesque augue, vitae accumsan augue nisl sed nibh. Etiam vel erat leo. Nam tempor posuere mi, congue auctor nisl tincidunt ut. Etiam ut turpis ligula. </p> <h1>Lorem ipsum dolor sit amet</h1> <blockquote> Nam sed dui nulla, quis fermentum diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </blockquote> <h1>LOREM IPSUM</h1> <p>Cras vel nunc a risus placerat placerat. Proin at sem aliquam enim ultrices blandit. Pellentesque imperdiet facilisis est, sit amet aliquet elit imperdiet nec.</p> <ul> <li>Nullam id purus nunc. Donec a erat eget metus condimentum faucibus. </li> <li>Curabitur blandit accumsan libero, </li> <li>non vulputate diam sagittis vel</li> </ul> <h1>LOREM IPSUM</h1> <p>Cras vel nunc a risus placerat placerat. Proin at sem aliquam enim ultrices blandit. Pellentesque imperdiet facilisis est, sit amet aliquet elit imperdiet nec.</p> <ol> <li>Nullam id purus nunc. Donec a erat eget metus condimentum faucibus. </li> <li>Curabitur blandit accumsan libero, </li> <li>non vulputate diam sagittis vel</li> </ol> <br /> </div><!--left end--> <div id="right"> <img src="styles/images/about_stock.jpg" alt="" /> <a href ="" id="contact_btn" class="replace"><span>Contact us</span></a> </div><!--right ends--> </div><!--content end-->
labrosb/Hospital-Management-System
content/patient/about.php
PHP
gpl-3.0
2,450
function handleDialogRequest(dialogName, xhr, status, args) { if (!args.success) { PF(dialogName).jq.effect("shake", {times : 5}, 100); } else { PF(dialogName).hide(); } }
matjaz99/DTools
WebContent/resources/default/1_0/js/dtools.js
JavaScript
gpl-3.0
180
package cn.bjsxt.oop.inherit; /** * 测试组合 * @author dell * */ public class Animal2 { String eye; public void run(){ System.out.println("跑跑!"); } public void eat(){ System.out.println("吃吃!"); } public void sleep(){ System.out.println("zzzzz"); } public Animal2(){ super(); System.out.println("创建一个动物!"); } public static void main(String[] args) { Bird2 b = new Bird2(); b.run(); b.animal2.eat(); } } class Mammal2 { Animal2 animal2=new Animal2(); //所谓组合,就是将父类的animal2作为属性防在这里 public void taisheng(){ System.out.println("我是胎生"); } } class Bird2 { Animal2 animal2=new Animal2(); //所谓组合,就是将父类的animal2作为属性防在这里 public void run(){ animal2.run(); System.out.println("我是一个小小小小鸟,飞呀飞不高"); } public void eggSheng(){ System.out.println("卵生"); } public Bird2(){ super(); System.out.println("建一个鸟对象"); } }
yangweijun213/Java
J2SE300/28_51OO/src/cn/bjsxt/oop/inherit/Animal2.java
Java
gpl-3.0
1,087
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2021 Evan Debenham * * 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.shatteredpixel.shatteredpixeldungeon.tiles; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; public class DungeonWallsTilemap extends DungeonTilemap { public DungeonWallsTilemap(){ super(Dungeon.level.tilesTex()); map( Dungeon.level.map, Dungeon.level.width() ); } @Override protected int getTileVisual(int pos, int tile, boolean flat){ if (flat) return -1; if (DungeonTileSheet.wallStitcheable(tile)) { if (pos + mapWidth < size && !DungeonTileSheet.wallStitcheable(map[pos + mapWidth])){ if (map[pos + mapWidth] == Terrain.DOOR){ return DungeonTileSheet.DOOR_SIDEWAYS; } else if (map[pos + mapWidth] == Terrain.LOCKED_DOOR){ return DungeonTileSheet.DOOR_SIDEWAYS_LOCKED; } else if (map[pos + mapWidth] == Terrain.OPEN_DOOR){ return DungeonTileSheet.NULL_TILE; } } else { return DungeonTileSheet.stitchInternalWallTile( tile, (pos+1) % mapWidth != 0 ? map[pos + 1] : -1, (pos+1) % mapWidth != 0 && pos + mapWidth < size ? map[pos + 1 + mapWidth] : -1, pos + mapWidth < size ? map[pos + mapWidth] : -1, pos % mapWidth != 0 && pos + mapWidth < size ? map[pos - 1 + mapWidth] : -1, pos % mapWidth != 0 ? map[pos - 1] : -1 ); } } if (pos + mapWidth < size && DungeonTileSheet.wallStitcheable(map[pos+mapWidth])) { return DungeonTileSheet.stitchWallOverhangTile( tile, (pos+1) % mapWidth != 0 ? map[pos + 1 + mapWidth] : -1, map[pos + mapWidth], pos % mapWidth != 0 ? map[pos - 1 + mapWidth] : -1 ); } else if (Dungeon.level.insideMap(pos) && (map[pos+mapWidth] == Terrain.DOOR || map[pos+mapWidth] == Terrain.LOCKED_DOOR) ) { return DungeonTileSheet.DOOR_OVERHANG; } else if (Dungeon.level.insideMap(pos) && map[pos+mapWidth] == Terrain.OPEN_DOOR ) { return DungeonTileSheet.DOOR_OVERHANG_OPEN; } else if (pos + mapWidth < size && (map[pos+mapWidth] == Terrain.STATUE || map[pos+mapWidth] == Terrain.STATUE_SP)){ return DungeonTileSheet.STATUE_OVERHANG; } else if (pos + mapWidth < size && map[pos+mapWidth] == Terrain.ALCHEMY){ return DungeonTileSheet.ALCHEMY_POT_OVERHANG; } else if (pos + mapWidth < size && map[pos+mapWidth] == Terrain.BARRICADE){ return DungeonTileSheet.BARRICADE_OVERHANG; } else if (pos + mapWidth < size && map[pos+mapWidth] == Terrain.HIGH_GRASS){ return DungeonTileSheet.getVisualWithAlts(DungeonTileSheet.HIGH_GRASS_OVERHANG, pos + mapWidth); } else if (pos + mapWidth < size && map[pos+mapWidth] == Terrain.FURROWED_GRASS){ return DungeonTileSheet.getVisualWithAlts(DungeonTileSheet.FURROWED_OVERHANG, pos + mapWidth); } return -1; } @Override public boolean overlapsPoint( float x, float y ) { return true; } @Override public boolean overlapsScreenPoint( int x, int y ) { return true; } }
00-Evan/shattered-pixel-dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/tiles/DungeonWallsTilemap.java
Java
gpl-3.0
3,780
using System; using System.Windows; using System.Windows.Threading; using StructureMap; using TailBlazer.Views; namespace TailBlazer.Infrastucture { public class BootStrap { [STAThread] public static void Main(string[] args) { var app = new App { ShutdownMode = ShutdownMode.OnLastWindowClose }; app.InitializeComponent(); var container = new Container(x=> x.AddRegistry<AppRegistry>()); var factory = container.GetInstance<WindowFactory>(); var window = factory.Create(); container.Configure(x => x.For<Dispatcher>().Add(window.Dispatcher)); //run start up jobs window.Show(); app.Run(); } } }
MendelMonteiro/TailBlazer
Source/TailBlazer/Infrastucture/BootStrap.cs
C#
gpl-3.0
754
using CP77.CR2W.Reflection; namespace CP77.CR2W.Types { [REDMeta] public class inkLayerProxy : ISerializable { public inkLayerProxy(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/inkLayerProxy.cs
C#
gpl-3.0
220
package org.schabi.newpipe.player; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.Log; import android.view.View; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import org.schabi.newpipe.ActivityCommunicator; import org.schabi.newpipe.R; import org.schabi.newpipe.extractor.MediaFormat; import org.schabi.newpipe.extractor.NewPipe; import org.schabi.newpipe.extractor.exceptions.ParsingException; import org.schabi.newpipe.extractor.stream_info.AudioStream; import org.schabi.newpipe.extractor.stream_info.StreamExtractor; import org.schabi.newpipe.extractor.stream_info.StreamPreviewInfo; import org.schabi.newpipe.extractor.stream_info.VideoStream; import org.schabi.newpipe.playList.NewPipeSQLiteHelper; import org.schabi.newpipe.settings.NetworkHelper; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.schabi.newpipe.search_fragment.SearchInfoItemFragment.PLAYLIST_ID; public class LunchAudioTrack { private final static String TAG = LunchAudioTrack.class.getName(); private final Context activity; private StreamPreviewInfo info = null; private Bitmap bitmap = null; private AudioStream audioStream = null; private final int playListId; private boolean hasLoadBitmap = false; private boolean hasAudioStream = false; public LunchAudioTrack(final Context activity, @NonNull final StreamPreviewInfo info, final int playListId) { this.activity = activity; this.info = info; this.playListId = playListId; } public void retrieveBitmap(final Runnable callback) { hasLoadBitmap = true; if (!TextUtils.isEmpty(info.thumbnail_url)) { ImageLoader.getInstance().loadImage(info.thumbnail_url, new ImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { Log.e(TAG, String.format("FAILED to load bitmap at %s", imageUri), failReason.getCause()); } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { Log.d(TAG, String.format("SUCCESS to load bitmap at %s", imageUri)); bitmap = loadedImage; if(callback != null) { callback.run(); } } @Override public void onLoadingCancelled(String imageUri, View view) { } }); } } public void retrieveInfoFromService(final Runnable callback) { hasAudioStream = true; new AsyncTask<Void, Void, AudioStream>() { @Override protected AudioStream doInBackground(Void... voids) { if(info != null) { try { final StreamExtractor extractor = NewPipe.getService(info.service_id) .getExtractorInstance(info.webpage_url); try { final List<AudioStream> audioStreams = extractor.getAudioStreams(); Log.d(TAG, String.format("Found %d audio track for song at %s", audioStreams.size(), info.webpage_url)); final AudioStream audioStream = audioStreams .get(getPreferredAudioStreamId(audioStreams)); Log.d(TAG, String.format("Url for track at %s\r\n%s", info.webpage_url, audioStream)); return audioStream; } catch (ParsingException e) { // fail back convert video to audio final List<VideoStream> videoStreams = extractor.getVideoStreams(); VideoStream selectedVideoStreamsBest = null; VideoStream selectedVideoStreamsSmall = null; int previousResolution = -1; for (final VideoStream videoStream : videoStreams) { if ("360p".equals(videoStream.resolution)) { selectedVideoStreamsBest = videoStream; } final int resolution = extractNumberPositiveInteger(videoStream.resolution); if (previousResolution == -1 || resolution < previousResolution) { previousResolution = resolution; selectedVideoStreamsSmall = videoStream; } } // check if we use wifi or not for avoid big download data on mobile network final boolean isConnectedByWifi = NetworkHelper.isOnlineByWifi(activity); final VideoStream videoStream = isConnectedByWifi && selectedVideoStreamsBest != null ? selectedVideoStreamsBest : selectedVideoStreamsSmall; if(videoStream == null) { return null; } Log.w(TAG, String.format("No audio track found, use fallback process " + "convert to AudioStream the video item (%s - %s)", MediaFormat.getMimeById(videoStream.format), videoStream.resolution)); return new AudioStream(videoStream.url, videoStream.format, -1, -1); } } catch (Exception e) { Log.e(TAG, "FAILED to found a proper audioStream value!", e); return null; } } else { return null; } } private int extractNumberPositiveInteger(final String str) { final Matcher m = Pattern.compile("[0-9]+").matcher(str); return m.find() ? Integer.parseInt(m.group()) : -1; } @Override protected void onPostExecute(AudioStream preferedAudioStream) { super.onPostExecute(preferedAudioStream); audioStream = preferedAudioStream; if(callback != null) { callback.run(); } } }.execute(); } private int getPreferredAudioStreamId(final List<AudioStream> audioStreams) { String preferredFormatString = PreferenceManager.getDefaultSharedPreferences(activity) .getString(activity.getString(R.string.default_audio_format_key), "webm"); int preferredFormat = MediaFormat.WEBMA.id; switch (preferredFormatString) { case "webm": preferredFormat = MediaFormat.WEBMA.id; break; case "m4a": preferredFormat = MediaFormat.M4A.id; break; default: break; } for (int i = 0; i < audioStreams.size(); i++) { if (audioStreams.get(i).format == preferredFormat) { Log.d(TAG, String.format("Preferred audio format found : %s with id : %d", preferredFormatString, preferredFormat)); return i; } } //todo: make this a proper error Log.e(TAG, "FAILED to set audioStream value, use the default value 0 !"); return 0; } public boolean hasLoadBitmap() { return hasLoadBitmap; } public boolean hasAudioStream() { return hasAudioStream; } public Intent retrieveIntent() { if (bitmap != null && audioStream != null) { ActivityCommunicator.getCommunicator().backgroundPlayerThumbnail = bitmap; final String mime = MediaFormat.getMimeById(audioStream.format); final Uri uri = Uri.parse(audioStream.url); final Intent intent = new Intent(activity, BackgroundPlayer.class); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(uri, mime); intent.putExtra(BackgroundPlayer.TITLE, info.title); intent.putExtra(BackgroundPlayer.WEB_URL, info.webpage_url); intent.putExtra(BackgroundPlayer.SERVICE_ID, info.service_id); intent.putExtra(PLAYLIST_ID, playListId); intent.putExtra(NewPipeSQLiteHelper.PLAYLIST_LINK_ENTRIES.POSITION, info.position); intent.putExtra(BackgroundPlayer.CHANNEL_NAME, info.uploader); return intent; } else { return null; } } public void process(final boolean forcePlay) { if (!BackgroundPlayer.isRunning || forcePlay) { if (bitmap != null && audioStream != null) { activity.startService(retrieveIntent()); } else if (!hasLoadBitmap) { retrieveBitmap(new Runnable() { @Override public void run() { process(forcePlay); } }); } else if (!hasAudioStream) { retrieveInfoFromService(new Runnable() { @Override public void run() { process(forcePlay); } }); } } } }
BlenderViking/NewPipe
app/src/main/java/org/schabi/newpipe/player/LunchAudioTrack.java
Java
gpl-3.0
10,189
#include "MD5.h" #include "string.h" namespace engine { namespace tools { using namespace std; /* Constants for MD5Transform routine. */ #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) /* ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { (a) += F ((b), (c), (d)) + (x) + ac; (a) = ROTATE_LEFT ((a), (s)); (a) += (b); } #define GG(a, b, c, d, x, s, ac) { (a) += G ((b), (c), (d)) + (x) + ac; (a) = ROTATE_LEFT ((a), (s)); (a) += (b); } #define HH(a, b, c, d, x, s, ac) { (a) += H ((b), (c), (d)) + (x) + ac; (a) = ROTATE_LEFT ((a), (s)); (a) += (b); } #define II(a, b, c, d, x, s, ac) { (a) += I ((b), (c), (d)) + (x) + ac; (a) = ROTATE_LEFT ((a), (s)); (a) += (b); } const byte MD5::PADDING[64] = { 0x80 }; const char MD5::HEX[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /* Default construct. */ MD5::MD5() { reset(); } /* Construct a MD5 object with a input buffer. */ MD5::MD5(const void* input, size_t length) { reset(); update(input, length); } /* Construct a MD5 object with a string. */ MD5::MD5(const string& str) { reset(); update(str); } /* Construct a MD5 object with a file. */ MD5::MD5(ifstream& in) { reset(); update(in); } /* Return the message-digest */ const Uuid MD5::digest() { if (!_finished) { _finished = true; final(); } return Uuid(_digest); } /* Reset the calculate state */ void MD5::reset() { _finished = false; /* reset number of bits. */ _count[0] = _count[1] = 0; /* Load magic initialization constants. */ _state[0] = 0x67452301; _state[1] = 0xefcdab89; _state[2] = 0x98badcfe; _state[3] = 0x10325476; } /* Updating the context with a input buffer. */ void MD5::update(const void* input, size_t length) { update((const byte*)input, length); } /* Updating the context with a string. */ void MD5::update(const string& str) { update((const byte*)str.c_str(), str.length()); } /* Updating the context with a file. */ void MD5::update(ifstream& in) { if (!in) { return; } std::streamsize length; char buffer[BUFFER_SIZE]; while (!in.eof()) { in.read(buffer, BUFFER_SIZE); length = in.gcount(); if (length > 0) { update(buffer, length); } } in.close(); } /* MD5 block update operation. Continues an MD5 message-digest operation, processing another message block, and updating the context. */ void MD5::update(const byte* input, size_t length) { uint32 i, index, partLen; _finished = false; /* Compute number of bytes mod 64 */ index = (uint32)((_count[0] >> 3) & 0x3f); /* update number of bits */ if ((_count[0] += ((uint32)length << 3)) < ((uint32)length << 3)) { ++_count[1]; } _count[1] += ((uint32)length >> 29); partLen = 64 - index; /* transform as many times as possible. */ if (length >= partLen) { memcpy(&_buffer[index], input, partLen); transform(_buffer); for (i = partLen; i + 63 < length; i += 64) { transform(&input[i]); } index = 0; } else { i = 0; } /* Buffer remaining input */ memcpy(&_buffer[index], &input[i], length - i); } /* MD5 finalization. Ends an MD5 message-_digest operation, writing the the message _digest and zeroizing the context. */ void MD5::final() { byte bits[8]; uint32 oldState[4]; uint32 oldCount[2]; uint32 index, padLen; /* Save current state and count. */ memcpy(oldState, _state, 16); memcpy(oldCount, _count, 8); /* Save number of bits */ encode(_count, bits, 8); /* Pad out to 56 mod 64. */ index = (uint32)((_count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); update(PADDING, padLen); /* Append length (before padding) */ update(bits, 8); /* Store state in digest */ encode(_state, _digest, 16); /* Restore current state and count. */ memcpy(_state, oldState, 16); memcpy(_count, oldCount, 8); } /* MD5 basic transformation. Transforms _state based on block. */ void MD5::transform(const byte block[64]) { uint32 a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16]; decode(block, x, 64); /* Round 1 */ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ _state[0] += a; _state[1] += b; _state[2] += c; _state[3] += d; } /* Encodes input (ulong) into output (byte). Assumes length is a multiple of 4. */ void MD5::encode(const uint32* input, byte* output, size_t length) { for (size_t i = 0, j = 0; j < length; ++i, j += 4) { output[j]= (byte)(input[i] & 0xff); output[j + 1] = (byte)((input[i] >> 8) & 0xff); output[j + 2] = (byte)((input[i] >> 16) & 0xff); output[j + 3] = (byte)((input[i] >> 24) & 0xff); } } /* Decodes input (byte) into output (ulong). Assumes length is a multiple of 4. */ void MD5::decode(const byte* input, uint32* output, size_t length) { for (size_t i = 0, j = 0; j < length; ++i, j += 4) { output[i] = ((uint32)input[j]) | (((uint32)input[j + 1]) << 8) | (((uint32)input[j + 2]) << 16) | (((uint32)input[j + 3]) << 24); } } /* Convert byte array to hex string. */ string MD5::bytesToHexString(const byte* input, size_t length) { string str; str.reserve(length << 1); for (size_t i = 0; i < length; ++i) { int t = input[i]; int a = t / 16; int b = t % 16; str.append(1, HEX[a]); str.append(1, HEX[b]); } return str; } } }
WusiStudio/Genesis
engine/common/tools/src/MD5.cpp
C++
gpl-3.0
13,017
package org.melodi.learning.service; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.melodi.tools.dataset.DataSet_Corpora; import org.melodi.tools.evaluation.Evaluation_Service; import opennlp.maxent.BasicEventStream; import opennlp.maxent.GIS; import opennlp.maxent.PlainTextByLineDataStream; import opennlp.model.AbstractModel; import opennlp.model.EventStream; public class Classifier_MaxEnt { AbstractModel model; public static double SMOOTHING_OBSERVATION = 0.1; public Classifier_MaxEnt() { } public AbstractModel train(FeatureGenerator_Service featureGen, int iteration, int cutoff, boolean USE_SMOOTHING, double value_smooth) throws IOException{ this.SMOOTHING_OBSERVATION = value_smooth; return this.train(featureGen,iteration,cutoff,USE_SMOOTHING); } public AbstractModel train(FeatureGenerator_Service featureGen, int iteration, int cutoff) throws IOException{ return this.train(featureGen,iteration,cutoff,false); } public AbstractModel train(FeatureGenerator_Service featureGen, int iteration) throws IOException{ return this.train(featureGen,iteration,0,false); } public AbstractModel train(FeatureGenerator_Service featureGen) throws IOException{ return this.train(featureGen,100,0,false); } public AbstractModel train(FeatureGenerator_Service featureGen, int iteration, int cutoff, boolean USE_SMOOTHING) throws IOException { // TODO : Utilisable mais améliorable sans passer par écriture/lecture! // TODO : Ecrire un vrai wrapper. featureGen.writeMaxEnt("dataset_train.txt"); FileReader datafr = new FileReader(new File("dataset_train.txt")); EventStream es = new BasicEventStream(new PlainTextByLineDataStream( datafr)); GIS.SMOOTHING_OBSERVATION = SMOOTHING_OBSERVATION; model = GIS.trainModel(es, iteration, cutoff, USE_SMOOTHING, true ); // Data Structures // datastructure[0] = model parameters // datastructure[1] = java.util.Map (mapping model predicate to unique integers) // datastructure[2] = java.lang.String[] names of outcomes // datastructure[3] = java.lang.integer : value of models correction constante // datastructure[4] = java.lang.Double : value of models correction paramter return model; } public Evaluation_Service predict(AbstractModel model, DataSet_Corpora corpora, FeatureGenerator_Service featureGen) { Evaluation_Service evaluator = new Evaluation_Service(); evaluator.setName("evaluator"); evaluator.setCorpora(corpora); for(PairUnit_Features currPair : featureGen){ predict(model, currPair); } return evaluator; } public void predict(AbstractModel model, PairUnit_Features currPair){ String predicates = ""; for(String currString : currPair.getFeatures()){ predicates += currString + " "; } String[] contexts = predicates.split(" "); double[] ocs = model.eval(contexts); currPair.getUnit().setPredict_y(model.getBestOutcome(ocs)); // System.out.println("For context: " + predicates+ "\n" + model.getAllOutcomes(ocs) + "\n"); } }
fauconnier/LaToe
src/org/melodi/learning/service/Classifier_MaxEnt.java
Java
gpl-3.0
3,139
""" IfExp astroid node An if statement written in an expression form. Attributes: - test (Node) - Holds a single node such as Compare. - Body (List[Node]) - A list of nodes that will execute if the condition passes. - orelse (List[Node]) - The else clause. Example: - test -> True - Body -> [x = 1] - orelse -> [0] """ x = 1 if True else 0
shweta97/pyta
nodes/IfExp.py
Python
gpl-3.0
406
var __v=[ { "Id": 2056, "Panel": 1052, "Name": "array", "Sort": 0, "Str": "" }, { "Id": 2057, "Panel": 1052, "Name": "相關接口", "Sort": 0, "Str": "" }, { "Id": 2058, "Panel": 1052, "Name": "Example", "Sort": 0, "Str": "" } ]
zuiwuchang/king-document
data/panels/1052.js
JavaScript
gpl-3.0
287
# -*- coding: utf-8 -*- import pilas archi = open('datos.txt', 'r') nivel = archi.readline() pantalla = archi.readline() idioma = archi.readline() archi.close() if idioma == "ES": from modulos.ES import * else: from modulos.EN import * class EscenaMenu(pilas.escena.Base): "Es la escena de presentación donde se elijen las opciones del juego." def __init__(self, musica=False): pilas.escena.Base.__init__(self) self.musica = musica def iniciar(self): pilas.fondos.Fondo("data/guarida.jpg") pilas.avisar(menu_aviso) self.crear_el_menu_principal() pilas.mundo.agregar_tarea(0.1, self.act) self.sonido = pilas.sonidos.cargar("data/menu.ogg") self.sonido.reproducir(repetir=True) def crear_el_menu_principal(self): opciones = [ (menu1, self.comenzar_a_jugar), (menu2, self.mostrar_ayuda_del_juego), (menu3, self.mostrar_historia), (menu4, self.mostrar_opciones), (menu5, self.salir_del_juego) ] self.trans = pilas.actores.Actor("data/trans.png") self.trans.x = -155 self.trans.arriba = 85 self.menu = pilas.actores.Menu(opciones, x=-150, y=70, color_normal= pilas.colores.negro, color_resaltado=pilas.colores.rojo) self.menu.x = -150 def act(self): if self.menu.x == -500: if self.donde == "jugar": self.sonido.detener() import escena_niveles pilas.cambiar_escena(escena_niveles.EscenaNiveles()) return False elif self.donde == "historia": self.sonido.detener() import escena_historia pilas.cambiar_escena(escena_historia.Historia()) elif self.donde == "ayuda": self.sonido.detener() import escena_ayuda pilas.cambiar_escena(escena_ayuda.Ayuda()) elif self.donde == "opciones": self.sonido.detener() import escena_opciones pilas.cambiar_escena(escena_opciones.Opciones()) return True def mostrar_historia(self): self.menu.x = [-500] self.trans.x = [-500] self.donde = "historia" def mostrar_opciones(self): self.menu.x = [-500] self.trans.x = [-500] self.donde = "opciones" def comenzar_a_jugar(self): self.menu.x = [-500] self.trans.x = [-500] self.donde = "jugar" def mostrar_ayuda_del_juego(self): self.menu.x = [-500] self.trans.x = [-500] self.donde = "ayuda" def salir_del_juego(self): pilas.terminar()
MendeleievBros/Mendeleiev-Bros
mendeleiev_bros/escena_menu.py
Python
gpl-3.0
2,716
#pragma once #include "common.hpp" namespace ccloutline { border_mat borders(const arma::mat&); } // namespace ccloutline
Thell/ccloutline
src/borders.hpp
C++
gpl-3.0
126
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # SSHplus # A remote connect utlity, sshmenu compatible clone, and application starter. # # (C) 2011 Anil Gulecha # Based on sshlist, incorporating changes by Benjamin Heil's simplestarter # # 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/>. # # Instructions # # 1. Copy file sshplus.py (this file) to /usr/local/bin # 2. Edit file .sshplus in your home directory to add menu entries, each # line in the format NAME|COMMAND|ARGS # 3. Launch sshplus.py # 4. Or better yet, add it to gnome startup programs list so it's run on login. import shlex import sys import notify2 import os import gi gi.require_version("AppIndicator3", "0.1") from gi.repository import AppIndicator3 gi.require_version("Gtk", "3.0") from gi.repository import Gtk _VERSION = "1.0" _SETTINGS_FILE = os.getenv("HOME") + "/.sshplus" _ABOUT_TXT = """A simple application starter as appindicator. To add items to the menu, edit the file <i>.sshplus</i> in your home directory. Each entry must be on a new line in this format: <tt>NAME|COMMAND|ARGS</tt> If the item is clicked in the menu, COMMAND with arguments ARGS will be executed. ARGS can be empty. To insert a separator, add a line which only contains "sep". Lines starting with "#" will be ignored. You can set an unclickable label with the prefix "label:". To insert a nested menu, use the prefix "folder:menu name". Subsequent items will be inserted in this menu, until a line containing an empty folder name is found: "folder:". After that, subsequent items get inserted in the parent menu. That means that more than one level of nested menus can be created. Example file: <tt><small> Show top|gnome-terminal|-x top sep # this is a comment label:SSH connections # create a folder named "Home" folder:Home SSH Ex|gnome-terminal|-x ssh user@1.2.3.4 # to mark the end of items inside "Home", specify and empty folder: folder: # this item appears in the main menu SSH Ex|gnome-terminal|-x ssh user@1.2.3.4 label:RDP connections RDP Ex|rdesktop|-T "RDP-Server" -r sound:local 1.2.3.4 </small></tt> Copyright 2011 Anil Gulecha Incorporating changes from simplestarter, Benjamin Heil, http://www.bheil.net Released under GPL3, http://www.gnu.org/licenses/gpl-3.0.html""" _EDIT_CONFIG = """To add items to the menu, edit the file <i>.sshplus</i> in your home directory. Each entry must be on a new line in this format: <tt>NAME|COMMAND|ARGS</tt> If the item is clicked in the menu, COMMAND with arguments ARGS will be executed. ARGS can be empty. To insert a separator, add a line which only contains "sep". Lines starting with "#" will be ignored. You can set an unclickable label with the prefix "label:". To insert a nested menu, use the prefix "folder:menu name". Subsequent items will be inserted in this menu, until a line containing an empty folder name is found: "folder:". After that, subsequent items get inserted in the parent menu. That means that more than one level of nested menus can be created. Example file: <tt><small> Show top|gnome-terminal|-x top sep # this is a comment label:SSH connections # create a folder named "Home" folder:Home SSH Ex|gnome-terminal|-x ssh user@1.2.3.4 # to mark the end of items inside "Home", specify and empty folder: folder: # this item appears in the main menu SSH Ex|gnome-terminal|-x ssh user@1.2.3.4 label:RDP connections RDP Ex|rdesktop|-T "RDP-Server" -r sound:local 1.2.3.4 </small></tt>""" def menuitem_response(w, item): if item == "_about": show_help_dlg(_ABOUT_TXT) elif item == "_edit": edit_config_file() elif item == "_refresh": newmenu = build_menu() ind.set_menu(newmenu) notify2.init("sshplus") notify2.Notification( "SSHplus refreshed", '"%s" has been read! Menu list was refreshed!' % _SETTINGS_FILE ).show() elif item == "_quit": sys.exit(0) elif item == "folder": pass else: print(item) os.spawnvp(os.P_NOWAIT, item["cmd"], [item["cmd"]] + item["args"]) os.wait3(os.WNOHANG) def show_help_dlg(msg, error=False): if error: dlg_icon = Gtk.MessageType.ERROR md = Gtk.MessageDialog( None, 0, dlg_icon, Gtk.ButtonsType.OK, "This is an INFO MessageDialog" ) edit_config_file() else: dlg_icon = Gtk.MessageType.INFO md = Gtk.MessageDialog( None, 0, dlg_icon, Gtk.ButtonsType.OK, "This is an INFO MessageDialog" ) try: md.set_markup("<b>SSHplus %s</b>" % _VERSION) md.format_secondary_markup(msg) md.run() finally: md.destroy() def edit_config_file(): if os.path.isfile(_SETTINGS_FILE) is not True: os.mknod(_SETTINGS_FILE) show_help_dlg( "<b>No <i>.sshplus</i> config file found, we created one for you!\n\nPlease edit the" " file and reload the config.</b>\n\n%s" % _EDIT_CONFIG, error=True, ) os.spawnvp(os.P_NOWAIT, "xdg-open", ["xdg-open", _SETTINGS_FILE]) os.wait3(os.WNOHANG) def add_separator(menu): separator = Gtk.SeparatorMenuItem() separator.show() menu.append(separator) def add_menu_item(menu, caption, item=None): menu_item = Gtk.MenuItem.new_with_label(caption) if item: menu_item.connect("activate", menuitem_response, item) else: menu_item.set_sensitive(False) menu_item.show() menu.append(menu_item) return menu_item def get_sshplusconfig(): if not os.path.exists(_SETTINGS_FILE): return [] app_list = [] f = open(_SETTINGS_FILE, "r") try: for line in f.readlines(): line = line.rstrip() if not line or line.startswith("#"): continue elif line == "sep": app_list.append("sep") elif line.startswith("label:"): app_list.append({"name": "LABEL", "cmd": line[6:], "args": ""}) elif line.startswith("folder:"): app_list.append({"name": "FOLDER", "cmd": line[7:], "args": ""}) else: try: name, cmd, args = line.split("|", 2) app_list.append( { "name": name, "cmd": cmd, "args": [n.replace("\n", "") for n in shlex.split(args)], } ) except ValueError: print("The following line has errors and will be ignored:\n%s" % line) finally: f.close() return app_list def build_menu(): if not os.path.exists(_SETTINGS_FILE): show_help_dlg( "<b>ERROR: No .sshmenu file found in home directory</b>\n\n%s" % _ABOUT_TXT, error=True ) sys.exit(1) app_list = get_sshplusconfig() menu = Gtk.Menu() menus = [menu] for app in app_list: if app == "sep": add_separator(menus[-1]) elif app["name"] == "FOLDER" and not app["cmd"]: if len(menus) > 1: menus.pop() elif app["name"] == "FOLDER": menu_item = add_menu_item(menus[-1], app["cmd"], "folder") menus.append(Gtk.Menu()) menu_item.set_submenu(menus[-1]) elif app["name"] == "LABEL": add_menu_item(menus[-1], app["cmd"], None) else: add_menu_item(menus[-1], app["name"], app) # Add SSHplus options folder to the end of the Menu add_separator(menu) menu_item = add_menu_item(menus[-1], "SSHplus Options", "folder") menus.append(Gtk.Menu()) menu_item.set_submenu(menus[-1]) add_menu_item(menus[-1], "Options", None) add_menu_item(menus[-1], "Edit", "_edit") add_menu_item(menus[-1], "Refresh", "_refresh") add_menu_item(menus[-1], "About", "_about") add_separator(menus[-1]) add_menu_item(menus[-1], "Quit", "_quit") menus.pop() return menu if __name__ == "__main__": ind = AppIndicator3.Indicator.new( "SSHplus", "utilities-terminal", AppIndicator3.IndicatorCategory.APPLICATION_STATUS ) ind.set_label("Launch", "none") ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE) if not os.path.exists(_SETTINGS_FILE): edit_config_file() appmenu = build_menu() ind.set_menu(appmenu) Gtk.main()
NoXPhasma/sshplus
sshplus.py
Python
gpl-3.0
9,010
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-09 11:32 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Company', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', django.contrib.postgres.fields.jsonb.JSONField(default={})), ('financial_data', django.contrib.postgres.fields.jsonb.JSONField(default={})), ('stock_data', django.contrib.postgres.fields.jsonb.JSONField(default={})), ], ), migrations.CreateModel( name='Exchange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', django.contrib.postgres.fields.jsonb.JSONField(default={})), ], ), migrations.CreateModel( name='News', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('source', models.URLField(max_length=255)), ('source_title', models.CharField(max_length=255)), ('companies', models.ManyToManyField(related_name='news', to='intellifin.Company')), ], ), migrations.AddField( model_name='company', name='exchange', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='companies', to='intellifin.Exchange'), ), ]
cw-intellineers/intellifin
intellifin/migrations/0001_initial.py
Python
gpl-3.0
2,024
/* Copyright (c) 2009 Sebastian Steiger, Integrated Systems Laboratory, ETH Zurich. Comments, suggestions, criticism or bug reports are welcome: steiger@purdue.edu. This file is part of ANGEL, a simulator for LEDs based on the NEGF formalism. The software is distributed under the Lesser GNU General Public License (LGPL). ANGEL is free software: you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License v3 or later. ANGEL is distributed without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. See also <http://www.gnu.org/licenses/>. */ #include "GreenFunctions.h" using namespace negf; GreenFunctions::GreenFunctions(const Options * options_, const Geometry * xspace_, const Kspace * kspace_, Energies * energies_, const Hamiltonian * ham_, const Overlap * ov_, bool mangle_overlap_calc_ /* true by default */) throw (Exception *): options(options_), xspace(xspace_), kspace(kspace_), energies(energies_), ov(ov_), ham(ham_), security_checking(true), mangle_overlap_calc(mangle_overlap_calc_) // if true, GL, GG, MGGM and MGLM will all be computed in calculate_lesser_greater {STACK_TRACE( logmsg->emit_header("setting up Green functions"); NEGF_ASSERT(options!=NULL && xspace!=NULL && kspace!=NULL && energies!=NULL && ov!=NULL, "null pointer encountered."); this->Nx = xspace->get_num_internal_vertices(); this->NxNn = Nx*Nn; // create GF for the energies of the calling process GR = new FullNEGFObject(xspace, kspace, energies, options); GA = new FullNEGFObject(xspace, kspace, energies, options); GL = new BandedNEGFObject(xspace, kspace, energies, options, constants::odGL); GG = new BandedNEGFObject(xspace, kspace, energies, options, constants::odGL); MGLM = new BandedNEGFObject(xspace, kspace, energies, options, constants::odGL); MGGM = new BandedNEGFObject(xspace, kspace, energies, options, constants::odGL); mpi->synchronize_processes(); );} GreenFunctions::~GreenFunctions() {STACK_TRACE( delete GR; delete GA; delete GL; delete GG; delete MGLM; delete MGGM; );} /** calculate the retarded GF using the Dyson equation for each k- and energy point */ void GreenFunctions::calculate_retarded(const SelfEnergy/*<odSE>*/ * SEtot) throw (Exception *) {STACK_TRACE( logmsg->emit_header("calculating GR"); uint Nk = kspace->get_number_of_points(); uint myNE = energies->get_my_number_of_points(); const OVMat & M = ov->get_internal_overlap(); NEGF_ASSERT(M.num_cols()==NxNn && M.num_rows()==M.num_cols(), "wrong overlap matrix."); // initialize helper matrices Matc Hsmall(Nx*Nn,Nx*Nn); OVMat EM = OVMat_create(NxNn); // small numerical parameter to make E a little bit complex // if omitted, NaN's will appear sometimes const double eta = constants::convert_from_SI(units::energy, constants::dyson_eta * constants::SIec); for (uint ee2 = 0; ee2 < myNE; ee2++) { uint ee = energies->get_global_index(ee2); mult(M, energies->get_energy_from_global_idx(ee)+eta, EM); // EM = (energies->get_energy_from_global_idx(ee)+eta) * M; if (ee % /*5*/10 == 0) logmsg->emit_noendl_all(LOG_INFO, "p%d: GR(E=%d,:)... ",mpi->get_rank(),ee); for (uint kk = 0; kk < Nk; kk++) { // get Hamiltonian of the interior points only, including electrostatic potential ham->get_internal(kspace->get_point(kk), Hsmall); NEGF_ASSERT(Hsmall.num_rows()==Nx*Nn, "something went wrong."); // get retarded GF and self-energy Matc & GRm = this->get_retarded(kk,ee); const SEMat & SigmaR = SEtot->get_retarded(kk,ee); // -------------------------- // solve Dyson equation // -------------------------- // assign GR = (E+eta)M - H - SigmaR GRm = SigmaR; GRm *= -1.0; GRm -= Hsmall; GRm += EM; // invert invert(GRm); } } // timing double time = timer->get_time(); uint slowest_process = constants::mpi_master_rank; string slowest_hostname = mpi->get_hostname(); if (mpi->get_rank()==constants::mpi_master_rank) { double max_time = time; for (int proc=0; proc < mpi->get_num_procs(); proc++) { if (proc==constants::mpi_master_rank) continue; int source = proc; double proc_time = 0.0; string proc_hostname; uint num_chars = 100; int tag = 832; mpi->recv(proc_time, source, tag); tag = 833; mpi->recv(proc_hostname, num_chars, source, tag); if (proc_time > max_time) { max_time = proc_time; slowest_process = proc; slowest_hostname = proc_hostname; } } // strip white spaces from hostname while (slowest_hostname[slowest_hostname.length()-1]==' ') { slowest_hostname.erase(slowest_hostname.length()-1); } } else { int dest = constants::mpi_master_rank; int tag = 832; mpi->send(time, dest, tag); string host = mpi->get_hostname(); host.resize(100, ' '); tag = 833; mpi->send(host, dest, tag); } mpi->synchronize_processes(); logmsg->emit(LOG_INFO, ""); if (mpi->get_rank()==constants::mpi_master_rank) logmsg->emit(LOG_INFO, "Process %d (%s) was slowest.",slowest_process, slowest_hostname.c_str()); );} /** calculate the advanced GF for each k- and own energy point */ void GreenFunctions::calculate_advanced() throw (Exception *) {STACK_TRACE( logmsg->emit_header("calculating GA"); uint Nk = kspace->get_number_of_points(); uint myNE = energies->get_my_number_of_points(); for (uint ee2 = 0; ee2 < myNE; ee2++) { uint ee = energies->get_global_index(ee2); for (uint kk = 0; kk < Nk; kk++) { const Matc & GRmat = this->get_retarded(kk,ee); Matc & GAmat = this->get_advanced(kk,ee); conjtrans(GRmat, GAmat); } } mpi->synchronize_processes(); );} /** calculate the lesser GF using the Keldysh equation for each k- and energy point */ void GreenFunctions::calculate_lesser_greater(const SelfEnergy/*<odSE>*/ * SEtot) throw (Exception *) {STACK_TRACE( if (!mangle_overlap_calc) { logmsg->emit_header("calculating GL and GG"); } else { logmsg->emit_header("calculating GL, M*GL*M, GG and M*GG*M"); } uint Nk = kspace->get_number_of_points(); uint myNE = energies->get_my_number_of_points(); const OVMat & M = ov->get_internal_overlap(); NEGF_ASSERT(M.num_cols()==NxNn && M.num_rows()==M.num_cols(), "wrong overlap matrix."); // initialize helper matrices Matc SLGA(NxNn,NxNn); // will store SL*GA Matc GLtmp(NxNn,NxNn); // will store the full GL Matc GLM(NxNn,NxNn); // will store GL*M Matc GGtmp(NxNn,NxNn); // will store the full GG Matc GGM(NxNn,NxNn); // will store GG*M for (uint ee2 = 0; ee2 < myNE; ee2++) { uint ee = energies->get_global_index(ee2); if (Nk==1) { if (ee % 20 == 0) logmsg->emit_noendl_all(LOG_INFO, "p%d: GL(E=%d,:)... ",mpi->get_rank(),ee); } else { if (ee % /*5*/10 == 0) logmsg->emit_noendl_all(LOG_INFO, "p%d: GL(E=%d,:)... ",mpi->get_rank(),ee); } for (uint kk = 0; kk < Nk; kk++) { // get Green's functions const Matc & GRm = this->get_retarded(kk,ee); const Matc & GAm = this->get_advanced(kk,ee); GLMat & GLm = this->get_lesser(kk,ee); GLMat & GGm = this->get_greater(kk,ee); // get lesser self-energy const SEMat & SLm = SEtot->get_lesser(kk,ee); // solve Keldysh equation (double multiplication is not supported) mult(SLm, GAm, SLGA); // SLGA = SL * GA; if (!mangle_overlap_calc) { mult(GRm, SLGA, GLm); // GL = GR * SLGA; GGm = GRm; GGm -= GAm; GGm += GLm; } else { // store full matrix GL in GLtmp mult(GRm, SLGA, GLtmp); GLm = GLtmp; // calculate overlap-augmented M*GL*M GLMat & MGLMm = this->get_overlap_augmented_lesser(kk,ee); mult(GLtmp, M, GLM); mult(M, GLM, MGLMm); // calculate the full GG (using the full GL) GGtmp = GRm; GGtmp -= GAm; GGtmp += GLtmp; GGm = GGtmp; // calculate M*GG*M GLMat & MGGMm = this->get_overlap_augmented_greater(kk,ee); mult(GGtmp, M, GGM); mult(M, GGM, MGGMm); } // anti-hermiticity check if (security_checking) { GLMat tmp = GLMat_create(NxNn); conjtrans(GLm, tmp); tmp += GLm; double tmp_norm = negf_math::matrix_norm(tmp); NEGF_FASSERT(tmp_norm < constants::antiherm_check, "InnerLoop: anti-hermiticity check of GL failed (delta=%e) : kk=%d, ee=%d=%.4g (ee2=%d)", tmp_norm, kk, ee, energies->get_energy_from_global_idx(ee), ee2); } } } mpi->synchronize_processes(); logmsg->emit(LOG_INFO, ""); );} /** calculate the lesser GF using the Keldysh equation for each k- and energy point */ void GreenFunctions::calculate_lesser(const SelfEnergy/*<odSE>*/ * SEtot) throw (Exception *) {STACK_TRACE( NEGF_ASSERT(!mangle_overlap_calc, "do not call this when GX and M*GX*M are calculated elsewhere"); logmsg->emit_header("calculating GL"); uint Nk = kspace->get_number_of_points(); uint myNE = energies->get_my_number_of_points(); // initialize helper matrices Matc SLGA(NxNn,NxNn); for (uint ee2 = 0; ee2 < myNE; ee2++) { uint ee = energies->get_global_index(ee2); if (Nk==1) { if (ee % 20 == 0) logmsg->emit_noendl_all(LOG_INFO, "p%d: GL(E=%d,:)... ",mpi->get_rank(),ee); } else { if (ee % 5 == 0) logmsg->emit_noendl_all(LOG_INFO, "p%d: GL(E=%d,:)... ",mpi->get_rank(),ee); } for (uint kk = 0; kk < Nk; kk++) { // get retarded and advanced GF const Matc & GRm = this->get_retarded(kk,ee); const Matc & GAm = this->get_advanced(kk,ee); // get lesser self-energy const SEMat & SLm = SEtot->get_lesser(kk,ee); // solve Keldysh equation (double multiplication is not supported) mult(SLm, GAm, SLGA); GLMat & GLm = this->get_lesser(kk,ee); mult(GRm, SLGA, GLm); // anti-hermiticity check if (security_checking) { GLMat tmp = GLMat_create(NxNn); conjtrans(GLm, tmp); tmp += GLm; double tmp_norm = negf_math::matrix_norm(tmp); NEGF_FASSERT(tmp_norm < constants::antiherm_check, "InnerLoop: anti-hermiticity check of GL failed (delta=%e) : kk=%d, ee=%d=%.4g (ee2=%d)", tmp_norm, kk, ee, energies->get_energy_from_global_idx(ee), ee2); } } } mpi->synchronize_processes(); logmsg->emit(LOG_INFO, ""); );} /** calculate the greater GF from GR, GR+ and G<: G> = GR - GA + G< */ void GreenFunctions::calculate_greater() throw (Exception *) {STACK_TRACE( NEGF_ASSERT(!mangle_overlap_calc, "do not call this when GX and M*GX*M are calculated elsewhere"); logmsg->emit_header("calculating GG"); uint Nk = kspace->get_number_of_points(); uint myNE = energies->get_my_number_of_points(); for (uint ee2 = 0; ee2 < myNE; ee2++) { uint ee = energies->get_global_index(ee2); logmsg->emit_noendl_all(LOG_INFO_L2, "p%d: GG(E=%d,k=:)... ",mpi->get_rank(),ee); for (uint kk = 0; kk < Nk; kk++) { const Matc & GRm = this->get_retarded(kk,ee); const Matc & GAm = this->get_advanced(kk,ee); const GLMat & GLm = this->get_lesser(kk,ee); GLMat & GGm = this->get_greater(kk,ee); GGm = GRm; GGm -= GAm; GGm += GLm; } } mpi->synchronize_processes(); );} void GreenFunctions::calculate_overlap_augmented_lesser() throw (Exception *) {STACK_TRACE( NEGF_ASSERT(!mangle_overlap_calc, "do not call this when GX and M*GX*M are calculated elsewhere"); logmsg->emit_header("calculating M*GL*M"); uint Nk = kspace->get_number_of_points(); uint myNE = energies->get_my_number_of_points(); const OVMat & M = ov->get_internal_overlap(); NEGF_ASSERT(M.num_cols()==NxNn && M.num_rows()==M.num_cols(), "wrong overlap matrix."); Matc tmp(NxNn,NxNn); for (uint ee2 = 0; ee2 < myNE; ee2++) { uint ee = energies->get_global_index(ee2); for (uint kk = 0; kk < Nk; kk++) { const GLMat & GLm = this->get_lesser(kk,ee); GLMat & MGLMm = this->get_overlap_augmented_lesser(kk,ee); // security check for anti-Hermiticity if (security_checking) { GLMat tmp2 = GLMat_create(NxNn); conjtrans(GLm,tmp2); tmp2 += GLm; double tmp_norm = negf_math::matrix_norm(tmp2); NEGF_FASSERT(tmp_norm < constants::antiherm_check, "GL was not anti-Hermitian: |GL - (-GL+)|=%e",tmp_norm); } mult(GLm, M, tmp); // tmp = GLmat * M; mult(BMatc, BMatc, Matc) mult(M,tmp,MGLMm); // MGLMmat = M * tmp; mult(BMatc, Matc, BMatc) // security check for anti-Hermiticity if (security_checking) { GLMat tmp2 = GLMat_create(NxNn); conjtrans(MGLMm, tmp2); tmp2 += MGLMm; double tmp_norm = negf_math::matrix_norm(tmp2); NEGF_FASSERT(tmp_norm < constants::antiherm_check, "MGLM was not anti-Hermitian: |MGLM - (-MGLM+)|=%e",tmp_norm); } } } mpi->synchronize_processes(); );} void GreenFunctions::calculate_overlap_augmented_greater() throw (Exception *) {STACK_TRACE( NEGF_ASSERT(!mangle_overlap_calc, "do not call this when GX and M*GX*M are calculated elsewhere"); logmsg->emit_header("calculating M*GG*M"); uint Nk = kspace->get_number_of_points(); uint myNE = energies->get_my_number_of_points(); const OVMat & M = ov->get_internal_overlap(); NEGF_ASSERT(M.num_cols()==NxNn && M.num_rows()==M.num_cols(), "wrong overlap matrix."); Matc tmp(NxNn,NxNn); for (uint ee2 = 0; ee2 < myNE; ee2++) { uint ee = energies->get_global_index(ee2); for (uint kk = 0; kk < Nk; kk++) { const GLMat & GGm = this->get_greater(kk,ee); GLMat & MGGMm = this->get_overlap_augmented_greater(kk,ee); mult(GGm, M, tmp); // tmp = GGmat * M; mult(BMatc, BMatc, Matc) mult(M, tmp, MGGMm); // MGGMmat = M * tmp; mult(BMatc, Matc, BMatc) } } mpi->synchronize_processes(); );} void GreenFunctions::interpolate_from_old_energies() throw (Exception *) {STACK_TRACE( const vector<double> & new_grid = this->energies->get_energy_grid(); const vector<double> & old_grid = this->energies->get_old_energy_grid(); NEGF_ASSERT(old_grid.size()==new_grid.size(), "inconsistent sizes of old and new energy grid."); uint nE = energies->get_number_of_points(); NEGF_ASSERT(new_grid.size()==nE, "inconsistent number of energy points."); // ------------------------------------------------------------------------------- // compute interpolation coefficients old-->new: // E_new[ii] = E1_coeff[ii] * E1_index[ii] + (1-E1_coeff[ii]) * E1_index[ii+1] // ------------------------------------------------------------------------------- vector<int> E1_index; E1_index.resize(nE, -2); vector<double> E1_coeff; E1_coeff.resize(nE, 0.0); for (uint ii=0; ii < nE; ii++) { double E = new_grid[ii]; if (E < old_grid[0] || E >= old_grid[nE-1]) { // >= is necessary s.th. idx<nE later; topmost energy should not be populated anyway // new energy is outside the old grid --> will assign zero E1_index[ii] = -1; E1_coeff[ii] = 0.0; continue; } // determine index of old energy grid which is just ABOVE energy E uint idx = 0; while(old_grid[idx] <= E) { idx++; NEGF_ASSERT(idx < nE, "something went wrong (idx>=nE)."); } NEGF_ASSERT(idx>0, "something went wrong (idx=0)."); // assign E1_index, E1_coeff E1_index[ii] = idx-1; double E1 = old_grid[idx-1]; double E2 = old_grid[idx]; NEGF_ASSERT(E>=E1 && E<=E2, "something went wrong (E1<=E<=E2)"); E1_coeff[ii] = (E2 - E) / (E2 - E1); // E = lambda*E1 + (1-lambda)*E2; lambda=0 --> E=E2, lambda=1 --> E=E1 } // security check if (security_checking) { uint Nk = kspace->get_number_of_points(); GLMat tmp = GLMat_create(NxNn); for (uint ee2=0; ee2<energies->get_my_number_of_points(); ee2++) { uint ee = energies->get_global_index(ee2); for (uint kk=0; kk < Nk; kk++) { const GLMat & GLm = this->get_lesser(kk,ee); conjtrans(GLm, tmp); // tmp = conjugateTranspose(GLm); tmp += GLm; double tmp_norm = negf_math::matrix_norm(tmp); NEGF_FASSERT(tmp_norm < constants::antiherm_check, "first anti-hermiticity check failed (delta=%e) : kk=%d, ee=%d=%.4g (ee2=%d)", tmp_norm, kk, ee, energies->get_energy_from_global_idx(ee), ee2); } } } // communicate GR and GL, then CALCULATE GA, GG, MGLM, MGGM! logmsg->emit_small_header("Interpolating GR"); Matc empty_full_matrix(NxNn,NxNn); this->interpolate_from_old_energies<FullNEGFObject, Matc>(this->get_retarded(), E1_index, E1_coeff, empty_full_matrix); mpi->synchronize_processes(); this->calculate_advanced(); logmsg->emit_small_header("Interpolating GL"); GLMat empty_GL_matrix = GLMat_create(NxNn); this->interpolate_from_old_energies<GL_object_type, GLMat>(this->get_lesser(), E1_index, E1_coeff, empty_GL_matrix); mpi->synchronize_processes(); if (!mangle_overlap_calc) { this->calculate_greater(); if (kspace->get_number_of_points()!=1) { // we don't need MGLM and MGGM in that case --> save time this->calculate_overlap_augmented_lesser(); this->calculate_overlap_augmented_greater(); } } else { logmsg->emit_small_header("Interpolating GG"); this->interpolate_from_old_energies<GL_object_type, GLMat>(this->get_greater(), E1_index, E1_coeff, empty_GL_matrix); mpi->synchronize_processes(); if (kspace->get_number_of_points()!=1) { // we don't need MGLM and MGGM in that case --> save time logmsg->emit_small_header("Interpolating M*GL*M"); this->interpolate_from_old_energies<GL_object_type, GLMat>(this->get_overlap_augmented_lesser(), E1_index, E1_coeff, empty_GL_matrix); mpi->synchronize_processes(); logmsg->emit_small_header("Interpolating M*GG*M"); this->interpolate_from_old_energies<GL_object_type, GLMat>(this->get_overlap_augmented_greater(), E1_index, E1_coeff, empty_GL_matrix); mpi->synchronize_processes(); } } // security check if (security_checking) { uint Nk = kspace->get_number_of_points(); GLMat tmp = GLMat_create(NxNn); for (uint ee2=0; ee2<energies->get_my_number_of_points(); ee2++) { uint ee = energies->get_global_index(ee2); for (uint kk=0; kk < Nk; kk++) { const GLMat & GLm = this->get_lesser(kk,ee); conjtrans(GLm, tmp); // tmp = conjugateTranspose(GLm); tmp += GLm; double tmp_norm = negf_math::matrix_norm(tmp); NEGF_FASSERT(tmp_norm < constants::antiherm_check, "second anti-hermiticity check failed (delta=%e) : kk=%d, ee=%d=%.4g (ee2=%d)", tmp_norm, kk, ee, energies->get_energy_from_global_idx(ee), ee2); } } } );} /** determine the linear interpolation E = a*E_i + (1-a)*E_{i+1}, E_i<=E<E_i+1 */ void GreenFunctions::get_interpol_coeffs(vector<uint> & indices, vector<double> & coeffs, const double & E) const {STACK_TRACE( uint nE = energies->get_number_of_points(); indices.clear(); coeffs.clear(); // determine the highest index below Elow uint E0idx = nE-1; while (E0idx > 0 && energies->get_energy_from_global_idx(E0idx) > E) { E0idx--; } double E0 = energies->get_energy_from_global_idx(E0idx); if (E0idx==nE-1 || E0>E) { // E lies outside computed range return; } double E1 = energies->get_energy_from_global_idx(E0idx+1); indices.resize(2, 0); indices[0] = E0idx; indices[1] = E0idx + 1; coeffs.resize(2, 0.0); coeffs[0] = 1.0 - (E-E0)/(E1-E0); coeffs[1] = (E-E0)/(E1-E0); // E=E0 --> coeffs[0] = 1 , coeffs[1] = 0 //coeffs[0] = 0.5; //coeffs[1] = 0.5; return; );} /** determine the coefficients c_i of * * 1/(Eupp-Elow) * int_Elow^Eupp f(E)dE ~ sum_i c_i f(Ei) * * to do so, we assume that f behaves linearly between the enbergy grid points * */ void GreenFunctions::get_interpol_coeffs(vector<uint> & indices, vector<double> & coeffs, const double & Elow, const double & Eupp) const {STACK_TRACE( NEGF_FASSERT(fabs(Eupp-Elow)>1e-15, "Elow=Eupp=%.5e are identical! Will yield nan coefficients.", Elow); uint nE = energies->get_number_of_points(); indices.clear(); coeffs.clear(); // determine the highest index below Elow uint E0idx = nE-1; while (E0idx > 0 && energies->get_energy_from_global_idx(E0idx) > Elow) { E0idx--; } // determine the lowest index above Eupp uint Enidx = 0; while (Enidx < nE-1 && energies->get_energy_from_global_idx(Enidx) < Eupp) { Enidx++; } // if Elow, Eupp are outside the energy range, we're done if (E0idx >= Enidx) { return; } // set up indices array (containing global energy indices) for (uint ii=E0idx; ii<=Enidx; ii++) { indices.push_back(ii); } // ---------------------- // find coefficients // ---------------------- const bool use_lumped_scheme = false; coeffs.resize(indices.size(), 0.0); uint NE = energies->get_number_of_points(); for (uint ii=0; ii<indices.size(); ii++) { // boundaries of interval belonging to energy grid point indices[ii] //double Ilow = (indices[ii]>0) ? energies->get_energy_from_global_idx(indices[ii]-1) : energies->get_energy_from_global_idx(indices[ii]); //double Iupp = (indices[ii]<NE-1) ? energies->get_energy_from_global_idx(indices[ii]+1) : energies->get_energy_from_global_idx(indices[ii]); // <ss 8.6.2010> was wrong! double E1 = energies->get_energy_from_global_idx(indices[ii]); double E0 = (indices[ii]>0 ) ? energies->get_energy_from_global_idx(indices[ii]-1) : E1; double E2 = (indices[ii]<NE-1) ? energies->get_energy_from_global_idx(indices[ii]+1) : E1; double Ilow = (E0+E1)/2; double Iupp = (E1+E2)/2; //if (indices[ii]<20) logmsg->emit(LOG_INFO,"indices[%d]=%d, E=%g", ii, indices[ii], E1); // determine the length of interval [Elow,Eupp] which is contained in [Ilow,Iupp] if (Ilow >= Eupp || Iupp <= Elow) { coeffs[ii] = 0.0; } else if (Ilow >= Elow && Iupp <= Eupp) { coeffs[ii] = Iupp - Ilow; } else if (Ilow <= Elow && Iupp >= Eupp) { coeffs[ii] = Eupp - Elow; } else if (Ilow >= Elow && Iupp >= Eupp) { coeffs[ii] = Eupp - Ilow; } else if (Ilow <= Elow && Iupp <= Eupp) { coeffs[ii] = Iupp - Elow; } else { NEGF_FEXCEPTION("We forgot a case: Elow=%e, Eupp=%e, Ilow=%e, Iupp=%e", Elow, Eupp, Ilow, Iupp); } } // take away points with coefficient ~0 vector<uint> indices_old = indices; vector<double> coeffs_old = coeffs; indices.clear(); coeffs.clear(); for (uint ii=0; ii<indices_old.size(); ii++) { if (fabs(coeffs_old[ii])>1e-14) { indices.push_back(indices_old[ii]); coeffs .push_back(coeffs_old[ii]); } } // DIVIDE ALL BY Eupp-Elow double simulated_interval = Eupp-Elow; for (uint ii=0; ii<coeffs.size(); ii++) { double E0 = energies->get_energy_from_global_idx(0); if (Elow<E0) { simulated_interval = Eupp-E0; } double EN = energies->get_energy_from_global_idx(energies->get_number_of_points()-1); if (Eupp>EN) { simulated_interval = EN-Elow; } coeffs[ii] = coeffs[ii] / simulated_interval; NEGF_FASSERT(!isnan(coeffs[ii]) && !isinf(coeffs[ii]), "Elow=%.3e, Eupp=%.3e: indices[%d]=%d, coeffs[%d]=%.3e", Elow,Eupp,ii,indices[ii],ii,coeffs[ii]); } // security checks // check that the function '1' interpolated gives 1 if (security_checking) { double check = 0.0; for (uint ii=0; ii<coeffs.size(); ii++) { if (coeffs[ii]<-1e-14) { logmsg->emit_all(LOG_ERROR,"Elow=%e, Eupp=%e, E0idx=%d(E=%e), Enidx=%d(E=%e)", Elow,Eupp,E0idx,energies->get_energy_from_global_idx(E0idx),Enidx,energies->get_energy_from_global_idx(Enidx)); for (uint jj=0; jj<coeffs.size(); jj++) { logmsg->emit_all(LOG_ERROR," coeffs[%d]=%.10e",jj,coeffs[jj]); } NEGF_FEXCEPTION("negative coefficient (%.10e) encountered.", coeffs[ii]); } check += coeffs[ii]; } NEGF_FASSERT(fabs(check - 1.0) < 1e-12, "check failed: check=%e, Elow=%g, Eupp=%g, Eupp-Elow=%e, indices.size()=%d.",check,Elow,Eupp,Eupp-Elow, indices.size()); } return; );} void GreenFunctions::assign_flat_band_lesser_greater(double EFn, double EFp, double Ec, double Ev) throw (Exception *) {STACK_TRACE( uint Nk = kspace->get_number_of_points(); uint myNE = energies->get_my_number_of_points(); NEGF_ASSERT(Nn==2, "need 2 DOFs!"); NEGF_ASSERT(fabs(options->get("kp_method")-3.0)<1e-10, "need kpmethod=3!"); const double hbar = constants::convert_from_SI(units::hbar, constants::SIhbar); const double me = constants::convert_from_SI(units::mass, 0.067 * constants::SIm0); const double mh = constants::convert_from_SI(units::mass, 0.500 * constants::SIm0); const double kT = constants::convert_from_SI(units::energy, constants::SIec * 0.02585); vector<double> V; V.resize(Nx, 0.0); double V_left = 0.0; double V_right = -0.3; for (uint xx=0; xx<Nx; xx++) { V[xx] = V_left + (V_right-V_left)/(Nx-1) * xx; } uint xx_left = Nx / 3; // integer division uint xx_right = 2 * Nx / 3; // integer division for (uint ee2 = 0; ee2 < myNE; ee2++) { uint ee = energies->get_global_index(ee2); double E = energies->get_energy_from_global_idx(ee); for (uint kk = 0; kk < Nk; kk++) { double k = kspace->get_point(kk).get_coord_abs(); double Eke = hbar*hbar*k*k / (2.0*me); double Ekh = hbar*hbar*k*k / (2.0*mh); GLMat & GLm = this->get_lesser(kk,ee); GLMat & GGm = this->get_greater(kk,ee); GLm = GLMat_create(NxNn); // initialize to zero GGm = GLMat_create(NxNn); for (uint xx=xx_left; xx<=xx_right; xx++) { double dx = 0.0; if (constants::old_orthogonal) { dx = 1.0; } else { const vector<Element *> elems_near_x = xspace->get_elems_near(xspace->get_vertex(xx-1)); for (uint ii=0; ii<elems_near_x.size(); ii++) { dx += elems_near_x[ii]->get_edge(0)->get_length(); } } double Ec_plus_V = Ec + V[xx]; double Ev_plus_V = Ev + V[xx]; double fn = 1.0 / (1.0 + negf_math::exp((E-Ec_plus_V)/kT)); // spatially varying Fermilevel double fp = 1.0 / (1.0 + negf_math::exp((E-Ev_plus_V)/kT)); double rho_CB = 0.0; if (E > Ec_plus_V+Eke) { rho_CB = 1.0 / negf_math::sqrt(E - (Ec_plus_V+Eke)); } // spatially varying DOS double rho_VB = 0.0; if (E < Ev_plus_V-Ekh) { rho_VB = 1.0 / negf_math::sqrt((Ev_plus_V-Ekh) - E); } Matc GLpart(2,2); GLpart(1,1) = constants::imag_unit * fn * rho_CB / dx; GLpart(2,2) = constants::imag_unit * fp * rho_VB / dx; GLm.fill_block(xx,xx, GLpart, Nx); Matc GGpart(2,2); GGpart(1,1) = -constants::imag_unit * (1.0-fn) * rho_CB / dx; GGpart(2,2) = -constants::imag_unit * (1.0-fp) * rho_VB / dx; GGm.fill_block(xx,xx, GGpart, Nx); } } } // security check if (security_checking) { GLMat tmp = GLMat_create(NxNn); for (uint ee2=0; ee2<energies->get_my_number_of_points(); ee2++) { uint ee = energies->get_global_index(ee2); for (uint kk=0; kk < Nk; kk++) { const GLMat & GLm = this->get_lesser(kk,ee); conjtrans(GLm, tmp); tmp += GLm; double tmp_norm = negf_math::matrix_norm(tmp); NEGF_FASSERT(tmp_norm < constants::antiherm_check, "anti-hermiticity check failed for GL (delta=%e) : kk=%d, ee=%d=%.4g (ee2=%d)", tmp_norm, kk, ee, energies->get_energy_from_global_idx(ee), ee2); const GLMat & GGm = this->get_greater(kk,ee); conjtrans(GGm, tmp); tmp += GGm; tmp_norm = negf_math::matrix_norm(tmp); NEGF_FASSERT(tmp_norm < constants::antiherm_check, "anti-hermiticity check failed for GG (delta=%e) : kk=%d, ee=%d=%.4g (ee2=%d)", tmp_norm, kk, ee, energies->get_energy_from_global_idx(ee), ee2); } } } mpi->synchronize_processes(); );}
XSZHOU/negf-reference
src/negf/GreenFunctions.cpp
C++
gpl-3.0
27,272
# Copyright 2016 Mycroft AI, Inc. # # This file is part of Mycroft Core. # # Mycroft Core 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. # # Mycroft Core 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 Mycroft Core. If not, see <http://www.gnu.org/licenses/>. from threading import Thread from time import sleep import random from adapt.intent import IntentBuilder from mycroft.messagebus.message import Message from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService from mycroft.skills.core import MycroftSkill from mycroft.util.log import getLogger __author__ = 'jarbas' logger = getLogger(__name__) class LILACSChatbotSkill(MycroftSkill): # https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19 def __init__(self): super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill") # initialize your variables self.reload_skill = False self.active = True self.parser = None self.service = None self.TIMEOUT = 2 def initialize(self): # register intents self.parser = LILACSQuestionParser() self.service = KnowledgeService(self.emitter) self.build_intents() # make thread to keep active self.make_bump_thread() def ping(self): while True: i = 0 if self.active: self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill", "utterances": [ "bump chat to active skill list"]})) while i < 60 * self.TIMEOUT: i += 1 sleep(1) i = 0 def make_bump_thread(self): timer_thread = Thread(target=self.ping) timer_thread.setDaemon(True) timer_thread.start() def build_intents(self): # build intents deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \ .require("deactivateChatBotKeyword").build() activate_intent=IntentBuilder("ActivateChatbotIntent") \ .require("activateChatBotKeyword").build() bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \ require("bumpChatBotKeyword").build() # register intents self.register_intent(deactivate_intent, self.handle_deactivate_intent) self.register_intent(activate_intent, self.handle_activate_intent) self.register_intent(bump_intent, self.handle_set_on_top_active_list()) def handle_set_on_top_active_list(self): # dummy intent just to bump curiosity skill to top of active skill list # called on a timer in order to always use converse method pass def handle_deactivate_intent(self, message): self.active = False self.speak_dialog("chatbot_off") def handle_activate_intent(self, message): self.active = True self.speak_dialog("chatbot_on") def stop(self): self.handle_deactivate_intent("global stop") def converse(self, transcript, lang="en-us"): # parse 1st utterance for entitys if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]: nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0]) self.log.info("nodes: " + str(nodes)) self.log.info("parents: " + str(parents)) self.log.info("synonims: " + str(synonims)) # get concept net , talk possible_responses = [] for node in nodes: try: dict = self.service.adquire(node, "concept net") usages = dict["concept net"]["surfaceText"] for usage in usages: possible_responses.append(usage.replace("[", "").replace("]", "")) except: self.log.info("could not get reply for node " + node) try: # say something random reply = random.choice(possible_responses) self.speak(reply) return True except: self.log.error("Could not get chatbot response for: " + transcript[0]) # dont know what to say # TODO ask user a question and play du,mb return False # tell intent skill you did not handle intent return False def create_skill(): return LILACSChatbotSkill()
ElliotTheRobot/LILACS-mycroft-core
mycroft/skills/LILACS_chatbot/__init__.py
Python
gpl-3.0
5,092
# -*- coding: utf-8 -*- # This file is part of Gertrude. # # Gertrude 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. # # Gertrude 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 Gertrude; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from __future__ import print_function from builtins import str as text import traceback import subprocess import wx import wx.lib.filebrowsebutton from ooffice import * class DocumentDialog(wx.Dialog): def __init__(self, parent, modifications): self.modifications = modifications self.document_generated = False # Instead of calling wx.Dialog.__init__ we precreate the dialog # so we can set an extra style that must be set before # creation, and then we create the GUI object using the Create # method. pre = wx.PreDialog() pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP) pre.Create(parent, -1, "Génération de document") # This next step is the most important, it turns this Python # object into the real wrapper of the dialog (instead of pre) # as far as the wxPython extension is concerned. self.PostCreate(pre) self.sizer = wx.BoxSizer(wx.VERTICAL) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.StaticText(self, -1, "Format :"), 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) if not IsOODocument(modifications.template): self.format = wx.Choice(self, -1, choices=["Texte"]) elif sys.platform == 'win32': self.format = wx.Choice(self, -1, choices=["LibreOffice", "PDF"]) else: self.format = wx.Choice(self, -1, choices=["LibreOffice"]) self.format.SetSelection(0) self.Bind(wx.EVT_CHOICE, self.onFormat, self.format) sizer.Add(self.format, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) default_output = normalize_filename(modifications.default_output) self.extension = os.path.splitext(default_output)[-1] wildcard = "OpenDocument (*%s)|*%s|PDF files (*.pdf)|*.pdf" % (self.extension, self.extension) self.fbb = wx.lib.filebrowsebutton.FileBrowseButton(self, -1, size=(600, -1), labelText="Nom de fichier :", startDirectory=config.documents_directory, initialValue=os.path.join(config.documents_directory, default_output), fileMask=wildcard, fileMode=wx.SAVE) sizer.Add(self.fbb, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5) self.sizer.Add(sizer, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.gauge = wx.Gauge(self, -1, size=(-1, 10)) self.gauge.SetRange(100) self.sizer.Add(self.gauge, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT | wx.TOP, 5) line = wx.StaticLine(self, -1, size=(20, -1), style=wx.LI_HORIZONTAL) self.sizer.Add(line, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, 5) sizer = wx.BoxSizer(wx.HORIZONTAL) self.sauver_ouvrir = wx.Button(self, -1, "Sauver et ouvrir") self.sauver_ouvrir.SetDefault() self.Bind(wx.EVT_BUTTON, self.OnSauverOuvrir, self.sauver_ouvrir) sizer.Add(self.sauver_ouvrir, 0, wx.LEFT | wx.RIGHT, 5) self.sauver = wx.Button(self, -1, "Sauver") self.Bind(wx.EVT_BUTTON, self.OnSauver, self.sauver) sizer.Add(self.sauver, 0, wx.RIGHT, 5) if modifications.multi: button = wx.Button(self, -1, "Sauver individuellement") self.Bind(wx.EVT_BUTTON, self.OnSauverUnitaire, button) sizer.Add(button, 0, wx.RIGHT, 5) if modifications.email: self.sauver_envoyer = wx.Button(self, -1, "Sauver et envoyer par email") self.Bind(wx.EVT_BUTTON, self.OnSauverEnvoyer, self.sauver_envoyer) sizer.Add(self.sauver_envoyer, 0, wx.RIGHT, 5) if modifications.multi is False and not modifications.email_to: self.sauver_envoyer.Disable() if database.creche.caf_email: self.sauver_envoyer = wx.Button(self, -1, "Sauver et envoyer par email à la CAF") self.Bind(wx.EVT_BUTTON, self.OnSauverEnvoyerCAF, self.sauver_envoyer) sizer.Add(self.sauver_envoyer, 0, wx.LEFT | wx.RIGHT, 5) # btnsizer.Add(self.ok) btn = wx.Button(self, wx.ID_CANCEL) sizer.Add(btn, 0, wx.RIGHT, 5) self.sizer.Add(sizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.SetSizer(self.sizer) self.sizer.Fit(self) self.CenterOnScreen() def onFormat(self, _): filename = os.path.splitext(self.fbb.GetValue())[0] if self.format.GetSelection() == 0: self.fbb.SetValue(filename + self.extension, None) else: self.fbb.SetValue(filename + ".pdf", None) def Sauver(self): self.fbb.Disable() self.sauver.Disable() if self.sauver_ouvrir: self.sauver_ouvrir.Disable() self.filename = self.fbb.GetValue() f, e = os.path.splitext(self.filename) if e == ".pdf": self.pdf = True self.oo_filename = f + self.extension else: self.pdf = False self.oo_filename = self.filename config.documents_directory = os.path.dirname(self.filename) dlg = None try: if self.modifications.multi is not False: errors = {} simple_modifications = self.modifications.get_simple_modifications(self.oo_filename) for i, (filename, modifs) in enumerate(simple_modifications): self.gauge.SetValue((100 * i) / len(simple_modifications)) errors.update(GenerateDocument(modifs, filename=filename)) if self.pdf: f, e = os.path.splitext(filename) convert_to_pdf(filename, f + ".pdf") os.remove(filename) else: self.filename = self.filename.replace(" <prenom> <nom>", "") self.oo_filename = self.oo_filename.replace(" <prenom> <nom>", "") errors = GenerateDocument(self.modifications, filename=self.oo_filename, gauge=self.gauge) if self.pdf: convert_to_pdf(self.oo_filename, self.filename) os.remove(self.oo_filename) self.document_generated = True if errors: message = "Document %s généré avec des erreurs :\n" % self.filename for label in errors.keys(): message += '\n' + label + ' :\n ' message += '\n '.join(errors[label]) dlg = wx.MessageDialog(self, message, 'Message', wx.OK | wx.ICON_WARNING) except IOError: print(sys.exc_info()) dlg = wx.MessageDialog(self, "Impossible de sauver le document. Peut-être est-il déjà ouvert ?", 'Erreur', wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() return except Exception as e: info = sys.exc_info() message = ' [type: %s value: %s traceback: %s]' % (info[0], info[1], traceback.extract_tb(info[2])) dlg = wx.MessageDialog(self, message, 'Erreur', wx.OK | wx.ICON_WARNING) if dlg: dlg.ShowModal() dlg.Destroy() self.EndModal(wx.ID_OK) def OnSauver(self, _): self.modifications.multi = False self.Sauver() def OnSauverOuvrir(self, event): self.OnSauver(event) if self.document_generated: if self.filename.endswith(".pdf"): StartAcrobatReader(self.filename) else: StartLibreOffice(self.filename) def OnSauverUnitaire(self, _): self.Sauver() def OnSauverEnvoyer(self, event): self.OnSauverUnitaire(event) if self.document_generated: if self.modifications.multi is not False: simple_modifications = self.modifications.get_simple_modifications(self.oo_filename) emails = '\n'.join( [" - %s (%s)" % (modifs.email_subject, ", ".join(modifs.email_to)) for filename, modifs in simple_modifications]) if len(emails) > 1000: emails = emails[:1000] + "\n..." dlg = wx.MessageDialog(self, "Ces emails seront envoyés :\n" + emails, 'Confirmation', wx.OK | wx.CANCEL | wx.ICON_WARNING) response = dlg.ShowModal() dlg.Destroy() if response != wx.ID_OK: return for filename, modifs in simple_modifications: if self.pdf: oo_filename = filename filename, e = os.path.splitext(oo_filename) filename += ".pdf" try: SendDocument(filename, modifs) except Exception as e: dlg = wx.MessageDialog(self, "Impossible d'envoyer le document %s\n%r" % (filename, e), 'Erreur', wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() else: try: SendDocument(self.filename, self.modifications) except Exception as e: dlg = wx.MessageDialog(self, "Impossible d'envoyer le document %s\n%r" % (self.filename, e), 'Erreur', wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() def OnSauverEnvoyerCAF(self, event): self.OnSauver(event) if self.document_generated: try: root, ext = os.path.splitext(self.modifications.introduction_filename) introduction_filename = root + " CAF" + ext SendDocument(self.filename, self.modifications, to=[database.creche.caf_email], introduction_filename=GetTemplateFile(introduction_filename)) except Exception as e: dlg = wx.MessageDialog(self, "Impossible d'envoyer le document %s\n%r" % (self.filename, e), "Erreur", wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() def StartLibreOffice(filename): if sys.platform == 'win32': filename = "".join(["file:", urllib.pathname2url(os.path.abspath(filename.encode("utf-8")))]) # print filename try: StarDesktop, objServiceManager, core_reflection = getOOoContext() StarDesktop.LoadComponentFromURL(filename, "_blank", 0, MakePropertyValues(objServiceManager, [ ["ReadOnly", False], ["Hidden", False]])) except Exception as e: print("Exception ouverture LibreOffice", e) dlg = wx.MessageDialog(None, "Impossible d'ouvrir le document\n%r" % e, "Erreur", wx.OK|wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() else: paths = [] if sys.platform == "darwin": paths.append("/Applications/LibreOffice.app/Contents/MacOS/soffice") paths.append("/Applications/OpenOffice.app/Contents/MacOS/soffice") else: paths.append("/usr/bin/libreoffice") paths.append("ooffice") for path in paths: try: print(path, filename) subprocess.Popen([path, filename]) return except Exception as e: print(e) pass dlg = wx.MessageDialog(None, "Impossible de lancer OpenOffice / LibreOffice", 'Erreur', wx.OK|wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() DDE_ACROBAT_STRINGS = ["AcroviewR15", "AcroviewA15", "AcroviewR12", "AcroviewA12", "AcroviewR11", "AcroviewA11", "AcroviewR10", "AcroviewA10", "acroview"] dde_server = None def StartAcrobatReader(filename): global dde_server import win32api import win32ui import dde filename = str(os.path.abspath(filename)) path, name = os.path.split(filename) reader = win32api.FindExecutable(name, path) os.spawnl(os.P_NOWAIT, reader[1], " ") for t in range(10): time.sleep(1) for acrobat in DDE_ACROBAT_STRINGS: try: if not dde_server: dde_server = dde.CreateServer() dde_server.Create('Gertrude') c = dde.CreateConversation(dde_server) c.ConnectTo(acrobat, 'control') c.Exec('[DocOpen("%s")]' % (filename,)) return except Exception as e: pass print("Impossible de lancer acrobat reader ; prochain essai dans 1s ...", e) dlg = wx.MessageDialog(None, "Impossible d'ouvrir le document", 'Erreur', wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy()
studio1247/gertrude
document_dialog.py
Python
gpl-3.0
13,966
from ..rerequest import TemplateRequest init_req = TemplateRequest( re = r'(http://)?(www\.)?(?P<domain>ur(play)?)\.se/(?P<req_url>.+)', encode_vars = lambda v: { 'req_url': 'http://%(domain)s.se/%(req_url)s' % v } ) hls = { 'title': 'UR-play', 'url': 'http://urplay.se/', 'feed_url': 'http://urplay.se/rss', 'items': [init_req, TemplateRequest( re = r'file_html5":\s?"(?P<final_url>[^"]+)".*?"subtitles":\s?"(?P<subtitles>[^",]*)', encode_vars = lambda v: { 'final_url': ('http://130.242.59.75/%(final_url)s/playlist.m3u8' % v).replace('\\', ''), 'suffix-hint': 'mp4', 'subtitles': v.get('subtitles', '').replace('\\', '') % v } )] } rtmp = { 'items': [init_req, TemplateRequest( re = r'file_flash":\s?"(?P<final_url>[^"]+\.(?P<ext>mp[34]))".*?"subtitles":\s?"(?P<subtitles>[^",]*)', encode_vars = lambda v: { 'final_url': ('rtmp://130.242.59.75/ondemand playpath=%(ext)s:/%(final_url)s app=ondemand' % v).replace('\\', ''), 'suffix-hint': 'flv', 'rtmpdump-realtime': True, 'subtitles': v.get('subtitles', '').replace('\\', '') % v } )] } services = [hls, rtmp]
jackuess/pirateplay.se
lib/pirateplay/lib/services/ur.py
Python
gpl-3.0
1,161
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. */ import Reflux from 'reflux'; import URLUtils from 'util/URLUtils'; import ApiRoutes from 'routing/ApiRoutes'; import fetch from 'logic/rest/FetchProvider'; import MessageFormatter from 'logic/message/MessageFormatter'; import ObjectUtils from 'util/ObjectUtils'; import CombinedProvider from 'injection/CombinedProvider'; const { SimulatorActions } = CombinedProvider.get('Simulator'); const SimulatorStore = Reflux.createStore({ listenables: [SimulatorActions], simulate(stream, messageFields, inputId) { const url = URLUtils.qualifyUrl(ApiRoutes.SimulatorController.simulate().url); const simulation = { stream_id: stream.id, message: messageFields, input_id: inputId, }; let promise = fetch('POST', url, simulation); promise = promise.then((response) => { const formattedResponse = ObjectUtils.clone(response); formattedResponse.messages = response.messages.map((msg) => MessageFormatter.formatMessageSummary(msg)); return formattedResponse; }); SimulatorActions.simulate.promise(promise); }, }); export default SimulatorStore;
Graylog2/graylog2-server
graylog2-web-interface/src/stores/simulator/SimulatorStore.js
JavaScript
gpl-3.0
1,756
/******************************************************************************* * Copyright (C) 2010 Lucas Madar and Peter Brewer * * 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: * Lucas Madar * Peter Brewer ******************************************************************************/ package org.tellervo.desktop.hardware.device; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tellervo.desktop.admin.model.GroupsWithPermissionsTableModel; import org.tellervo.desktop.hardware.AbstractMeasuringDevice; import org.tellervo.desktop.hardware.AbstractSerialMeasuringDevice; import org.tellervo.desktop.hardware.MeasuringSampleIOEvent; import gnu.io.SerialPortEvent; /** * The LINTAB platform is made by RINNTECH. The original platform uses a protocol * that RINNTECH claim is proprietary. An agreement was made whereby RINNTECH * would produce and supply new boxes that would attach to LINTAB platforms that * communicate with a non-proprietary ASCII-based protocol. Users must purchase * such an adapter to use LINTAB platforms with Tellervo (or any other software * other than TSAP-Win). * * These new boxes include a serial and USB connection. The USB connection is * provided by an internal USB-to-serial adapter (driver from www.ftdichip.com). * * Both serial and virtual-serial connections use the following parameters: * - Baud: 1200 * - Data bits : 8 * - Stop bits : 1 * - Parity : none * - Flow control : none * * There is no way for the user to alter these settings. * * Data is transmitted by LINTAB whenever the platform is moved. The data is * as follows: * [integer position in 1/1000mm];[add button state �0� or �1�][reset button state �0� or �1�][LF] * * LINTAB also accepts commands. To force a manual data record output the ASCII-command * GETDATA should be sent to LINTAB. A reset of the counter is done by sending the * ASCII-command RESET to LINTAB. After a command a linefeed (0x0A) or carriage return * (0x0D) must sent to execute the command. * * @author peterbrewer * */ public class LintabDevice extends AbstractSerialMeasuringDevice{ private static final int EVE_ENQ = 5; private Boolean fireOnNextValue = false; private String previousFireState = "0"; private Boolean resetting = false; private Boolean isInitialized = false; int resetCounter = 0; private final static Logger log = LoggerFactory.getLogger(LintabDevice.class); @Override public void setDefaultPortParams() { baudRate = BaudRate.B_1200; dataBits = DataBits.DATABITS_8; stopBits = StopBits.STOPBITS_1; parity = PortParity.NONE; flowControl = FlowControl.NONE; lineFeed = LineFeed.NONE; unitMultiplier = UnitMultiplier.TIMES_1; this.correctionMultiplier = 1.0; this.measureInReverse = true; this.measureCumulatively = true; } @Override public String toString() { return "LINTAB with ASCII adapter"; } @Override public boolean doesInitialize() { return false; } @Override public void serialEvent(SerialPortEvent e) { if(e.getEventType() == SerialPortEvent.DATA_AVAILABLE) { InputStream input; try { input = getSerialPort().getInputStream(); StringBuffer readBuffer = new StringBuffer(); int intReadFromPort; /* LINTAB data appears in the following format: * [integer position in 1/1000mm];[add button state ‘0’ or ’1’][reset button state ‘0’ or ‘1’][LF] * It should look like "140;10" or "46;10" with a LF. * With every change of the LINTAB table state (move table, button press, button release) a * new data record is sent with a line feed (0x0A) at the end of the line. * This means that a lot of the data needs to be ignored. */ //Read from port into buffer while not LF (10) while ((intReadFromPort=input.read()) != 10){ //System.out.println(intReadFromPort); //If a timeout then show bad sample if(intReadFromPort == -1) { fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.BAD_SAMPLE_EVENT, null); return; } readBuffer.append((char) intReadFromPort); } String strReadBuffer = readBuffer.toString(); fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.RAW_DATA, String.valueOf(strReadBuffer), DataDirection.RECEIVED); // Ignore "0;10" data as this is a side-effect of Lintab's hardware button if (strReadBuffer.equals("0;10")) return; // Ignore repeated 'fire' requests String thisFireState = strReadBuffer.substring(strReadBuffer.indexOf(";")+1, strReadBuffer.indexOf(";")+2); if (previousFireState.equals("1") && thisFireState.equals("1")) return; // Keep track of the state of the 'fire' button previousFireState = thisFireState; //Chop the three characters off the right side of the string to leave the number. String strReadPosition = strReadBuffer.substring(0,(strReadBuffer.length())-3); // Check that Lintab has actually reset when we asked. Sometimes if a hardware // switch is used quickly, it doesn't hear the reset request if(resetting) { if(!strReadPosition.equals("0")) { log.debug("Platform reset request ignored... retrying (attempt "+resetCounter+")"); zeroMeasurement(); return; } else if (resetCounter>10) { log.error("Lintab appears to be continually ignoring reset requests!"); } resetRequestTrack(false); } isInitialized = true; // Round up to integer of 1/1000th mm Float fltValue = new Float(strReadPosition); Integer intValue = Math.round(fltValue); // Inverse if reverse measuring mode is on if(getReverseMeasuring()) { intValue = 0 - intValue; } // Handle any correction factor intValue = getCorrectedValue(intValue); //Only process the data if the add button is set and the reset button is not set. if( strReadBuffer.endsWith(";10") || fireOnNextValue) { // Do calculation if working in cumulative mode if(this.measureCumulatively) { Integer cumValue = intValue; intValue = intValue - getPreviousPosition(); setPreviousPosition(cumValue); } fireOnNextValue = false; fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.NEW_SAMPLE_EVENT, intValue); // Only zero the measurement if we're not measuring cumulatively if(!measureCumulatively) { zeroMeasurement(); } } else if( strReadBuffer.endsWith(";01") || strReadBuffer.endsWith(";11")) { zeroMeasurement(); } else { // Not recording this value just updating current value counter fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.UPDATED_CURRENT_VALUE_EVENT, intValue); } } catch (IOException ioe) { fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.ERROR, "Error reading from serial port"); } } } /** * Lintab boxes sometimes ignore reset requests, so we need to ask several * times to make sure it is accepted. This function keeps track of requests, * to ensure we don't enter an infinite loop. * * @param reset */ private void resetRequestTrack(Boolean reset) { if (reset == true) { resetting = true; resetCounter++; } else { resetting = false; resetCounter = 0; } } /** * Send zero command to LINTAB 6 */ @Override public void zeroMeasurement() { if(isInitialized) { String strCommand = "RESET"; resetRequestTrack(true); this.sendData(strCommand); this.setPreviousPosition(0); } } /** * Send request for data to LINTAB 6 */ @Override public void requestMeasurement() { fireOnNextValue=true; String strCommand = "GETDATA"; this.sendData(strCommand); } /** * Send a command to the LINTAB 6 platform. * * @param strCommand */ private void sendData(String strCommand) { //After a command a linefeed (0x0A) or carriage return (0x0D) must be sent to execute the command. strCommand = strCommand+"\r"; OutputStream output; try { output = getSerialPort().getOutputStream(); OutputStream outToPort=new DataOutputStream(output); byte[] command = strCommand.getBytes(); outToPort.write(command); fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.RAW_DATA, strCommand, DataDirection.SENT); } catch (IOException ioe) { fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.ERROR, "Error writing to serial port", DataDirection.SENT); } } @Override public Boolean isRequestDataCapable() { return true; } @Override public Boolean isCurrentValueCapable() { return true; } @Override public Boolean isBaudEditable() { return false; } @Override public Boolean isDatabitsEditable() { return false; } @Override public Boolean isLineFeedEditable() { return false; } @Override public Boolean isParityEditable() { return false; } @Override public Boolean isStopbitsEditable() { return false; } @Override public Boolean isFlowControlEditable(){ return false; } @Override public Boolean isUnitsEditable() { return false; } @Override public Boolean isMeasureCumulativelyConfigurable() { return true; } @Override public Boolean isReverseMeasureCapable() { return true; } @Override public Boolean isCorrectionFactorEditable() { return true; } }
petebrew/tellervo
src/main/java/org/tellervo/desktop/hardware/device/LintabDevice.java
Java
gpl-3.0
11,073
<?php /** * @package leavesandlove-wp-plugin-util * @author Felix Arntz <felix-arntz@leaves-and-love.net> */ if ( ! defined( 'ABSPATH' ) ) { die(); } if ( ! class_exists( 'LaL_WP_Plugin' ) ) { /** * The base plugin main class. * * The main class of each plugin that should use the plugin loader must extend this class. * * The class uses a singleton pattern and uses late static binding (one reason that PHP 5.3 * is required). The class will only be instantiated if all dependencies are met, so this will * not cause a fatal error on PHP 5.2 setups. * * You must never instantiate your plugin class manually as it will be handled by the plugin loader. * When you call the singleton handler, make sure to not specify any arguments to prevent an invalid * instantiation. * * There are three things that you must implement in your derived class: * * a protected static variable called `$_args` to store basic plugin information (this base class automatically handles it) * * a protected class constructor that takes one argument and passes it on to its parent constructor * * a protected method `run()` that actually bootstraps the plugin and its processes (except for loading the plugin textdomain as the base class already takes care of this) * * In addition the following static methods will be automatically called by the plugin loader if they exist: * * `install()`: performs a site-wide installation (must return `true` or `false`) * * `network_install()`: performs a network-wide installation (must return `true` or `false`) * * `uninstall()`: performs a site-wide uninstallation (must return `true` or `false`) * * `network_uninstall()`: performs a network-wide uninstallation (must return `true` or `false`) * * `activate()`: performs a site-wide activation (must return `true` or `false`) * * `network_activate()`: performs a network-wide activation (must return `true` or `false`) * * `deactivate()`: performs a site-wide deactivation (must return `true` or `false`) * * `network_deactivate()`: performs a network-wide deactivation (must return `true` or `false`) * * `filter_plugin_links( $links )`: filters the site-wide plugin action links (must return the filtered `$links`) * * `filter_network_plugin_links( $links )`: filters the network-wide plugin action links (must return the filtered `$links`) * * `render_status_message()`: renders a plugin status message for a site-wide plugin (will be shown inside an admin notice) * * `render_network_status_message()`: renders a plugin status message for a network-wide plugin (will be shown inside an admin notice) * * For more information about how these methods are called check the `LaL_WP_Plugin_Loader` documentation. * * In addition to the methods that you must or may implement, the base class also contains some static * utility methods that the plugin can (and maybe even should!) use, for example to access basic plugin * data like name, version, path, URL and more or to output PHP notices when the plugin is being used * incorrectly. * * @since 1.5.0 */ abstract class LaL_WP_Plugin { /** * @since 1.5.0 * @var array Stores all instances of plugins based on this class. */ protected static $instances = array(); /** * @since 1.5.0 * @var array Contains basic plugin information. Variable must be redefined in the extending class. */ protected static $_args = array(); /** * Singleton handler. * * Uses late static binding and therefore must not be redefined in child class. * * @since 1.5.0 * @param array $args plugin data (passed automatically on instantiation) * @return LaL_WP_Plugin_Util|null a plugin's main class instance or null if not instantiated yet */ public static function instance( $args = array() ) { $slug = ''; if ( isset( $args['slug'] ) ) { $slug = $args['slug']; } elseif ( isset( static::$_args['slug'] ) ) { $slug = static::$_args['slug']; } if ( empty( $slug ) ) { return null; } if ( ! isset( self::$instances[ $slug ] ) ) { self::$instances[ $slug ] = new static( $args ); } return self::$instances[ $slug ]; } /** * @since 1.5.0 * @var boolean Stores whether the `run()` method has already been called to prevent double initialization. */ protected $_run_method_called = false; /** * Protected constructor for singleton. * * Should be redefined in child class, calling this constructor from there. * * @since 1.5.0 * @param array $args plugin data (passed automatically on instantiation) */ protected function __construct( $args ) { static::$_args = $args; } /** * Internal method to initialize the plugin class. * * @since 1.5.0 */ public function _maybe_run() { if ( ! $this->_run_method_called ) { $this->_run_method_called = true; $this->load_textdomain(); $this->run(); } } /** * Abstract method that should actually bootstrap and initialize the plugin's processes. * * @since 1.5.0 */ protected abstract function run(); /** * Loads the plugin textdomain. * * This method is automatically called by this base class and therefore should not be called manually. * * @since 1.5.0 * @return boolean status of the operation */ protected function load_textdomain() { if ( ! empty( static::$_args['textdomain'] ) ) { if ( ! empty( static::$_args['textdomain_dir'] ) ) { if ( 0 === strpos( static::$_args['mode'], 'bundled' ) ) { $locale = apply_filters( 'plugin_locale', get_locale(), static::$_args['textdomain'] ); return load_textdomain( static::$_args['textdomain'], static::$_args['textdomain_dir'] . static::$_args['textdomain'] . '-' . $locale . '.mo' ); } elseif ( 'muplugin' === static::$_args['mode'] ) { return load_muplugin_textdomain( static::$_args['textdomain'], static::$_args['textdomain_dir'] ); } else { return load_plugin_textdomain( static::$_args['textdomain'], false, static::$_args['textdomain_dir'] ); } } else { if ( 0 === strpos( static::$_args['mode'], 'bundled' ) ) { $locale = apply_filters( 'plugin_locale', get_locale(), static::$_args['textdomain'] ); return load_textdomain( static::$_args['textdomain'], WP_LANG_DIR . '/plugins/' . static::$_args['textdomain'] . '-' . $locale . '.mo' ); } else { // As of WordPress 4.6 there's no need to manually load the textdomain. if ( version_compare( get_bloginfo( 'version' ), '4.6', '>=' ) ) { return true; } if ( 'muplugin' === static::$_args['mode'] ) { return load_muplugin_textdomain( static::$_args['textdomain'] ); } else { return load_plugin_textdomain( static::$_args['textdomain'] ); } } } } return false; } /** * Returns basic information about the plugin. * * If the first parameter is provided, the method will return the field's value (or false if invalid field). * Otherwise it will return the full array of plugin information. * * Possible field names are: * * `slug` * * `name` * * `version` * * `main_file` * * `basename` (for the plugin basename) * * `mode` (either 'plugin', 'muplugin', 'bundled-plugin', 'bundled-muplugin', 'bundled-theme' or 'bundled-childtheme') * * `namespace` * * `textdomain` * * `textdomain_dir` * * `use_language_packs` (whether the plugin uses wordpress.org language packs) * * `is_library` (whether the plugin is a library) * * `network_only` (whether the plugin is network only) * * @since 1.5.0 * @param string $field field name to get value of (or empty to get all fields) * @return string|boolean|array the plugin information field/s */ public static function get_info( $field = '' ) { if ( ! empty( $field ) ) { if ( isset( static::$_args[ $field ] ) ) { return static::$_args[ $field ]; } return false; } return static::$_args; } /** * Creates a full path from a path relative to the plugin's directory. * * @since 1.5.0 * @param string $path path relative to this plugin's directory * @return string full path to be used in PHP */ public static function get_path( $path = '' ) { $base_path = ''; switch ( static::$_args['mode'] ) { case 'bundled-childtheme': $base_path = get_stylesheet_directory() . str_replace( wp_normalize_path( get_stylesheet_directory() ), '', wp_normalize_path( dirname( static::$_args['main_file'] ) ) ); break; case 'bundled-theme': $base_path = get_template_directory() . str_replace( wp_normalize_path( get_template_directory() ), '', wp_normalize_path( dirname( static::$_args['main_file'] ) ) ); break; case 'muplugin': $base_path = plugin_dir_path( dirname( static::$_args['main_file'] ) . '/' . static::$_args['slug'] . '/composer.json' ); break; case 'bundled-muplugin': case 'bundled-plugin': case 'plugin': default: $base_path = plugin_dir_path( static::$_args['main_file'] ); } return \LaL_WP_Plugin_Util::build_path( $base_path, $path ); } /** * Creates a full URL from a path relative to the plugin's directory. * * @since 1.5.0 * @param string $path path relative to this plugin's directory * @return string full URL to be used for loading assets for example */ public static function get_url( $path = '' ) { $base_path = ''; switch ( static::$_args['mode'] ) { case 'bundled-childtheme': $base_path = get_stylesheet_directory_uri() . str_replace( wp_normalize_path( get_stylesheet_directory() ), '', wp_normalize_path( dirname( static::$_args['main_file'] ) ) ); break; case 'bundled-theme': $base_path = get_template_directory_uri() . str_replace( wp_normalize_path( get_template_directory() ), '', wp_normalize_path( dirname( static::$_args['main_file'] ) ) ); break; case 'muplugin': $base_path = plugin_dir_url( dirname( static::$_args['main_file'] ) . '/' . static::$_args['slug'] . '/composer.json' ); break; case 'bundled-muplugin': case 'bundled-plugin': case 'plugin': default: $base_path = plugin_dir_url( static::$_args['main_file'] ); } return \LaL_WP_Plugin_Util::build_path( $base_path, $path ); } /** * Outputs a PHP notice for a misused function of this plugin. * * The notice will only be triggered if `WP_DEBUG` is enabled. * * @since 1.5.0 * @param string $function this should be either `__FUNCTION__` or `__METHOD__` from the calling function * @param string $message notice to show * @param string $version version number where this notice was added */ public static function doing_it_wrong( $function, $message, $version ) { if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) { $version = sprintf( __( 'This message was added in %1$s version %2$s.', 'lalwpplugin' ), '&quot;' . static::$_args['name'] . '&quot;', $version ); trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>: %2$s %3$s', 'lalwpplugin' ), $function, $message, $version ) ); } } /** * Outputs a PHP deprecated notice for a function of this plugin. * * The notice will only be triggered if `WP_DEBUG` is enabled. * * @since 1.5.0 * @param string $function either `__FUNCTION__` or `__METHOD__` from the calling function * @param string $version version number where this function was deprecated * @param string|null $replacement function or method name to use as a replacement (if available) */ public static function deprecated_function( $function, $version, $replacement = null ) { if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) { if ( null === $replacement ) { trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> as of %4$s version %2$s with no alternative available.', 'lalwpplugin' ), $function, $version, '', '&quot;' . static::$_args['name'] . '&quot;' ) ); } else { trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> as of %4$s version %2$s. Use %3$s instead!', 'lalwpplugin' ), $function, $version, $replacement, '&quot;' . static::$_args['name'] . '&quot;' ) ); } } } /** * Outputs a PHP deprecated notice for an action hook of this plugin. * * The notice will only be triggered if `WP_DEBUG` is enabled. * * @since 1.7.0 * @param string $tag the hook name of the deprecated action hook * @param string $version version number where this action hook was deprecated * @param string|null $replacement hook name to use as a replacement (if available) */ public static function deprecated_action( $tag, $version, $replacement = null ) { if ( WP_DEBUG && apply_filters( 'deprecated_action_trigger_error', true ) ) { if ( null === $replacement ) { trigger_error( sprintf( __( 'The action %1$s is <strong>deprecated</strong> as of %4$s version %2$s with no alternative available.', 'lalwpplugin' ), $function, $version, '', '&quot;' . static::$_args['name'] . '&quot;' ) ); } else { trigger_error( sprintf( __( 'The action %1$s is <strong>deprecated</strong> as of %4$s version %2$s. Use %3$s instead!', 'lalwpplugin' ), $function, $version, $replacement, '&quot;' . static::$_args['name'] . '&quot;' ) ); } } } /** * Outputs a PHP deprecated notice for a filter hook of this plugin. * * The notice will only be triggered if `WP_DEBUG` is enabled. * * @since 1.7.0 * @param string $tag the hook name of the deprecated filter hook * @param string $version version number where this filter hook was deprecated * @param string|null $replacement hook name to use as a replacement (if available) */ public static function deprecated_filter( $tag, $version, $replacement = null ) { if ( WP_DEBUG && apply_filters( 'deprecated_filter_trigger_error', true ) ) { if ( null === $replacement ) { trigger_error( sprintf( __( 'The filter %1$s is <strong>deprecated</strong> as of %4$s version %2$s with no alternative available.', 'lalwpplugin' ), $function, $version, '', '&quot;' . static::$_args['name'] . '&quot;' ) ); } else { trigger_error( sprintf( __( 'The filter %1$s is <strong>deprecated</strong> as of %4$s version %2$s. Use %3$s instead!', 'lalwpplugin' ), $function, $version, $replacement, '&quot;' . static::$_args['name'] . '&quot;' ) ); } } } /** * Outputs a PHP deprecated notice for an argument of a function of this plugin. * * The notice will only be triggered if `WP_DEBUG` is enabled. * * @since 1.5.0 * @param string $function either `__FUNCTION__` or `__METHOD__` from the calling function * @param string $version version number where this argument was deprecated * @param string|null $message additional notice about a replacement (if available) */ public static function deprecated_argument( $function, $version, $message = null ) { if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) { if ( null === $message ) { trigger_error( sprintf( __( '%1$s was called with an argument that is <strong>deprecated</strong> as of %4$s version %2$s. %3$s', 'lalwpplugin' ), $function, $version, '', '&quot;' . static::$_args['name'] . '&quot;' ) ); } else { trigger_error( sprintf( __( '%1$s was called with an argument that is <strong>deprecated</strong> as of %4$s version %2$s with no alternative available.', 'lalwpplugin' ), $function, $version, $message, '&quot;' . static::$_args['name'] . '&quot;' ) ); } } } } }
felixarntz/leavesandlove-wp-plugin-util
leavesandlove-wp-plugin.php
PHP
gpl-3.0
15,683
// Copyright (C) 2007-2012 Christian Stehno // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "CImageLoaderPPM.h" #ifdef _IRR_COMPILE_WITH_PPM_LOADER_ #include "IReadFile.h" #include "CColorConverter.h" #include "CImage.h" #include "os.h" #include "fast_atof.h" #include "coreutil.h" #include "debug.h" namespace irr { namespace video { //! constructor CImageLoaderPPM::CImageLoaderPPM() { #ifdef _DEBUG setDebugName("CImageLoaderPPM"); #endif } //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") bool CImageLoaderPPM::isALoadableFileExtension(const io::path& filename) const { return core::hasFileExtension ( filename, "ppm", "pgm", "pbm" ); } //! returns true if the file maybe is able to be loaded by this class bool CImageLoaderPPM::isALoadableFileFormat(io::IReadFile* file) const { c8 id[2]={0}; file->read(&id, 2); return (id[0]=='P' && id[1]>'0' && id[1]<'7'); } //! creates a surface from the file IImage* CImageLoaderPPM::loadImage(io::IReadFile* file) const { IImage* image; if (file->getSize() < 12) return 0; c8 id[2]; file->read(&id, 2); if (id[0]!='P' || id[1]<'1' || id[1]>'6') return 0; const u8 format = id[1] - '0'; const bool binary = format>3; core::stringc token; getNextToken(file, token); const u32 width = core::strtoul10(token.c_str()); getNextToken(file, token); const u32 height = core::strtoul10(token.c_str()); u8* data = 0; const u32 size = width*height; if (format==1 || format==4) { skipToNextToken(file); // go to start of data const u32 bytesize = size/8+(size & 3)?1:0; if (binary) { if (file->getSize()-file->getPos() < (long)bytesize) return 0; data = DBG_NEW u8[bytesize]; file->read(data, bytesize); } else { if (file->getSize()-file->getPos() < (long)(2*size)) // optimistic test return 0; data = DBG_NEW u8[bytesize]; memset(data, 0, bytesize); u32 shift=0; for (u32 i=0; i<size; ++i) { getNextToken(file, token); if (token == "1") data[i/8] |= (0x01 << shift); if (++shift == 8) shift=0; } } image = DBG_NEW CImage(ECF_A1R5G5B5, core::dimension2d<u32>(width, height)); if (image) CColorConverter::convert1BitTo16Bit(data, (s16*)image->getData(), width, height); } else { getNextToken(file, token); const u32 maxDepth = core::strtoul10(token.c_str()); if (maxDepth > 255) // no double bytes yet return 0; skipToNextToken(file); // go to start of data if (format==2 || format==5) { if (binary) { if (file->getSize()-file->getPos() < (long)size) return 0; data = DBG_NEW u8[size]; file->read(data, size); image = DBG_NEW CImage(ECF_A8R8G8B8, core::dimension2d<u32>(width, height)); if (image) { u8* ptr = (u8*)image->getData(); for (u32 i=0; i<size; ++i) { *ptr++ = data[i]; *ptr++ = data[i]; *ptr++ = data[i]; *ptr++ = 255; } } } else { if (file->getSize()-file->getPos() < (long)(2*size)) // optimistic test return 0; image = DBG_NEW CImage(ECF_A8R8G8B8, core::dimension2d<u32>(width, height)); if (image) { u8* ptr = (u8*)image->getData(); for (u32 i=0; i<size; ++i) { getNextToken(file, token); const u8 num = (u8)core::strtoul10(token.c_str()); *ptr++ = num; *ptr++ = num; *ptr++ = num; *ptr++ = 255; } } } } else { const u32 bytesize = 3*size; if (binary) { if (file->getSize()-file->getPos() < (long)bytesize) return 0; data = DBG_NEW u8[bytesize]; file->read(data, bytesize); image = DBG_NEW CImage(ECF_A8R8G8B8, core::dimension2d<u32>(width, height)); if (image) { u8* ptr = (u8*)image->getData(); for (u32 i=0; i<size; ++i) { *ptr++ = data[3*i]; *ptr++ = data[3*i+1]; *ptr++ = data[3*i+2]; *ptr++ = 255; } } } else { if (file->getSize()-file->getPos() < (long)(2*bytesize)) // optimistic test return 0; image = DBG_NEW CImage(ECF_A8R8G8B8, core::dimension2d<u32>(width, height)); if (image) { u8* ptr = (u8*)image->getData(); for (u32 i=0; i<size; ++i) { getNextToken(file, token); *ptr++ = (u8)core::strtoul10(token.c_str()); getNextToken(file, token); *ptr++ = (u8)core::strtoul10(token.c_str()); getNextToken(file, token); *ptr++ = (u8)core::strtoul10(token.c_str()); *ptr++ = 255; } } } } } delete [] data; return image; } //! read the next token from file void CImageLoaderPPM::getNextToken(io::IReadFile* file, core::stringc& token) const { token = ""; c8 c; while(file->getPos()<file->getSize()) { file->read(&c, 1); if (c=='#') { while (c!='\n' && c!='\r' && (file->getPos()<file->getSize())) file->read(&c, 1); } else if (!core::isspace(c)) { token.append(c); break; } } while(file->getPos()<file->getSize()) { file->read(&c, 1); if (c=='#') { while (c!='\n' && c!='\r' && (file->getPos()<file->getSize())) file->read(&c, 1); } else if (!core::isspace(c)) token.append(c); else break; } } //! skip to next token (skip whitespace) void CImageLoaderPPM::skipToNextToken(io::IReadFile* file) const { c8 c; while(file->getPos()<file->getSize()) { file->read(&c, 1); if (c=='#') { while (c!='\n' && c!='\r' && (file->getPos()<file->getSize())) file->read(&c, 1); } else if (!core::isspace(c)) { file->seek(-1, true); // put back break; } } } //! creates a loader which is able to load windows bitmaps IImageLoader* createImageLoaderPPM() { return DBG_NEW CImageLoaderPPM; } } // end namespace video } // end namespace irr #endif
Traderain/Wolven-kit
WolvenKit.Irrlicht/source/CImageLoaderPPM.cpp
C++
gpl-3.0
5,858
class Object: def __init__(self, name): self._name = name @property def name(self): return self._name
gnovis/swift
swift_fca/swift_core/object_fca.py
Python
gpl-3.0
131
using System; using System.Collections.Generic; using Server.Items; namespace Server.Mobiles { public class SBButcher : SBInfo { private readonly List<GenericBuyInfo> m_BuyInfo = new InternalBuyInfo(); private readonly IShopSellInfo m_SellInfo = new InternalSellInfo(); public SBButcher() { } public override IShopSellInfo SellInfo { get { return base.SellInfo; } } public override List<GenericBuyInfo> BuyInfo { get { return this.m_BuyInfo; } } public class InternalBuyInfo : List<GenericBuyInfo> { public InternalBuyInfo() { this.Add(new GenericBuyInfo(typeof(Bacon), 7, 20, 0x979, 0)); this.Add(new GenericBuyInfo(typeof(Ham), 26, 20, 0x9C9, 0)); this.Add(new GenericBuyInfo(typeof(Sausage), 18, 20, 0x9C0, 0)); this.Add(new GenericBuyInfo(typeof(RawChickenLeg), 6, 20, 0x1607, 0)); this.Add(new GenericBuyInfo(typeof(RawBird), 9, 20, 0x9B9, 0)); this.Add(new GenericBuyInfo(typeof(RawLambLeg), 9, 20, 0x1609, 0)); this.Add(new GenericBuyInfo(typeof(RawRibs), 16, 20, 0x9F1, 0)); this.Add(new GenericBuyInfo(typeof(ButcherKnife), 13, 20, 0x13F6, 0)); this.Add(new GenericBuyInfo(typeof(Cleaver), 13, 20, 0xEC3, 0)); this.Add(new GenericBuyInfo(typeof(SkinningKnife), 13, 20, 0xEC4, 0)); } } public class InternalSellInfo : GenericSellInfo { public InternalSellInfo() { this.Add(typeof(RawRibs), 8); this.Add(typeof(RawLambLeg), 4); this.Add(typeof(RawChickenLeg), 3); this.Add(typeof(RawBird), 4); this.Add(typeof(Bacon), 3); this.Add(typeof(Sausage), 9); this.Add(typeof(Ham), 13); this.Add(typeof(ButcherKnife), 7); this.Add(typeof(Cleaver), 7); this.Add(typeof(SkinningKnife), 7); } } } }
ironclad88/JustZH
Scripts/Mobiles/Vendors/SBInfo/SBButcher.cs
C#
gpl-3.0
2,268
/* * ULife, the old computer simulation of Life. * Copyright (C) 1998 by Ian Lane (email: lanei@ideal.net.au) * * Distribution: This control is free for public use and components may be * freely descended from it as long as credit is given to the author. * * Converted to C#: 20/07/2011, Serg V. Zhdanovskih */ using System.Drawing; namespace ConwayLife { public sealed class LifeOptions { private int fAnimationDelay; private Color fBackgroundColor; private int fGridHeight; private int fGridWidth; private Color fLivingCellColor; private bool fModified; public string LS_LifeGame { get; set; } public string LS_Step { get; set; } public string LS_Start { get; set; } public string LS_Stop { get; set; } public string LS_SetCells { get; set; } public string LS_Clear { get; set; } public string LS_Random { get; set; } public string LS_Options { get; set; } public int AnimationDelay { get { return fAnimationDelay; } set { if (value != fAnimationDelay) { fAnimationDelay = value; fModified = true; } } } public Color BackgroundColor { get { return fBackgroundColor; } set { if (value != fBackgroundColor) { fBackgroundColor = value; fModified = true; } } } public int GridHeight { get { return fGridHeight; } set { if (value != fGridHeight) { fGridHeight = value; fModified = true; } } } public int GridWidth { get { return fGridWidth; } set { if (value != fGridWidth) { fGridWidth = value; fModified = true; } } } public Color LivingCellColor { get { return fLivingCellColor; } set { if (value != fLivingCellColor) { fLivingCellColor = value; fModified = true; } } } public bool Modified { get { return fModified; } } public LifeOptions() { LS_LifeGame = "Игра \"Жизнь Конвея\""; LS_Step = "Шаг"; LS_Start = "Старт"; LS_Stop = "Стоп"; LS_SetCells = "Изменить поле"; LS_Clear = "Очистить"; LS_Random = "Случайное заполнение"; LS_Options = "Настройки"; RestoreDefaults(); } public void RestoreDefaults() { AnimationDelay = LifeConsts.DefaultAnimationDelay; BackgroundColor = LifeConsts.DefaultBackgroundColor; GridHeight = LifeConsts.DefaultGridHeight; GridWidth = LifeConsts.DefaultGridWidth; LivingCellColor = LifeConsts.DefaultCellColor; fModified = true; } } }
ruslangaripov/GEDKeeper
projects/GKv2/GKLifePlugin/ConwayLife/LifeOptions.cs
C#
gpl-3.0
3,499
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>BiduleTroc</title> <link href="style.css" rel="stylesheet" type ="text/css" media="screen"/> </head> <body> <div id="principal"> <div id="title"> <h1>BIDULETROC</h1> </div> <div class="column"> <ul> <li> <h3>Recherche</h3> </li> <li> Catégorie <select name="Categorie" id="Categorie"> <option value="Meuble">Meuble</option> <option value="Ustensile">Ustensile</option> <option value="Livres">Livres</option> <option value="Jeux">Jeux Vidéos/DVD/CD</option> <option value="Vetements">Vetements</option> <option value="Divers">Divers</option> <option value="Hitech">Hi-tech</option> <option value="Outils">Outils</option> <option value="Sports">Sports</option> </select> </li> <li> Mot clef <input type="text" name="RechercheMot" id="RechercheMot" /> </li> </ul> </div> <div id="menu"> <ul id="onglets"> <li class="active"><a href="Accueil.html"> Objets déposés </a></li> <li><a href="Forums.html"> Object recherchés </a></li> </ul> </div> </div> <div id="Connection"> <form name="login" method="post" action="validate.php"> Pseudo :<input type="text" name="user_name"><br> Password :<input type="password" name="password"><br> <input type="submit" value="Se connecter"> <a href="CreerCompte.php">Créer un compte </form> </div> </body> </html>
Lordnight/HTML_Project
index.php
PHP
gpl-3.0
1,566
// polyFEM // with mass matrix, and all // plus, correction to quadratic consistency // periodic boundary conditions // Solves NS equation for an incompressible // fluid in Fourier space #include <CGAL/Timer.h> // write out matrices //#define WRITE //#define EXPLICIT #include"main.h" #include"CH_FFT.h" #include"sim_pars.h" #include"linear.h" #include"fields.h" // Init global stuff.- #include"periodic.h" const FT LL=1; // length of original domain Iso_rectangle domain(-LL/2, -LL/2, LL/2, LL/2); // TODO: the two triangulations store different things. // specific bases and faces should be implemented for each sim_pars simu; //#define FULL #define FULL_FULL //#define FULL_LUMPED //#define FLIP #ifdef FULL_FULL #define FULL #endif #ifdef FULL_LUMPED #define FULL #endif #include"onto_from_mesh.h" //const Eigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, ", ", ";\n", "", "", "[", "];"); Triangulation Tp(domain); // particles Triangulation Tm(domain); // mesh void load_fields_on_fft(const Triangulation& T , CH_FFT& fft ); void load_fields_from_fft(const CH_FFT& fft , Triangulation& T ); int main() { // CGAL::Timer time; // // time.start(); cout << "Creating point cloud" << endl; simu.read(); create(); if(simu.create_points()) { // set_alpha_circle( Tp , 2); // set_alpha_under_cos( Tp ) ; cout << "Creating velocity field " << endl; set_fields_TG( Tm ) ; //set_fields_cos( Tm ) ; cout << "Numbering particles " << endl; number(Tp); number(Tm); } int Nb=sqrt( simu.no_of_particles() + 1e-12); // Set up fft, and calculate initial velocities: move_info( Tm ); move_info( Tp ); CH_FFT fft( LL , Nb ); load_fields_on_fft( Tm , fft ); FT dt=simu.dt(); FT mu=simu.mu(); fft.all_fields_NS( dt * mu ); fft.draw( "phi", 0, fft.field_f() ); fft.draw( "press", 0, fft.field_p() ); fft.draw( "vel_x", 0, fft.field_vel_x() ); fft.draw( "vel_y", 0, fft.field_vel_y() ); load_fields_from_fft( fft, Tm ); // every step areas(Tp); quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() ); // just once! linear algebra(Tm); areas(Tm); quad_coeffs(Tm , simu.FEMm() ); volumes(Tm, simu.FEMm() ); cout << "Setting up diff ops " << endl; // TODO: Are these two needed at all? // if(simu.create_points()) { // nabla(Tm); // TODO, they is, too clear why Delta(Tm); // } const std::string mesh_file("mesh.dat"); const std::string particle_file("particles.dat"); // // step 0 draw.- // draw(Tm, mesh_file , true); // draw(Tp, particle_file , true); cout << "Assigning velocities to particles " << endl; #if defined FULL_FULL { Delta(Tp); linear algebra_p(Tp); from_mesh_full_v( Tm , Tp , algebra_p , kind::U); } #elif defined FULL_LUMPED from_mesh_lumped_v( Tm , Tp , kind::U); #elif defined FLIP from_mesh_v(Tm , Tp , kind::U); #else from_mesh_v(Tm , Tp , kind::U); #endif // #if defined FULL_FULL // { // Delta(Tp); // linear algebra_p(Tp); // from_mesh_full( Tm , Tp , algebra_p,kind::ALPHA); // } // #elif defined FULL_LUMPED // from_mesh_lumped( Tm , Tp , kind::ALPHA); // #elif defined FLIP // from_mesh(Tm , Tp , kind::ALPHA); // #else // from_mesh(Tm , Tp , kind::ALPHA); // #endif cout << "Moving info" << endl; move_info( Tm ); move_info( Tp ); draw(Tm, mesh_file , true); draw(Tp, particle_file , true); // return 1; simu.advance_time(); simu.next_step(); // bool first_iter=true; CGAL::Timer time; time.start(); std::ofstream log_file; log_file.open("main.log"); bool is_overdamped = ( simu.mu() > 1 ) ; // high or low Re for(; simu.current_step() <= simu.Nsteps(); simu.next_step()) { cout << "Step " << simu.current_step() << " . Time " << simu.time() << " ; t step " << simu.dt() << endl; FT dt=simu.dt(); FT dt2 = dt / 2.0 ; int iter=0; FT displ=1e10; FT min_displ=1e10; int min_iter=0; const int max_iter=8; //10; const FT max_displ= 1e-8; // < 0 : disable // leapfrog, special first step.- // if(simu.current_step() == 1) dt2 *= 0.5; // dt2 *= 0.5; move_info(Tm); move_info(Tp); // iter loop for( ; ; iter++) { // comment for no move.- cout << "Moving half step " << endl; FT d0; displ = move( Tp , dt2 , d0 ); areas(Tp); quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() ); cout << "Iter " << iter << " , moved avg " << d0 << " to half point, " << displ << " from previous" << endl; if( displ < min_displ) { min_displ=displ; min_iter=iter; } if( (displ < max_displ) && (iter !=0) ) { cout << "Convergence in " << iter << " iterations " << endl; break; } if( iter == max_iter-1 ) { cout << "Exceeded " << iter-1 << " iterations " << endl; break; } cout << "Proj advected U0 velocities onto mesh " << endl; #if defined FULL onto_mesh_full_v(Tp,Tm,algebra,kind::UOLD); #elif defined FLIP flip_volumes (Tp , Tm , simu.FEMm() ); onto_mesh_flip_v(Tp,Tm,simu.FEMm(),kind::UOLD); #else onto_mesh_delta_v(Tp,Tm,kind::UOLD); #endif load_fields_on_fft( Tm , fft ); FT b = mu * dt2; fft.all_fields_NS( b ); // fft.evolve( b ); load_fields_from_fft( fft , Tm ); cout << "Proj Delta U from mesh onto particles" << endl; #if defined FULL_FULL { Delta(Tp); linear algebra_p(Tp); from_mesh_full_v(Tm, Tp, algebra_p , kind::DELTAU); } #elif defined FULL_LUMPED from_mesh_lumped_v(Tm, Tp, kind::DELTAU); #elif defined FLIP from_mesh_v(Tm, Tp, kind::DELTAU); #else from_mesh_v(Tm, Tp, kind::DELTAU); #endif incr_v( Tp , kind::UOLD , kind::DELTAU , kind::U ); // // substract spurious overall movement.- // zero_mean_v( Tm , kind::FORCE); } // iter loop cout << "Moving whole step: relative "; FT d0; displ=move( Tp , dt , d0 ); cout << displ << " from half point, " << d0 << " from previous point" << endl; // comment for no move.- update_half_velocity( Tp , is_overdamped ); update_half_alpha( Tp ); areas(Tp); quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() ); // this, for the looks basically .- cout << "Proj U_t+1 , alpha_t+1 onto mesh " << endl; #if defined FULL onto_mesh_full_v(Tp,Tm,algebra,kind::U); onto_mesh_full (Tp,Tm,algebra,kind::ALPHA); #elif defined FLIP flip_volumes(Tp , Tm , simu.FEMm() ); onto_mesh_flip_v(Tp,Tm,simu.FEMm(),kind::U); onto_mesh_flip (Tp,Tm,simu.FEMm(),kind::ALPHA); #else onto_mesh_delta_v(Tp,Tm,kind::U); onto_mesh_delta (Tp,Tm,kind::ALPHA); #endif move_info( Tm ); move_info( Tp ); if(simu.current_step()%simu.every()==0) { draw(Tm, mesh_file , true); draw(Tp, particle_file , true); fft.histogram( "phi", simu.current_step() , fft.field_fq() ); } log_file << simu.current_step() << " " << simu.time() << " " ; // integrals( Tp , log_file); log_file << " "; // fidelity( Tp , log_file ); log_file << endl; simu.advance_time(); } // time loop time.stop(); log_file.close(); cout << "Total runtime: " << time.time() << endl; return 0; } void create(void) { int N=simu.no_of_particles(); std::vector<Point> points; // points.reserve(N); if(simu.create_points()) { if(simu.at_random()) { points.reserve(N); CGAL::Random_points_in_square_2<Point,Creator> g(LL/2.0-0.0001); CGAL::cpp11::copy_n( g, N, std::back_inserter(points)); cout << N << " particles placed at random" << endl; } else { // if((plotting)&&(Nin%2==0)&&(spike)) { // cout << "Please enter an odd number of particles" << endl; // std::abort(); // } int Nb=sqrt(N + 1e-12); N=Nb*Nb; simu.set_no_of_particles(N); points.reserve(N); cout << N << " particles placed on square lattice" << endl; FT spacing=LL/FT(Nb+0); FT side=LL-1*spacing; points_on_square_grid_2(side/2.0, N, std::back_inserter(points),Creator());; // for(int i = 0 ; i < Nb ; ++i ) if(simu.perturb()) { CGAL::perturb_points_2( points.begin(), points.end(), simu.pert_rel()* spacing );//,Creator()); cout << "each particle perturbed about " << simu.pert_rel()* spacing << endl; } } cout << "Inserting" << endl; Tp.insert(points.begin(), points.end()); points.clear(); // int Nb = sqrt(N + 1e-12); // int nm = Nb* simu.mesh_factor() + 1 ; // int Nm = nm * nm; int Nm=simu.no_of_nodes(); int nm=sqrt(Nm + 1e-12); Nm= nm * nm; simu.set_no_of_nodes(Nm); points.reserve(Nm); cout << Nm << " mesh on square lattice" << endl; FT spacing=LL/FT( nm +0); FT side=LL-1*spacing; points_on_square_grid_2(side/2.0, Nm , std::back_inserter(points),Creator());; // // TODO: perfectly regular square grids are not too good, in fact // CGAL::perturb_points_2( // points.begin(), points.end(), // 0.001* spacing ); Tm.insert(points.begin(), points.end()); } else { int N=simu.no_of_particles(); char part_file[]="particles.dat"; cout << "reading from file : " << part_file << endl; std::ifstream main_data; main_data.open(part_file ); for(int i=0;i<N;i++) { FT x,y; main_data >> x; main_data >> y; // cout << x << " " << y << endl; Vertex_handle vh=Tp.insert(Point(x,y)); #include"readin.h" } cout << "particles' data read" << endl; main_data.close(); char mesh_file[]="mesh.dat"; cout << "reading from file : " << mesh_file << endl; main_data.open(mesh_file ); int Nm=simu.no_of_nodes(); for(int i=0;i<Nm;i++) { FT x,y; main_data >> x; main_data >> y; // cout << x << " " << y << endl; Vertex_handle vh=Tm.insert(Point(x,y)); #include"readin.h" } cout << "mesh data read" << endl; main_data.close(); } // straight from the manual.- Triangulation::Covering_sheets cs = Tp.number_of_sheets(); cout << "Original covering (particles): " << cs[0] << ' ' << cs[1] << endl; // return ; Tp.convert_to_1_sheeted_covering(); cs = Tp.number_of_sheets(); cout << "Current covering (particles): " << cs[0] << ' ' << cs[1] << endl; return ; if ( Tp.is_triangulation_in_1_sheet() ) // = true { bool is_extensible = Tp.is_extensible_triangulation_in_1_sheet_h1() || Tp.is_extensible_triangulation_in_1_sheet_h2(); // = false Tp.convert_to_1_sheeted_covering(); cs = Tp.number_of_sheets(); cout << "Current covering: " << cs[0] << ' ' << cs[1] << endl; if ( is_extensible ) // = false cout << "It is safe to change the triangulation here." << endl; else { cout << "It is NOT safe to change the triangulation here!" << endl; abort(); } // T.convert_to_9_sheeted_covering(); // cs = T.number_of_sheets(); // cout << "Current covering: " << cs[0] << ' ' << cs[1] << endl; } else { cout << "Triangulation not on one sheet!" << endl; abort(); } // cout << "It is (again) safe to modify the triangulation." << endl; return ; } void load_fields_on_fft( const Triangulation& T , CH_FFT& fft ) { int Nb = fft.Nx(); size_t align=fft.alignment(); c_array ux( Nb , Nb , align ); c_array uy( Nb , Nb , align ); for(F_v_it vit=T.vertices_begin(); vit != T.vertices_end(); vit++) { int nx = vit->nx.val(); int ny = vit->ny.val(); // "right" ordering int i = ( Nb - 1 ) - ny ; int j = nx; // "wrong" ordering // int i = nx; // int j = ny; Vector_2 vv = vit->Uold.val(); //FT val = vit->alpha.val(); ux(i,j) = vv.x(); uy(i,j) = vv.y(); } fft.set_u( ux , uy ); return; } void load_fields_from_fft(const CH_FFT& fft , Triangulation& T ) { int Nb = fft.Nx(); c_array vx = fft.field_vel_x(); c_array vy = fft.field_vel_y(); c_array al = fft.field_f(); c_array pp = fft.field_p(); for(F_v_it vit=T.vertices_begin(); vit != T.vertices_end(); vit++) { int nx = vit->nx.val(); int ny = vit->ny.val(); // "right" ordering int i = ( Nb - 1 ) - ny ; int j = nx; // "wrong" ordering // int i = nx; // int j = ny; vit->alpha.set( real( al(i,j) ) ); vit->p.set( real( pp(i,j) ) ); // TODO: PiC trick here !! vit->Delta_U.set( Vector_2( real( vx(i,j) ) , real( vy(i,j) ) ) ); // TODO: return more fields (chem pot, pressure, force, etc) } return; } void number(Triangulation& T) { int idx=0; int N=simu.no_of_particles(); int Nb=sqrt(N + 1e-12); FT spacing=LL/FT(Nb+0); FT side=LL-1*spacing; for(F_v_it vit=T.vertices_begin(); vit != T.vertices_end(); vit++) { // vit->indx.set(i); //or vit->idx = idx; FT x = vit->point().x() + side/2.0; FT y = vit->point().y() + side/2.0; int i = rint( FT(Nb) * x / LL );//+ 0.5); int j = rint( FT(Nb) * y / LL );//+ 0.5); // --i; --j; vit->nx = i; vit->ny = j; // cout << idx // << " " << i // << " " << j // << " " << x // << " " << y // << endl; ++idx; } return; } // for ( // Periodic_point_iterator pit= // T.periodic_points_begin(stored_cover); // pit != T.periodic_points_end(stored_cover); // ++pit) // { // // pt = *ptit; // // if (! (pt[0].second.is_null() && pt[1].second.is_null() && pt[2].second.is_null()) ) // // { // // Convert the current Periodic_triangle to a Triangle if it is // // not strictly contained inside the original domain. // // Note that this requires EXACT constructions to be exact! // // t_bd = T.triangle(pt); // //} // Point p=pit->first; // Offset os=pit->second; // interior // << p.x()+os[0]*LL << " " // << p.y()+os[1]*LL << " " // // << vit->indx() // << endl; // } // for(F_v_it vit=T.vertices_begin(); // vit != T.vertices_end(); // vit++) // interior // << vit->point().x() << " " // << vit->point().y() << " " // << vit->indx() << endl; // return;
ddcampayo/polyFEM
mains/projected/main_Fourier_TG_2.cpp
C++
gpl-3.0
14,759
package bms.player.beatoraja.result; import static bms.player.beatoraja.ClearType.*; import static bms.player.beatoraja.skin.SkinProperty.*; import java.util.*; import java.util.logging.Logger; import bms.player.beatoraja.input.KeyCommand; import com.badlogic.gdx.utils.FloatArray; import bms.model.BMSModel; import bms.player.beatoraja.*; import bms.player.beatoraja.MainController.IRStatus; import bms.player.beatoraja.input.BMSPlayerInputProcessor; import bms.player.beatoraja.input.KeyBoardInputProcesseor.ControlKeys; import bms.player.beatoraja.ir.*; import bms.player.beatoraja.select.MusicSelector; import bms.player.beatoraja.skin.SkinType; import bms.player.beatoraja.skin.property.EventFactory.EventType; /** * コースリザルト * * @author exch */ public class CourseResult extends AbstractResult { private List<IRSendStatus> irSendStatus = new ArrayList<IRSendStatus>(); private ResultKeyProperty property; public CourseResult(MainController main) { super(main); } public void create() { final PlayerResource resource = main.getPlayerResource(); for(int i = 0;i < REPLAY_SIZE;i++) { saveReplay[i] = main.getPlayDataAccessor().existsReplayData(resource.getCourseBMSModels(), resource.getPlayerConfig().getLnmode(), i ,resource.getConstraint()) ? ReplayStatus.EXIST : ReplayStatus.NOT_EXIST ; } setSound(SOUND_CLEAR, "course_clear.wav", SoundType.SOUND,false); setSound(SOUND_FAIL, "course_fail.wav", SoundType.SOUND, false); setSound(SOUND_CLOSE, "course_close.wav", SoundType.SOUND, false); loadSkin(SkinType.COURSE_RESULT); for(int i = resource.getCourseGauge().size;i < resource.getCourseBMSModels().length;i++) { FloatArray[] list = new FloatArray[resource.getGrooveGauge().getGaugeTypeLength()]; for(int type = 0; type < list.length; type++) { list[type] = new FloatArray(); for(int l = 0;l < (resource.getCourseBMSModels()[i].getLastNoteTime() + 500) / 500;l++) { list[type].add(0f); } } resource.getCourseGauge().add(list); } property = ResultKeyProperty.get(resource.getBMSModel().getMode()); if(property == null) { property = ResultKeyProperty.BEAT_7K; } updateScoreDatabase(); // リプレイの自動保存 if(resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY){ for(int i=0;i<REPLAY_SIZE;i++){ if(MusicResult.ReplayAutoSaveConstraint.get(resource.getPlayerConfig().getAutoSaveReplay()[i]).isQualified(oldscore ,getNewScore())) { saveReplayData(i); } } } gaugeType = resource.getGrooveGauge().getType(); } public void prepare() { state = STATE_OFFLINE; final PlayerResource resource = main.getPlayerResource(); final PlayerConfig config = resource.getPlayerConfig(); final ScoreData newscore = getNewScore(); ranking = resource.getRankingData() != null && resource.getCourseBMSModels() != null ? resource.getRankingData() : new RankingData(); rankingOffset = 0; final IRStatus[] ir = main.getIRStatus(); if (ir.length > 0 && resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY) { state = STATE_IR_PROCESSING; boolean uln = false; for(BMSModel model : resource.getCourseBMSModels()) { if(model.containsUndefinedLongNote()) { uln = true; break; } } final int lnmode = uln ? config.getLnmode() : 0; for(IRStatus irc : ir) { boolean send = resource.isUpdateCourseScore() && resource.getCourseData().isRelease(); switch(irc.config.getIrsend()) { case IRConfig.IR_SEND_ALWAYS: break; case IRConfig.IR_SEND_COMPLETE_SONG: // FloatArray gauge = resource.getGauge()[resource.getGrooveGauge().getType()]; // send &= gauge.get(gauge.size - 1) > 0.0; break; case IRConfig.IR_SEND_UPDATE_SCORE: // send &= (newscore.getExscore() > oldscore.getExscore() || newscore.getClear() > oldscore.getClear() // || newscore.getCombo() > oldscore.getCombo() || newscore.getMinbp() < oldscore.getMinbp()); break; } if(send) { irSendStatus.add(new IRSendStatus(irc.connection, resource.getCourseData(), lnmode, newscore)); } } Thread irprocess = new Thread(() -> { try { int irsend = 0; boolean succeed = true; List<IRSendStatus> removeIrSendStatus = new ArrayList<IRSendStatus>(); for(IRSendStatus irc : irSendStatus) { if(irsend == 0) { main.switchTimer(TIMER_IR_CONNECT_BEGIN, true); } irsend++; succeed &= irc.send(); if(irc.retry < 0 || irc.retry > main.getConfig().getIrSendCount()) { removeIrSendStatus.add(irc); } } irSendStatus.removeAll(removeIrSendStatus); if(irsend > 0) { main.switchTimer(succeed ? TIMER_IR_CONNECT_SUCCESS : TIMER_IR_CONNECT_FAIL, true); IRResponse<bms.player.beatoraja.ir.IRScoreData[]> response = ir[0].connection.getCoursePlayData(null, new IRCourseData(resource.getCourseData(), lnmode)); if(response.isSucceeded()) { ranking.updateScore(response.getData(), newscore.getExscore() > oldscore.getExscore() ? newscore : oldscore); rankingOffset = ranking.getRank() > 10 ? ranking.getRank() - 5 : 0; Logger.getGlobal().warning("IRからのスコア取得成功 : " + response.getMessage()); } else { Logger.getGlobal().warning("IRからのスコア取得失敗 : " + response.getMessage()); } } } catch (Exception e) { Logger.getGlobal().severe(e.getMessage()); } finally { state = STATE_IR_FINISHED; } }); irprocess.start(); } play(newscore.getClear() != Failed.id ? SOUND_CLEAR : SOUND_FAIL); } public void render() { long time = main.getNowTime(); main.switchTimer(TIMER_RESULTGRAPH_BEGIN, true); main.switchTimer(TIMER_RESULTGRAPH_END, true); main.switchTimer(TIMER_RESULT_UPDATESCORE, true); if(time > getSkin().getInput()){ main.switchTimer(TIMER_STARTINPUT, true); } if (main.isTimerOn(TIMER_FADEOUT)) { if (main.getNowTime(TIMER_FADEOUT) > getSkin().getFadeout()) { main.getPlayerResource().getPlayerConfig().setGauge(main.getPlayerResource().getOrgGaugeOption()); stop(SOUND_CLEAR); stop(SOUND_FAIL); stop(SOUND_CLOSE); main.changeState(MainStateType.MUSICSELECT); } } else if (time > getSkin().getScene()) { main.switchTimer(TIMER_FADEOUT, true); if(getSound(SOUND_CLOSE) != null) { stop(SOUND_CLEAR); stop(SOUND_FAIL); play(SOUND_CLOSE); } } } public void input() { super.input(); final PlayerResource resource = main.getPlayerResource(); final BMSPlayerInputProcessor inputProcessor = main.getInputProcessor(); if (!main.isTimerOn(TIMER_FADEOUT) && main.isTimerOn(TIMER_STARTINPUT)) { boolean ok = false; for (int i = 0; i < property.getAssignLength(); i++) { if (property.getAssign(i) == ResultKeyProperty.ResultKey.CHANGE_GRAPH && inputProcessor.getKeyState(i) && inputProcessor.resetKeyChangedTime(i)) { gaugeType = (gaugeType - 5) % 3 + 6; } else if (property.getAssign(i) != null && inputProcessor.getKeyState(i) && inputProcessor.resetKeyChangedTime(i)) { ok = true; } } if (inputProcessor.isControlKeyPressed(ControlKeys.ESCAPE) || inputProcessor.isControlKeyPressed(ControlKeys.ENTER)) { ok = true; } if (resource.getScoreData() == null || ok) { if (((CourseResultSkin) getSkin()).getRankTime() != 0 && !main.isTimerOn(TIMER_RESULT_UPDATESCORE)) { main.switchTimer(TIMER_RESULT_UPDATESCORE, true); } else if (state == STATE_OFFLINE || state == STATE_IR_FINISHED){ main.switchTimer(TIMER_FADEOUT, true); if(getSound(SOUND_CLOSE) != null) { stop(SOUND_CLEAR); stop(SOUND_FAIL); play(SOUND_CLOSE); } } } if(inputProcessor.isControlKeyPressed(ControlKeys.NUM1)) { saveReplayData(0); } else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM2)) { saveReplayData(1); } else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM3)) { saveReplayData(2); } else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM4)) { saveReplayData(3); } if(inputProcessor.isActivated(KeyCommand.OPEN_IR)) { this.executeEvent(EventType.open_ir); } } } public void updateScoreDatabase() { final PlayerResource resource = main.getPlayerResource(); final PlayerConfig config = resource.getPlayerConfig(); BMSModel[] models = resource.getCourseBMSModels(); final ScoreData newscore = getNewScore(); if (newscore == null) { return; } boolean dp = false; for (BMSModel model : models) { dp |= model.getMode().player == 2; } newscore.setCombo(resource.getMaxcombo()); int random = 0; if (config.getRandom() > 0 || (dp && (config.getRandom2() > 0 || config.getDoubleoption() > 0))) { random = 2; } if (config.getRandom() == 1 && (!dp || (config.getRandom2() == 1 && config.getDoubleoption() == 1))) { random = 1; } final ScoreData score = main.getPlayDataAccessor().readScoreData(models, config.getLnmode(), random, resource.getConstraint()); oldscore = score != null ? score : new ScoreData(); getScoreDataProperty().setTargetScore(oldscore.getExscore(), resource.getRivalScoreData() != null ? resource.getRivalScoreData().getExscore() : 0, Arrays.asList(resource.getCourseData().getSong()).stream().mapToInt(sd -> sd.getNotes()).sum()); getScoreDataProperty().update(newscore); main.getPlayDataAccessor().writeScoreDara(newscore, models, config.getLnmode(), random, resource.getConstraint(), resource.isUpdateCourseScore()); Logger.getGlobal().info("スコアデータベース更新完了 "); } public int getJudgeCount(int judge, boolean fast) { final PlayerResource resource = main.getPlayerResource(); ScoreData score = resource.getCourseScoreData(); if (score != null) { switch (judge) { case 0: return fast ? score.getEpg() : score.getLpg(); case 1: return fast ? score.getEgr() : score.getLgr(); case 2: return fast ? score.getEgd() : score.getLgd(); case 3: return fast ? score.getEbd() : score.getLbd(); case 4: return fast ? score.getEpr() : score.getLpr(); case 5: return fast ? score.getEms() : score.getLms(); } } return 0; } @Override public void dispose() { super.dispose(); } public void saveReplayData(int index) { final PlayerResource resource = main.getPlayerResource(); if (resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY && resource.getCourseScoreData() != null) { if (saveReplay[index] != ReplayStatus.SAVED && resource.isUpdateCourseScore()) { // 保存されているリプレイデータがない場合は、EASY以上で自動保存 ReplayData[] rd = resource.getCourseReplay(); for(int i = 0; i < rd.length; i++) { rd[i].gauge = resource.getPlayerConfig().getGauge(); } main.getPlayDataAccessor().wrireReplayData(rd, resource.getCourseBMSModels(), resource.getPlayerConfig().getLnmode(), index, resource.getConstraint()); saveReplay[index] = ReplayStatus.SAVED; } } } public ScoreData getNewScore() { return main.getPlayerResource().getCourseScoreData(); } static class IRSendStatus { public final IRConnection ir; public final CourseData course; public final int lnmode; public final ScoreData score; public int retry = 0; public IRSendStatus(IRConnection ir, CourseData course, int lnmode, ScoreData score) { this.ir = ir; this.course = course; this.lnmode = lnmode; this.score = score; } public boolean send() { Logger.getGlobal().info("IRへスコア送信中 : " + course.getName()); IRResponse<Object> send1 = ir.sendCoursePlayData(new IRCourseData(course, lnmode), new bms.player.beatoraja.ir.IRScoreData(score)); if(send1.isSucceeded()) { Logger.getGlobal().info("IRスコア送信完了 : " + course.getName()); retry = -255; return true; } else { Logger.getGlobal().warning("IRスコア送信失敗 : " + send1.getMessage()); retry++; return false; } } } }
exch-bms2/beatoraja
src/bms/player/beatoraja/result/CourseResult.java
Java
gpl-3.0
12,539
package com.epam.jdi.uitests.mobile.appium.driver; /* * Copyright 2004-2016 EPAM Systems * * This file is part of JDI project. * * JDI 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. * * JDI 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 JDI. If not, see <http://www.gnu.org/licenses/>. */ import org.openqa.selenium.os.CommandLine; import org.openqa.selenium.os.WindowsUtils; import static com.epam.commons.LinqUtils.first; import static com.epam.commons.LinqUtils.where; import static com.epam.commons.TryCatchUtil.tryGetResult; /** * Created by 12345 on 26.01.2015. */ public final class WebDriverUtils { private WebDriverUtils() { } public static void killAllRunWebDrivers() { try { String pid = getPid(); while (pid != null) { killPID(pid); pid = getPid(); } } catch (Exception ignore) { // Ignore in case of not windows Operation System or any other errors } } private static String getPid() { return first(where(tryGetResult(WindowsUtils::procMap), el -> el.getKey() != null && (el.getKey().contains("Android") && el.getKey().contains("Appium")))); } private static void killPID(String processID) { new CommandLine("taskkill", "/f", "/t", "/pid", processID).execute(); } }
alexeykuptsov/JDI
Java/JDI/jdi-uitest-mobile/src/main/java/com/epam/jdi/uitests/mobile/appium/driver/WebDriverUtils.java
Java
gpl-3.0
1,834
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin // SPDX - License - Identifier: GPL - 3.0 + #include "MantidMDAlgorithms/MinusMD.h" #include "MantidDataObjects/MDBox.h" #include "MantidDataObjects/MDBoxIterator.h" #include "MantidDataObjects/MDEventFactory.h" #include "MantidDataObjects/MDEventWorkspace.h" #include "MantidKernel/System.h" using namespace Mantid::Kernel; using namespace Mantid::API; using namespace Mantid::DataObjects; namespace Mantid { namespace MDAlgorithms { // Register the algorithm into the AlgorithmFactory DECLARE_ALGORITHM(MinusMD) //---------------------------------------------------------------------------------------------- /// Algorithm's name for identification. @see Algorithm::name const std::string MinusMD::name() const { return "MinusMD"; } /// Algorithm's version for identification. @see Algorithm::version int MinusMD::version() const { return 1; } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- /// Is the operation commutative? bool MinusMD::commutative() const { return false; } //---------------------------------------------------------------------------------------------- /// Check the inputs and throw if the algorithm cannot be run void MinusMD::checkInputs() { if (m_lhs_event || m_rhs_event) { if (m_lhs_histo || m_rhs_histo) throw std::runtime_error("Cannot subtract a MDHistoWorkspace and a " "MDEventWorkspace (only MDEventWorkspace - " "MDEventWorkspace is allowed)."); if (m_lhs_scalar || m_rhs_scalar) throw std::runtime_error("Cannot subtract a MDEventWorkspace and a " "scalar (only MDEventWorkspace - " "MDEventWorkspace is allowed)."); } } //---------------------------------------------------------------------------------------------- /** Perform the subtraction. * * Will do m_out_event -= m_operand_event * * @param ws :: MDEventWorkspace being added to */ template <typename MDE, size_t nd> void MinusMD::doMinus(typename MDEventWorkspace<MDE, nd>::sptr ws1) { typename MDEventWorkspace<MDE, nd>::sptr ws2 = boost::dynamic_pointer_cast<MDEventWorkspace<MDE, nd>>(m_operand_event); if (!ws1 || !ws2) throw std::runtime_error("Incompatible workspace types passed to MinusMD."); MDBoxBase<MDE, nd> *box1 = ws1->getBox(); MDBoxBase<MDE, nd> *box2 = ws2->getBox(); Progress prog(this, 0.0, 0.4, box2->getBoxController()->getTotalNumMDBoxes()); // How many events you started with size_t initial_numEvents = ws1->getNPoints(); // Make a leaf-only iterator through all boxes with events in the RHS // workspace MDBoxIterator<MDE, nd> it2(box2, 1000, true); do { MDBox<MDE, nd> *box = dynamic_cast<MDBox<MDE, nd> *>(it2.getBox()); if (box) { // Copy the events from WS2 and add them into WS1 const std::vector<MDE> &events = box->getConstEvents(); // Perform a copy while flipping the signal std::vector<MDE> eventsCopy; eventsCopy.reserve(events.size()); for (auto it = events.begin(); it != events.end(); it++) { MDE eventCopy(*it); eventCopy.setSignal(-eventCopy.getSignal()); eventsCopy.push_back(eventCopy); } // Add events, with bounds checking box1->addEvents(eventsCopy); box->releaseEvents(); } prog.report("Substracting Events"); } while (it2.next()); this->progress(0.41, "Splitting Boxes"); // This is freed in the destructor of the ThreadPool class, // it should not be a memory leak auto prog2 = new Progress(this, 0.4, 0.9, 100); ThreadScheduler *ts = new ThreadSchedulerFIFO(); ThreadPool tp(ts, 0, prog2); ws1->splitAllIfNeeded(ts); prog2->resetNumSteps(ts->size(), 0.4, 0.6); tp.joinAll(); this->progress(0.95, "Refreshing cache"); ws1->refreshCache(); // Set a marker that the file-back-end needs updating if the # of events // changed. if (ws1->getNPoints() != initial_numEvents) ws1->setFileNeedsUpdating(true); } //---------------------------------------------------------------------------------------------- /// Run the algorithm with an MDEventWorkspace as output void MinusMD::execEvent() { // Now we add m_operand_event into m_out_event. CALL_MDEVENT_FUNCTION(this->doMinus, m_out_event); // Clear masking (box flags) from the output workspace m_out_event->clearMDMasking(); // Set to the output setProperty("OutputWorkspace", m_out_event); } //---------------------------------------------------------------------------------------------- /// Run the algorithm with a MDHisotWorkspace as output and operand void MinusMD::execHistoHisto( Mantid::DataObjects::MDHistoWorkspace_sptr out, Mantid::DataObjects::MDHistoWorkspace_const_sptr operand) { out->subtract(*operand); } //---------------------------------------------------------------------------------------------- /// Run the algorithm with a MDHisotWorkspace as output, scalar and operand void MinusMD::execHistoScalar( Mantid::DataObjects::MDHistoWorkspace_sptr out, Mantid::DataObjects::WorkspaceSingleValue_const_sptr scalar) { out->subtract(scalar->y(0)[0], scalar->e(0)[0]); } } // namespace MDAlgorithms } // namespace Mantid
mganeva/mantid
Framework/MDAlgorithms/src/MinusMD.cpp
C++
gpl-3.0
5,591