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
package nars.clock; /** nanosecond accuracy */ public class RealtimeNSClock extends RealtimeClock { public RealtimeNSClock(boolean updatePerCycle) { super(updatePerCycle); } @Override protected long getRealTime() { return System.nanoTime(); } @Override protected float unitsToSeconds(final long l) { return (l / 1e9f); } }
printedheart/opennars
nars_logic/src/main/java/nars/clock/RealtimeNSClock.java
Java
agpl-3.0
384
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.learner.functions.kernel.jmysvm.svm; import com.rapidminer.operator.Operator; import com.rapidminer.operator.learner.functions.kernel.jmysvm.examples.SVMExamples; import com.rapidminer.operator.learner.functions.kernel.jmysvm.kernel.Kernel; import com.rapidminer.parameter.UndefinedParameterError; import com.rapidminer.tools.RandomGenerator; /** * Class for regression SVM * * @author Stefan Rueping, Ingo Mierswa */ public class SVMregression extends SVM { public SVMregression() {} public SVMregression(Operator paramOperator, Kernel kernel, SVMExamples sVMExamples, com.rapidminer.example.ExampleSet rapidMinerExamples, RandomGenerator randomGenerator) throws UndefinedParameterError { super(paramOperator, kernel, sVMExamples, rapidMinerExamples, randomGenerator); }; /** * Calls the optimizer */ @Override protected void optimize() { // optimizer-specific call // qp.n = working_set_size; int i; int j; double[] my_primal = primal; // equality constraint qp.b[0] = 0; for (i = 0; i < working_set_size; i++) { qp.b[0] += alphas[working_set[i]]; } ; // set initial optimization parameters double new_target = 0; double old_target = 0; double target_tmp; for (i = 0; i < working_set_size; i++) { target_tmp = my_primal[i] * qp.H[i * working_set_size + i] / 2; for (j = 0; j < i; j++) { target_tmp += my_primal[j] * qp.H[j * working_set_size + i]; } ; target_tmp += qp.c[i]; old_target += target_tmp * my_primal[i]; } ; double new_constraint_sum = 0; double my_is_zero = is_zero; int sv_count = working_set_size; // optimize boolean KKTerror = true; // KKT not yet satisfied boolean convError = false; // KKT can still be satisfied qp.max_allowed_error = convergence_epsilon; qp.x = primal; qp.solve(); primal = qp.x; lambda_WS = qp.lambda_eq; my_primal = primal; // loop while some KKT condition is not valid (alpha=0) int it = 3; double lambda_lo; while (KKTerror && (it > 0)) { // iterate optimization 3 times with changed sign on variables, if // KKT conditions are not satisfied KKTerror = false; it--; for (i = 0; i < working_set_size; i++) { if (my_primal[i] < is_zero) { lambda_lo = epsilon_neg + epsilon_pos - qp.c[i]; for (j = 0; j < working_set_size; j++) { lambda_lo -= my_primal[j] * qp.H[i * working_set_size + j]; } ; if (qp.A[i] > 0) { lambda_lo -= lambda_WS; } else { lambda_lo += lambda_WS; } ; if (lambda_lo < -convergence_epsilon) { // change sign of i KKTerror = true; qp.A[i] = -qp.A[i]; which_alpha[i] = !which_alpha[i]; my_primal[i] = -my_primal[i]; qp.c[i] = epsilon_neg + epsilon_pos - qp.c[i]; if (qp.A[i] > 0) { qp.u[i] = cNeg[working_set[i]]; } else { qp.u[i] = cPos[working_set[i]]; } ; for (j = 0; j < working_set_size; j++) { qp.H[i * working_set_size + j] = -qp.H[i * working_set_size + j]; qp.H[j * working_set_size + i] = -qp.H[j * working_set_size + i]; } ; if (quadraticLossNeg) { if (which_alpha[i]) { (qp.H)[i * (working_set_size + 1)] += 1 / cNeg[working_set[i]]; (qp.u)[i] = Double.MAX_VALUE; } else { // previous was neg (qp.H)[i * (working_set_size + 1)] -= 1 / cNeg[working_set[i]]; } ; } ; if (quadraticLossPos) { if (!which_alpha[i]) { (qp.H)[i * (working_set_size + 1)] += 1 / cPos[working_set[i]]; (qp.u)[i] = Double.MAX_VALUE; } else { // previous was pos (qp.H)[i * (working_set_size + 1)] -= 1 / cPos[working_set[i]]; } ; } ; } ; } ; } ; qp.x = my_primal; qp.solve(); my_primal = qp.x; lambda_WS = qp.lambda_eq; } ; KKTerror = true; while (KKTerror) { // clip sv_count = working_set_size; new_constraint_sum = qp.b[0]; for (i = 0; i < working_set_size; i++) { // check if at bound if (my_primal[i] <= my_is_zero) { // at lower bound my_primal[i] = qp.l[i]; sv_count--; } else if (qp.u[i] - my_primal[i] <= my_is_zero) { // at upper bound my_primal[i] = qp.u[i]; sv_count--; } ; new_constraint_sum -= qp.A[i] * my_primal[i]; } ; // enforce equality constraint if (sv_count > 0) { new_constraint_sum /= sv_count; logln(5, "adjusting " + sv_count + " alphas by " + new_constraint_sum); for (i = 0; i < working_set_size; i++) { if ((my_primal[i] > qp.l[i]) && (my_primal[i] < qp.u[i])) { // real sv my_primal[i] += qp.A[i] * new_constraint_sum; } ; } ; } else if (Math.abs(new_constraint_sum) > working_set_size * is_zero) { // error, can't get feasible point logln(5, "WARNING: No SVs, constraint_sum = " + new_constraint_sum); old_target = -Double.MIN_VALUE; convError = true; } ; // test descend new_target = 0; for (i = 0; i < working_set_size; i++) { // attention: optimizer changes one triangle of H! target_tmp = my_primal[i] * qp.H[i * working_set_size + i] / 2.0; for (j = 0; j < i; j++) { target_tmp += my_primal[j] * qp.H[j * working_set_size + i]; } ; target_tmp += qp.c[i]; new_target += target_tmp * my_primal[i]; } ; if (new_target < old_target) { KKTerror = false; if (descend < old_target - new_target) { target_count = 0; } else { convError = true; } ; logln(5, "descend = " + (old_target - new_target)); } else if (sv_count > 0) { // less SVs // set my_is_zero to min_i(primal[i]-qp.l[i], qp.u[i]-primal[i]) my_is_zero = Double.MAX_VALUE; for (i = 0; i < working_set_size; i++) { if ((my_primal[i] > qp.l[i]) && (my_primal[i] < qp.u[i])) { if (my_primal[i] - qp.l[i] < my_is_zero) { my_is_zero = my_primal[i] - qp.l[i]; } ; if (qp.u[i] - my_primal[i] < my_is_zero) { my_is_zero = qp.u[i] - my_primal[i]; } ; } ; } ; if (target_count == 0) { my_is_zero *= 2; } ; logln(5, "WARNING: no descend (" + (old_target - new_target) + " <= " + descend + "), adjusting is_zero to " + my_is_zero); logln(5, "new_target = " + new_target); } else { // nothing we can do logln(5, "WARNING: no descend (" + (old_target - new_target) + " <= " + descend + "), stopping."); KKTerror = false; convError = true; } ; } ; if (convError) { target_count++; if (old_target < new_target) { for (i = 0; i < working_set_size; i++) { my_primal[i] = qp.A[i] * alphas[working_set[i]]; } ; logln(5, "WARNING: Convergence error, restoring old primals"); } ; } ; if (target_count > 50) { // non-recoverable numerical error convergence_epsilon *= 2; feasible_epsilon = convergence_epsilon; logln(1, "WARNING: reducing KKT precision to " + convergence_epsilon); target_count = 0; } ; }; @Override protected final boolean is_alpha_neg(int i) { boolean result; double alpha = alphas[i]; if (alpha > 0) { result = true; } else if (alpha == 0) { if (sum[i] - ys[i] + lambda_eq > 0) { result = false; } else { result = true; } ; } else { result = false; } ; return result; }; @Override protected final double nabla(int i) { double alpha = alphas[i]; double y = ys[i]; double result; if (alpha > 0) { result = (sum[i] - y + epsilon_neg); } else if (alpha == 0) { if (is_alpha_neg(i)) { result = (sum[i] - y + epsilon_neg); } else { result = (-sum[i] + y + epsilon_pos); } ; } else { result = (-sum[i] + y + epsilon_pos); } ; return result; }; };
boob-sbcm/3838438
src/main/java/com/rapidminer/operator/learner/functions/kernel/jmysvm/svm/SVMregression.java
Java
agpl-3.0
9,029
# encoding: utf-8 class Api::EpisodesController < Api::BaseController include ApiUpdatedSince api_versions :v1 represent_with Api::EpisodeRepresenter find_method :find_by_guid filter_resources_by :podcast_id after_action :process_media, only: [:create, :update] after_action :publish, only: [:create, :update, :destroy] def included(relation) if action_name == 'index' relation.includes(:podcast, :images, :all_contents, :contents, :enclosures) else relation end end def create res = create_resource consume! res, create_options if !res.prx_uri.blank? && existing_res = Episode.find_by(prx_uri: res.prx_uri) res = existing_res consume! res, create_options end hal_authorize res res.save! respond_with root_resource(res), create_options res end def decorate_query(res) list_scoped(super(res)) end def list_scoped(res) res.published end def show super if visible? end def visible? visible = false if !show_resource respond_with_error(HalApi::Errors::NotFound.new) elsif show_resource.deleted? respond_with_error(ResourceGone.new) elsif !show_resource.published? if EpisodePolicy.new(pundit_user, show_resource).update? redirect_to api_authorization_episode_path(api_version, show_resource) else respond_with_error(HalApi::Errors::NotFound.new) end else visible = true end visible end def find_base super.with_deleted end def sorted(res) res.order('published_at DESC, id DESC') end def process_media resource.copy_media if resource end def publish resource.podcast.publish! if resource && resource.podcast end end
PRX/feeder.prx.org
app/controllers/api/episodes_controller.rb
Ruby
agpl-3.0
1,756
<?php return [ /* |-------------------------------------------------------------------------- | Application Name |-------------------------------------------------------------------------- | | This value is the name of your application. This value is used when the | framework needs to place the application's name in a notification or | any other location as required by the application or its packages. */ 'name' => 'Sublist Manager', /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services your application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_ENV', 'production'), /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => env('APP_DEBUG', false), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => env('APP_URL', 'http://localhost'), /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'America/Chicago', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY'), 'cipher' => 'AES-256-CBC', /* |-------------------------------------------------------------------------- | Logging Configuration |-------------------------------------------------------------------------- | | Here you may configure the log settings for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Settings: "single", "daily", "syslog", "errorlog" | */ 'log' => env('APP_LOG', 'single'), 'log_level' => env('APP_LOG_LEVEL', 'debug'), /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Notifications\NotificationServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Package Service Providers... */ // /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, Weidner\Goutte\GoutteServiceProvider::class, Laravel\Socialite\SocialiteServiceProvider::class, Yajra\Datatables\DatatablesServiceProvider::class, ], /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Bus' => Illuminate\Support\Facades\Bus::class, 'Cache' => Illuminate\Support\Facades\Cache::class, 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, 'File' => Illuminate\Support\Facades\File::class, 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, 'Notification' => Illuminate\Support\Facades\Notification::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, 'Redis' => Illuminate\Support\Facades\Redis::class, 'Request' => Illuminate\Support\Facades\Request::class, 'Response' => Illuminate\Support\Facades\Response::class, 'Route' => Illuminate\Support\Facades\Route::class, 'Schema' => Illuminate\Support\Facades\Schema::class, 'Session' => Illuminate\Support\Facades\Session::class, 'Storage' => Illuminate\Support\Facades\Storage::class, 'URL' => Illuminate\Support\Facades\URL::class, 'Validator' => Illuminate\Support\Facades\Validator::class, 'View' => Illuminate\Support\Facades\View::class, 'Goutte' => Weidner\Goutte\GoutteFacade::class, 'Helper' => App\helpers::class, 'Carbon' => Carbon\Carbon::class, 'Socialite' => Laravel\Socialite\Facades\Socialite::class, ], ];
turtles2/Sublist-Manager
config/app.php
PHP
agpl-3.0
9,485
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2010-2012 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * 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 Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.dcma.validation.service; import com.ephesoft.dcma.core.DCMAException; /** * This is service for validating document. * * @author Ephesoft * @version 1.0 * @see com.ephesoft.dcma.validation.service.ValidationService */ public class ValidationServiceImpl implements ValidationService { /** * To validate the document. * * @param batchInstanceIdentifier String * @throws DCMAException in case of error */ @Override public void validateDocument(String batchInstanceIdentifier) throws DCMAException { } }
kuzavas/ephesoft
dcma-validation/src/main/java/com/ephesoft/dcma/validation/service/ValidationServiceImpl.java
Java
agpl-3.0
2,528
const { GenericCommand } = require('../../models/') const videos = [ 'https://www.pornhub.com/view_video.php?viewkey=ph5a5a31a130d7b', 'https://www.pornhub.com/view_video.php?viewkey=ph5925ca42189b1', 'https://www.pornhub.com/view_video.php?viewkey=ph58a2743e7bc0a', 'https://www.pornhub.com/view_video.php?viewkey=ph588bb994715f4', 'https://www.pornhub.com/view_video.php?viewkey=ph57a9e5cbbbc6b', 'https://www.pornhub.com/view_video.php?viewkey=ph594f81e1bb436', 'https://www.pornhub.com/view_video.php?viewkey=ph57f425354c95a', 'https://www.pornhub.com/view_video.php?viewkey=ph57cb90be0d19d', 'https://www.pornhub.com/view_video.php?viewkey=ph575460edacb01', 'https://www.pornhub.com/view_video.php?viewkey=ph588c05619d874', 'https://www.pornhub.com/view_video.php?viewkey=ph586f01bb87f0f' ] module.exports = new GenericCommand( async ({ Memer, msg, args }) => { return { title: 'Minecraft Porn', description: `You must [click here](${Memer.randomInArray(videos)}) to watch this weird shit.`, footer: { text: 'Why does this exist' } } }, { triggers: ['mcporn'], isNSFW: true, description: 'This is some good stuff, trust me' } )
melmsie/Dank-Memer
src/commands/nsfwCommands/mcporn.js
JavaScript
agpl-3.0
1,202
#!/usr/bin/env python import networkx as nx import matplotlib.pyplot as plt import matplotlib.colors as colors from infomap import infomap """ Generate and draw a network with NetworkX, colored according to the community structure found by Infomap. """ def findCommunities(G): """ Partition network with the Infomap algorithm. Annotates nodes with 'community' id and return number of communities found. """ conf = infomap.init("--two-level"); # Input data network = infomap.Network(conf); # Output data tree = infomap.HierarchicalNetwork(conf) print "Building network..." for e in G.edges_iter(): network.addLink(*e) network.finalizeAndCheckNetwork(True, nx.number_of_nodes(G)); # Cluster network infomap.run(network, tree); print "Found %d top modules with codelength: %f" % (tree.numTopModules(), tree.codelength()) communities = {} clusterIndexLevel = 1 # 1, 2, ... or -1 for top, second, ... or lowest cluster level for node in tree.leafIter(clusterIndexLevel): communities[node.originalLeafIndex] = node.clusterIndex() nx.set_node_attributes(G, 'community', communities) return tree.numTopModules() def drawNetwork(G): # position map pos = nx.spring_layout(G) # community ids communities = [v for k,v in nx.get_node_attributes(G, 'community').items()] numCommunities = max(communities) + 1 # color map from http://colorbrewer2.org/ cmapLight = colors.ListedColormap(['#a6cee3', '#b2df8a', '#fb9a99', '#fdbf6f', '#cab2d6'], 'indexed', numCommunities) cmapDark = colors.ListedColormap(['#1f78b4', '#33a02c', '#e31a1c', '#ff7f00', '#6a3d9a'], 'indexed', numCommunities) # edges nx.draw_networkx_edges(G, pos) # nodes nodeCollection = nx.draw_networkx_nodes(G, pos = pos, node_color = communities, cmap = cmapLight ) # set node border color to the darker shade darkColors = [cmapDark(v) for v in communities] nodeCollection.set_edgecolor(darkColors) # Print node labels separately instead for n in G.nodes_iter(): plt.annotate(n, xy = pos[n], textcoords = 'offset points', horizontalalignment = 'center', verticalalignment = 'center', xytext = [0, 2], color = cmapDark(communities[n]) ) plt.axis('off') # plt.savefig("karate.png") plt.show() G=nx.karate_club_graph() numCommunities = findCommunities(G) print "Number of communities found:", numCommunities drawNetwork(G)
nicktimko/infomap
examples/python/example-networkx.py
Python
agpl-3.0
2,366
class CreateTaggeds < ActiveRecord::Migration def self.up create_table :taggeds do |t| t.references :tag t.references :proposicao t.timestamps end end def self.down drop_table :taggeds end end
pbelasco/pub_data_brasil
db/migrate/20091027191715_create_taggeds.rb
Ruby
agpl-3.0
233
package info.nightscout.androidaps.plugins.InsulinFastacting; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import java.util.ArrayList; import java.util.Date; import java.util.List; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.InsulinInterface; /** * Created by mike on 21.04.2017. */ public class ActivityGraph extends GraphView { Context context; public ActivityGraph(Context context) { super(context); this.context = context; } public ActivityGraph(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } public void show(InsulinInterface insulin) { double dia = insulin.getDia(); int hours = (int) Math.floor(dia + 1); Treatment t = new Treatment(insulin, dia); t.date = 0; t.insulin = 1d; LineGraphSeries<DataPoint> activitySeries = null; LineGraphSeries<DataPoint> iobSeries = null; List<DataPoint> activityArray = new ArrayList<DataPoint>(); List<DataPoint> iobArray = new ArrayList<DataPoint>(); for (long time = 0; time <= hours * 60 * 60 * 1000; time += 5 * 60 * 1000L) { Iob iob = t.iobCalc(time, dia); activityArray.add(new DataPoint(time / 60 / 1000, iob.activityContrib)); iobArray.add(new DataPoint(time / 60 / 1000, iob.iobContrib)); } DataPoint[] activityDataPoints = new DataPoint[activityArray.size()]; activityDataPoints = activityArray.toArray(activityDataPoints); addSeries(activitySeries = new LineGraphSeries<DataPoint>(activityDataPoints)); activitySeries.setThickness(8); getViewport().setXAxisBoundsManual(true); getViewport().setMinX(0); getViewport().setMaxX(hours * 60); getGridLabelRenderer().setNumHorizontalLabels(hours + 1); getGridLabelRenderer().setHorizontalAxisTitle("[min]"); getGridLabelRenderer().setVerticalLabelsColor(activitySeries.getColor()); DataPoint[] iobDataPoints = new DataPoint[iobArray.size()]; iobDataPoints = iobArray.toArray(iobDataPoints); getSecondScale().addSeries(iobSeries = new LineGraphSeries<DataPoint>(iobDataPoints)); iobSeries.setDrawBackground(true); iobSeries.setColor(Color.MAGENTA); iobSeries.setBackgroundColor(Color.argb(70, 255, 0, 255)); getSecondScale().setMinY(0); getSecondScale().setMaxY(1); getGridLabelRenderer().setVerticalLabelsSecondScaleColor(Color.MAGENTA); } }
RoumenGeorgiev/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/ActivityGraph.java
Java
agpl-3.0
2,815
# -*- coding: utf-8 -*- ############################################################################### # # ODOO (ex OpenERP) # Open Source Management Solution # Copyright (C) 2001-2015 Micronaet S.r.l. (<http://www.micronaet.it>) # Developer: Nicola Riolini @thebrush (<https://it.linkedin.com/in/thebrush>) # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### { 'name': 'Label for Easylabel', 'version': '0.1', 'category': 'Generic/Label', 'author': "Micronaet S.r.l. - Nicola Riolini", 'website': 'http://www.micronaet.it', 'license': 'AGPL-3', "depends": [ 'base', 'product', 'sale', 'report_aeroo', ], "data": [ 'security/easylabel_group.xml', 'security/ir.model.access.csv', 'easylabel.xml', 'wizard/view_wizard.xml', 'report/report_easylabel.xml', ], "qweb": [], "demo": [], "test": [], "active": False, "installable": True, "application": False, }
Micronaet/micronaet-migration
label_easy/__openerp__.py
Python
agpl-3.0
1,694
package wp.core; public class UserDisabledException extends Exception { public UserDisabledException (String userId) { super("User " + userId + " is disabled."); } }
WebPredict/brave-new-code
src/main/java/wp/core/UserDisabledException.java
Java
agpl-3.0
172
class AddMotionLastViewedAtToMotionReadLogs < ActiveRecord::Migration[4.2] class MotionReadLog < ActiveRecord::Base end def up add_column :motion_read_logs, :motion_last_viewed_at, :datetime MotionReadLog.reset_column_information MotionReadLog.where(:motion_last_viewed_at => nil).update_all :motion_last_viewed_at => Time.now change_column :motion_read_logs, :motion_last_viewed_at, :datetime, :null => true remove_column :motion_read_logs, :motion_activity_when_last_read end def down remove_column :motion_read_logs, :motion_last_viewed_at add_column :motion_read_logs, :motion_activity_when_last_read, :integer, :default => 0 end end
piratas-ar/loomio
db/migrate/20121008010612_add_motion_last_viewed_at_to_motion_read_logs.rb
Ruby
agpl-3.0
679
import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { TranslateService, LangChangeEvent } from '@ngx-translate/core'; import { BehaviorSubject, combineLatest, throwError } from 'rxjs'; import { EditLogApiOptions } from './EditLogApiOptions.class'; import { IsariDataService } from './../isari-data.service'; import { Observable } from 'rxjs'; import { ToasterService } from 'angular2-toaster'; import flattenDeep from 'lodash/flattenDeep'; import keyBy from 'lodash/keyBy'; import uniq from 'lodash/uniq'; import { map, startWith, switchMap, catchError } from 'rxjs/operators'; @Component({ selector: 'isari-logs', templateUrl: './isari-logs.component.html' // styleUrls: ['./isari-layout.component.css'] }) export class IsariLogsComponent implements OnInit { feature: string; options: EditLogApiOptions = { skip: 0, limit: 5 }; options$: BehaviorSubject<EditLogApiOptions>; details$: BehaviorSubject<boolean>; logs$: Observable<{ count: number; logs: Array<any> }>; labs$: Observable<any[]>; constructor( private route: ActivatedRoute, private isariDataService: IsariDataService, private translate: TranslateService, private router: Router, private toasterService: ToasterService ) { } ngOnInit() { this.options$ = new BehaviorSubject(this.options); this.details$ = new BehaviorSubject(false); this.logs$ = combineLatest( this.route.paramMap, this.options$, this.translate.onLangChange.pipe( map((event: LangChangeEvent) => event.lang), startWith(this.translate.currentLang) ) ).pipe( // this.logs$ = Observable.combineLatest([ // this.route.paramMap, // this.options$, // this.translate.onLangChange // .map((event: LangChangeEvent) => event.lang) // .startWith(this.translate.currentLang) // ]) switchMap(([paramMap, options, lang]) => { this.feature = paramMap.get('feature'); this.options = Object.assign( {}, { itemID: paramMap.get('itemID') }, options ); return combineLatest( this.isariDataService.getHistory(this.feature, this.options, lang) .pipe( catchError(err => { if (err.status === 401) { this.translate .get('error.' + err.status) .subscribe(translated => { this.toasterService.pop('error', '', translated); this.router.navigate(['/', this.feature], { preserveQueryParams: true }); }); } return throwError(err); }) ), this.details$ ); }), map(([{ count, logs }, details]) => { this.labs$ = this.isariDataService .getForeignLabel( 'Organization', uniq( flattenDeep(logs.map(log => log.who.roles ? log.who.roles.map(role => role.lab) : [])) ) ) .pipe(map(labs => keyBy(labs, 'id'))); if (details && this.options['path']) { return { count, logs: logs.map(log => Object.assign({}, log, { _open: true, diff: log.diff.filter( diff => diff.path[0] === this.options['path'] ) }) ) }; } return { count, logs: logs.map(log => Object.assign({}, log, { _open: details })) }; }) ); } changeOpt(options) { this.options = options; this.options$.next(options); } toggleDetails() { this.details$.next(!this.details$.value); } exportLogs({ logs, filetype }) { this.isariDataService.exportLogs( logs, this.feature, this.labs$, this.translate, this.details$.value, filetype ); } }
SciencesPo/isari
client/src/app/isari-logs/isari-logs.component.ts
TypeScript
agpl-3.0
4,092
/* Copyright 2011 Daniel Lombraña González Users_Widget.js is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by Free Software Foundation, either version 3 of the License, or (at your option) any later version. Users_Widget.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Users_Widget.js. If not, see <http://www.gnu.org/licenses/>. */ google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(init); function drawChart(options) { console.log("Drawing charts for " + options.data); console.log("From: " + options.from + " to: " + options.to); $.throbber.show({overlay: false}); //if ( options.days == null ) options.days = 7; if ( options.type == null) options.type = 'total'; // options = { 'days': days, total: 1, with_credit: 1 }; $.getJSON('project_stats.php', options, function(data) { var d = new google.visualization.DataTable(); d.addColumn('string', 'Date'); if (options.type == 'with_credit') d.addColumn('number', 'With credit'); if (options.type == 'total') d.addColumn('number', 'Total'); if (options.type == 'new') d.addColumn('number', 'New'); var x = 0; $.each(data[options.data][0], function(key, val) { d.addRow(); d.setValue(x,0,key); d.setValue(x,1,val); x = x + 1; }); var chart = new google.visualization.LineChart(document.getElementById(options.div)); chart.draw(d, {width: 600, height: 440, colors: options.color, labelPosition: 'right', legend: {'position': 'none'}, title: options.description}); $.throbber.hide(); }); } function default_charts() { var data = $("input[@name=data]:checked").val(); var from = $("#from").val(); var to = $("#to").val(); // New Users or Hosts drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'new', 'div': 'new', 'description': 'New ' + data, 'color': ['red']}); // Total registered users or hosts drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'total', 'div': 'total', 'description': 'Total number of ' + data, 'color': ['blue']}); if (data != 'posts') { // Users or hosts with credit $("#with_credit").show(); drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'with_credit', 'div': 'with_credit', 'description': 'Number of ' + data + ' with credit', 'color': ['green']}); } else { $("#with_credit").hide(); } } function init() { $("input[name='data']").bind("click", default_charts); $("button").button(); var dates = $( "#from, #to" ).datepicker({ defaultDate: "-1w", changeMonth: true, changeYear: true, minDate: new Date(2010,10,01), maxDate: new Date(), dateFormat: 'yy-mm-dd', numberOfMonths: 1, onSelect: function( selectedDate ) { var option = this.id == "from" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); } }); $("#from").datepicker("setDate","-1w"); $("#to").datepicker("setDate", new Date()); $("button").click( function() { var data = $("input[@name=data]:checked").val(); drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'new', 'div': 'new', 'description': 'New ' + data , 'color': ['red']}); drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'total', 'div': 'total', 'description': 'Total number of ' + data, 'color': ['blue']}); if (data != "posts") drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'with_credit', 'div': 'with_credit', 'description': 'Number of ' + data + ' with credit', 'color': ['green']}); }); default_charts(); }
teleyinex/boinc-widgets
project_stats.js
JavaScript
agpl-3.0
4,398
# frozen_string_literal: true module Decidim module Budgets # This cell renders the budget item list in the budgets list class BudgetListItemCell < BaseCell delegate :voting_finished?, to: :controller property :title alias budget model private def card_class ["card--list__item"].tap do |list| unless voting_finished? list << "card--list__data-added" if voted? list << "card--list__data-progress" if progress? end end.join(" ") end def link_class "card__link card--list__heading" end def voted? current_user && status == :voted end def progress? current_user && status == :progress end def status @status ||= current_workflow.status(budget) end end end end
mainio/decidim
decidim-budgets/app/cells/decidim/budgets/budget_list_item_cell.rb
Ruby
agpl-3.0
857
package com.x.cms.assemble.control.jaxrs.viewfieldconfig; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.entity.JpaObject; import com.x.base.core.project.bean.WrapCopier; import com.x.base.core.project.bean.WrapCopierFactory; import com.x.base.core.project.cache.Cache; import com.x.base.core.project.cache.CacheManager; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.cms.assemble.control.Business; import com.x.cms.assemble.control.factory.ViewFieldConfigFactory; import com.x.cms.core.entity.element.ViewFieldConfig; import net.sf.ehcache.Element; public class ActionListByViewId extends BaseAction { @SuppressWarnings("unchecked") protected ActionResult<List<Wo>> execute( HttpServletRequest request, EffectivePerson effectivePerson, String viewId ) throws Exception { ActionResult<List<Wo>> result = new ActionResult<>(); List<Wo> wraps = null; Cache.CacheKey cacheKey = new Cache.CacheKey( this.getClass(), viewId ); Optional<?> optional = CacheManager.get(cacheCategory, cacheKey ); if (optional.isPresent()) { wraps = (List<Wo>) optional.get(); result.setData(wraps); } else { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Business business = new Business(emc); //如判断用户是否有查看所有展示列配置信息的权限,如果没权限不允许继续操作 if (!business.viewEditAvailable( effectivePerson )) { throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} 用户没有查询全部展示列配置信息的权限!"); } //如果有权限,继续操作 ViewFieldConfigFactory viewFieldConfigFactory = business.getViewFieldConfigFactory(); List<String> ids = viewFieldConfigFactory.listByViewId( viewId );//获取指定应用的所有展示列配置信息列表 List<ViewFieldConfig> viewFieldConfigList = emc.list( ViewFieldConfig.class, ids );//查询ID IN ids 的所有展示列配置信息信息列表 wraps = Wo.copier.copy( viewFieldConfigList );//将所有查询出来的有状态的对象转换为可以输出的过滤过属性的对象 CacheManager.put(cacheCategory, cacheKey, wraps ); result.setData(wraps); } catch (Throwable th) { th.printStackTrace(); result.error(th); } } return result; } public static class Wo extends ViewFieldConfig { private static final long serialVersionUID = -5076990764713538973L; public static List<String> excludes = new ArrayList<String>(); public static final WrapCopier<ViewFieldConfig, Wo> copier = WrapCopierFactory.wo( ViewFieldConfig.class, Wo.class, null, JpaObject.FieldsInvisible); } }
o2oa/o2oa
o2server/x_cms_assemble_control/src/main/java/com/x/cms/assemble/control/jaxrs/viewfieldconfig/ActionListByViewId.java
Java
agpl-3.0
2,946
<section id="principal" class="drm"> <div id="application_drm"> <?php if (!$isTeledeclarationMode): ?> <?php include_partial('drm/header', array('drm' => $drm)); ?> <ul id="recap_infos_header"> <li> <label>Nom de l'opérateur : </label><?php echo $drm->getEtablissement()->nom ?><label style="float: right;">Période : <?php echo $drm->periode ?></label> </li> </ul> <?php endif; ?> <?php include_partial('drm/etapes', array('drm' => $drm, 'isTeledeclarationMode' => $isTeledeclarationMode, 'etape_courante' => DRMClient::ETAPE_VALIDATION)); ?> <h2>Modification des informations de votre chai</h2> <form action="<?php echo url_for('drm_validation_update_etablissement', $drm); ?>" method="POST" class="drm_validation_etablissement_form"> <?php echo $form->renderHiddenFields(); ?> <?php echo $form->renderGlobalErrors(); ?> <div class="ligne_form"> <label>Raison Sociale :</label> <?php echo $drm->declarant->nom; ?> </div> <div class="ligne_form"> <?php echo $form['cvi']->renderError(); ?> <?php echo $form['cvi']->renderLabel(); ?> <?php echo $form['cvi']->render(); ?> </div> <div class="ligne_form"> <?php echo $form['no_accises']->renderError(); ?> <?php echo $form['no_accises']->renderLabel(); ?> <?php echo $form['no_accises']->render(); ?> </div> <div class="ligne_form"> <?php echo $form['adresse']->renderError(); ?> <?php echo $form['adresse']->renderLabel(); ?> <?php echo $form['adresse']->render(array('class' => 'champ_long')); ?> </div> <div class="ligne_form"> <?php echo $form['code_postal']->renderError(); ?> <?php echo $form['code_postal']->renderLabel(); ?> <?php echo $form['code_postal']->render(); ?> </div> <div class="ligne_form"> <?php echo $form['commune']->renderError(); ?> <?php echo $form['commune']->renderLabel(); ?> <?php echo $form['commune']->render(); ?> </div> <?php if ($drm->declarant->exist('adresse_compta')): ?> <div class="ligne_form"> <?php echo $form['adresse_compta']->renderError(); ?> <?php echo $form['adresse_compta']->renderLabel(); ?> <?php echo $form['adresse_compta']->render(array('class' => 'champ_long')); ?> </div> <?php endif; ?> <?php if ($drm->declarant->exist('caution')): ?> <div class="ligne_form alignes update_form_radio_list"> <span> <?php echo $form['caution']->renderError(); ?> <?php echo $form['caution']->renderLabel(); ?> <?php echo $form['caution']->render(); ?> </span> </div> <?php endif; ?> <?php $hasSocialeCautionneur = (($drm->getEtablissement()->exist('caution') && ($drm->getEtablissement()->caution == EtablissementClient::CAUTION_CAUTION)) || (($drm->declarant->exist('caution')) && ($drm->declarant->caution == EtablissementClient::CAUTION_CAUTION))); ?> <?php if ($drm->declarant->exist('raison_sociale_cautionneur')): ?> <div class="ligne_form raison_sociale_cautionneur" style="<?php echo (!$hasSocialeCautionneur) ? 'display:none;' : ''; ?>" > <?php echo $form['raison_sociale_cautionneur']->renderError(); ?> <?php echo $form['raison_sociale_cautionneur']->renderLabel(); ?> <?php echo $form['raison_sociale_cautionneur']->render(array('class' => 'champ_long')); ?> </div> <?php endif; ?> <div id="btn_etape_dr"> <a href="<?php echo url_for('drm_validation', $drm) ?>" class="btn_majeur btn_annuler" style="float: left;" id="drm_validation_etablissement_annuler_btn"><span>annuler</span></a> <button type="submit" class="btn_majeur btn_valider" id="drm_validation_etablissement_valider_btn" style="float: right;"><span>Valider</span></button> </div> </form> </div> </section> <?php include_partial('drm/colonne_droite', array('drm' => $drm, 'isTeledeclarationMode' => $isTeledeclarationMode)); ?>
24eme/acVinDRMPlugin
modules/drm_validation/templates/updateEtablissementSuccess.php
PHP
agpl-3.0
4,662
/** * Copyright (C) 2013-2014 Spark Labs, Inc. All rights reserved. - https://www.spark.io/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can download the source here: https://github.com/spark/spark-server */ var settings = require('../settings.js'); var CoreController = require('../lib/CoreController.js'); var roles = require('../lib/RolesController.js'); var sequence = require('when/sequence'); var parallel = require('when/parallel'); var pipeline = require('when/pipeline'); var logger = require('../lib/logger.js'); var utilities = require("../lib/utilities.js"); var fs = require('fs'); var when = require('when'); var util = require('util'); var path = require('path'); var ursa = require('ursa'); var moment = require('moment'); var crypto = require('crypto'); // var corepath; // var corepath = settings.getToCores(); /* * TODO: modularize duplicate code * TODO: implement proper session handling / user authentication * TODO: add cors handler without losing :params support * */ var Api = { loadViews: function (app) { //our middleware app.param("coreid", Api.loadCore); //core functions / variables app.post('/v1/devices/:coreid/:func', Api.fn_call); app.get('/v1/devices/:coreid/:var', Api.get_var); app.put('/v1/devices/:coreid', Api.set_core_attributes); app.get('/v1/devices/:coreid', Api.get_core_attributes); //doesn't need per-core permissions, only shows owned cores. app.get('/v1/devices', Api.list_devices); app.post('/v1/provisioning/:coreid', Api.provision_core); //app.delete('/v1/devices/:coreid', Api.release_device); app.post('/v1/devices', Api.claim_device); }, getSocketID: function (userID) { return userID + "_" + global._socket_counter++; }, getUserID: function (req) { if (!req.user) { logger.log("User obj was empty"); return null; } //req.user.id is set in authorise.validateAccessToken in the OAUTH code return req.user.id; }, list_devices: function (req, res) { var userid = Api.getUserID(req); logger.log("ListDevices", { userID: userid }); // corepath = settings.getToCores(userid); global.server.loadCoreData(userid); // console.log(corepath); //give me all the cores var allCoreIDs = global.server.getAllCoreIDs(userid); // console.log(allCoreIDs); devices = [], connected_promises = []; if(allCoreIDs == null){ var devices = ("no device is claimed by this user"); res.json(200, devices); } else{ for (var coreid in allCoreIDs) { if (!coreid) { continue; } var core = global.server.getCoreAttributes(coreid); var device = { id: coreid, name: (core) ? core.name : null, last_app: core ? core.last_flashed_app_name : null, last_heard: null }; if (utilities.check_requires_update(core, settings.cc3000_driver_version)) { device["requires_deep_update"] = true; } devices.push(device); connected_promises.push(Api.isDeviceOnline(userid, device.id)); } logger.log("ListDevices... waiting for connected state to settle ", { userID: userid }); //switched 'done' to 'then' - threw an exception with 'done' here. when.settle(connected_promises).then(function (descriptors) { for (var i = 0; i < descriptors.length; i++) { var desc = descriptors[i]; devices[i].connected = ('rejected' !== desc.state); devices[i].last_heard = (desc.value) ? desc.value.lastPing : null; } res.json(200, devices); }); } }, get_core_attributes: function (req, res) { var userid = Api.getUserID(req); var socketID = Api.getSocketID(userid), coreID = req.coreID, socket = new CoreController(socketID); logger.log("GetAttr", { coreID: coreID, userID: userid.toString() }); var objReady = parallel([ function () { return when.resolve(global.server.getCoreAttributes(coreID)); }, function () { return utilities.alwaysResolve(socket.sendAndListenForDFD(coreID, { cmd: "Describe" }, { cmd: "DescribeReturn" })); } ]); //whatever we get back... when(objReady).done(function (results) { try { if (!results || (results.length != 2)) { logger.error("get_core_attributes results was the wrong length " + JSON.stringify(results)); res.json(404, "Oops, I couldn't find that core"); return; } //we're expecting descResult to be an array: [ sender, {} ] var doc = results[0], descResult = results[1], coreState = null; if (!doc || !doc.coreID) { logger.error("get_core_attributes 404 error: " + JSON.stringify(doc)); res.json(404, "Oops, I couldn't find that core"); return; } if (util.isArray(descResult) && (descResult.length > 1)) { coreState = descResult[1].state || {}; } if (!coreState) { logger.error("get_core_attributes didn't get description: " + JSON.stringify(descResult)); } var device = { id: doc.coreID, name: doc.name || null, last_app: doc.last_flashed, connected: !!coreState, variables: (coreState) ? coreState.v : null, functions: (coreState) ? coreState.f : null, cc3000_patch_version: doc.cc3000_driver_version }; if (utilities.check_requires_update(doc, settings.cc3000_driver_version)) { device["requires_deep_update"] = true; } res.json(device); } catch (ex) { logger.error("get_core_attributes merge error: " + ex); res.json(500, { Error: "get_core_attributes error: " + ex }); } }, null); //get_core_attribs - end }, set_core_attributes: function (req, res) { var coreID = req.coreID; var userid = Api.getUserID(req); var promises = []; logger.log("set_core_attributes", { coreID: coreID, userID: userid.toString() }); var coreName = req.body ? req.body.name : null; if (coreName != null) { logger.log("SetAttr", { coreID: coreID, userID: userid.toString(), name: coreName }); global.server.setCoreAttribute(req.coreID, "name", coreName); promises.push(when.resolve({ ok: true, name: coreName })); } var hasFiles = req.files && req.files.file; if (hasFiles) { //oh hey, you want to flash firmware? promises.push(Api.compile_and__or_flash_dfd(req)); } var signal = req.body && req.body.signal; if (signal) { //get your hands up in the air! Or down. promises.push(Api.core_signal_dfd(req)); } var flashApp = req.body ? req.body.app : null; if (flashApp) { // It makes no sense to flash a known app and also // either signal or flash a file sent with the request if (!hasFiles && !signal) { // MUST sanitize app name here, before sending to Device Service if (utilities.contains(settings.known_apps, flashApp)) { promises.push(Api.flash_known_app_dfd(req)); } else { promises.push(when.reject("Can't flash unknown app " + flashApp)); } } } var app_id = req.body ? req.body.app_id : null; if (app_id && !hasFiles && !signal && !flashApp) { //we have an app id, and no files, and stuff //we must be flashing from the db! promises.push(Api.flash_app_in_db_dfd(req)); } var app_example_id = req.body ? req.body.app_example_id : null; if (app_example_id && !hasFiles && !signal && !flashApp && !app_id) { //we have an app id, and no files, and stuff //we must be flashing from the db! promises.push(Api.flash_example_app_in_db_dfd(req)); } if (promises.length >= 1) { when.all(promises).done( function (results) { var aggregate = {}; for (var i in results) { for (var key in results[i]) { aggregate[key] = results[i][key]; } } res.json(aggregate); }, function (err) { res.json({ ok: false, errors: [err] }); } ); } else { logger.error("set_core_attributes - nothing to do?", { coreID: coreID, userID: userid.toString() }); res.json({error: "Nothing to do?"}); } }, isDeviceOnline: function (userID, coreID) { var tmp = when.defer(); var socketID = Api.getSocketID(userID); var socket = new CoreController(socketID); var failTimer = setTimeout(function () { logger.log("isDeviceOnline: Ping timed out ", { coreID: coreID }); socket.close(); tmp.reject("Device is not connected"); }, settings.isCoreOnlineTimeout); //setup listener for response back from the device service socket.listenFor(coreID, { cmd: "Pong" }, function (sender, msg) { clearTimeout(failTimer); socket.close(); logger.log("isDeviceOnline: Device service thinks it is online... ", { coreID: coreID }); if (msg && msg.online) { tmp.resolve(msg); } else { tmp.reject(["Core isn't online", 404]); } }, true); logger.log("isDeviceOnline: Pinging core... ", { coreID: coreID }); //send it along to the device service if (!socket.send(coreID, { cmd: "Ping" })) { tmp.reject("send failed"); } return tmp.promise; }, claim_device: function (req, res) { res.json({ ok: true }); }, loadCore: function (req, res, next) { req.coreID = req.param('coreid') || req.body.id; //load core info! req.coreInfo = { "last_app": "", "last_heard": new Date(), "connected": false, "deviceID": req.coreID }; //if that user doesn't own that coreID, maybe they sent us a core name var userid = Api.getUserID(req); var gotCore = utilities.deferredAny([ function () { var core = global.server.getCoreAttributes(req.coreID); if (core && core.coreID) { return when.resolve(core); } else { return when.reject(); } }, function () { var core = global.server.getCoreByName(req.coreID); if (core && core.coreID) { return when.resolve(core); } else { return when.reject(); } } ]); when(gotCore).then( function (core) { if (core) { req.coreID = core.coreID || req.coreID; req.coreInfo = { last_handshake_at: core.last_handshake_at }; } next(); }, function (err) { //s`okay. next(); }) }, get_var: function (req, res) { var userid = Api.getUserID(req); var socketID = Api.getSocketID(userid), coreID = req.coreID, varName = req.param('var'), format = req.param('format'); logger.log("GetVar", {coreID: coreID, userID: userid.toString()}); //send it along to the device service //and listen for a response back from the device service var socket = new CoreController(socketID); var coreResult = socket.sendAndListenForDFD(coreID, { cmd: "GetVar", name: varName }, { cmd: "VarReturn", name: varName }, settings.coreRequestTimeout ); //sendAndListenForDFD resolves arr to ==> [sender, msg] when(coreResult) .then(function (arr) { var msg = arr[1]; if (msg.error) { //at this point, either we didn't get a describe return, or that variable //didn't exist, either way, 404 return res.json(404, { ok: false, error: msg.error }); } //TODO: make me look like the spec. msg.coreInfo = req.coreInfo; msg.coreInfo.connected = true; if (format && (format == "raw")) { return res.send("" + msg.result); } else { return res.json(msg); } }, function () { res.json(408, {error: "Timed out."}); } ).ensure(function () { socket.close(); }); }, fn_call: function (req, res) { var user_id = Api.getUserID(req), coreID = req.coreID, funcName = req.params.func, format = req.params.format; logger.log("FunCall", { coreID: coreID, user_id: user_id.toString() }); var socketID = Api.getSocketID(user_id); var socket = new CoreController(socketID); var core = socket.getCore(coreID); var args = req.body; delete args.access_token; logger.log("FunCall - calling core ", { coreID: coreID, user_id: user_id.toString() }); var coreResult = socket.sendAndListenForDFD(coreID, { cmd: "CallFn", name: funcName, args: args }, { cmd: "FnReturn", name: funcName }, settings.coreRequestTimeout ); //sendAndListenForDFD resolves arr to ==> [sender, msg] when(coreResult) .then( function (arr) { var sender = arr[0], msg = arr[1]; try { //logger.log("FunCall - heard back ", { coreID: coreID, user_id: user_id.toString() }); if (msg.error && (msg.error.indexOf("Unknown Function") >= 0)) { res.json(404, { ok: false, error: "Function not found" }); } else if (msg.error != null) { res.json(400, { ok: false, error: msg.error }); } else { if (format && (format == "raw")) { res.send("" + msg.result); } else { res.json({ id: core.coreID, name: core.name || null, last_app: core.last_flashed_app_name || null, connected: true, return_value: msg.result }); } } } catch (ex) { logger.error("FunCall handling resp error " + ex); res.json(500, { ok: false, error: "Error while api was rendering response" }); } }, function () { res.json(408, {error: "Timed out."}); } ).ensure(function () { socket.close(); }); //socket.send(coreID, { cmd: "CallFn", name: funcName, args: args }); // send the function call along to the device service }, /** * Ask the core to start / stop the "RaiseYourHand" signal * @param req */ core_signal_dfd: function (req) { var tmp = when.defer(); var userid = Api.getUserID(req), socketID = Api.getSocketID(userid), coreID = req.coreID, showSignal = parseInt(req.body.signal); logger.log("SignalCore", { coreID: coreID, userID: userid.toString()}); var socket = new CoreController(socketID); var failTimer = setTimeout(function () { socket.close(); tmp.reject({error: "Timed out, didn't hear back"}); }, settings.coreSignalTimeout); //listen for a response back from the device service socket.listenFor(coreID, { cmd: "RaiseHandReturn"}, function () { clearTimeout(failTimer); socket.close(); tmp.resolve({ id: coreID, connected: true, signaling: showSignal === 1 }); }, true); //send it along to the core via the device service socket.send(coreID, { cmd: "RaiseHand", args: { signal: showSignal } }); return tmp.promise; }, compile_and__or_flash_dfd: function (req) { var allDone = when.defer(); var userid = Api.getUserID(req), coreID = req.coreID; // // Did they pass us a source file or a binary file? // var hasSourceFiles = false; var sourceExts = [".cpp", ".c", ".h", ".ino" ]; if (req.files) { for (var name in req.files) { if (!req.files.hasOwnProperty(name)) { continue; } var ext = utilities.getFilenameExt(req.files[name].path); if (utilities.contains(sourceExts, ext)) { hasSourceFiles = true; break; } } } if (hasSourceFiles) { //TODO: federate? allDone.reject("Not yet implemented"); } else { //they sent a binary, just flash it! var flashDone = Api.flash_core_dfd(req); //pipe rejection / resolution of flash to response utilities.pipeDeferred(flashDone, allDone); } return allDone.promise; }, /** * Flashing firmware to the core, binary file! * @param req * @returns {promise|*|Function|Promise|when.promise} */ flash_core_dfd: function (req) { var tmp = when.defer(); var userid = Api.getUserID(req), socketID = Api.getSocketID(userid), coreID = req.coreID; logger.log("FlashCore", {coreID: coreID, userID: userid.toString()}); var args = req.query; delete args.coreid; if (req.files) { args.data = fs.readFileSync(req.files.file.path); } var socket = new CoreController(socketID); var failTimer = setTimeout(function () { socket.close(); tmp.reject({error: "Timed out."}); }, settings.coreFlashTimeout); //listen for the first response back from the device service socket.listenFor(coreID, { cmd: "Event", name: "Update" }, function (sender, msg) { clearTimeout(failTimer); socket.close(); var response = { id: coreID, status: msg.message }; if ("Update started" === msg.message) { tmp.resolve(response); } else { logger.error("flash_core_dfd rejected ", response); tmp.reject(response); } }, true); //send it along to the device service socket.send(coreID, { cmd: "UFlash", args: args }); return tmp.promise; }, provision_core: function (req, res) { //if we're here, the user should be allowed to provision cores. var done = Api.provision_core_dfd(req); when(done).then( function (result) { res.json(result); }, function (err) { //different status code here? res.json(400, err); }); }, provision_core_dfd: function (req) { var result = when.defer(), userid = Api.getUserID(req), deviceID = req.body.deviceID, publicKey = req.body.publicKey; if (!deviceID) { return when.reject({ error: "No deviceID provided" }); } try { var keyObj = ursa.createPublicKey(publicKey); if (!publicKey || (!ursa.isPublicKey(keyObj))) { return when.reject({ error: "No key provided" }); } } catch (ex) { logger.error("error while parsing publicKey " + ex); return when.reject({ error: "Key error " + ex }); } global.server.addCoreKey(userid, deviceID, publicKey); global.server.setCoreAttribute(deviceID, "registrar", userid); global.server.setCoreAttribute(deviceID, "timestamp", new Date()); result.resolve("Success!"); return result.promise; }, _: null }; exports = module.exports = Api; //implement :: save core data
SreejitS/spark-server
views/api_v1.js
JavaScript
agpl-3.0
18,143
# frozen_string_literal: true module Decidim module Meetings # This controller is the abstract class from which all other controllers of # this engine inherit. # # Note that it inherits from `Decidim::Components::BaseController`, which # override its layout and provide all kinds of useful methods. module Directory class ApplicationController < Decidim::ApplicationController helper Decidim::Meetings::Directory::ApplicationHelper end end end end
decidim/decidim
decidim-meetings/app/controllers/decidim/meetings/directory/application_controller.rb
Ruby
agpl-3.0
501
class TutorialProgressesController < ApplicationController before_filter :admin_required # GET /tutorial_progresses # GET /tutorial_progresses.json def index @tutorial_progresses = TutorialProgress.all respond_to do |format| format.html # index.html.erb format.json { render json: @tutorial_progresses } end end # GET /tutorial_progresses/1 # GET /tutorial_progresses/1.json def show @tutorial_progress = TutorialProgress.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @tutorial_progress } end end # GET /tutorial_progresses/new # GET /tutorial_progresses/new.json def new @tutorial_progress = TutorialProgress.new respond_to do |format| format.html # new.html.erb format.json { render json: @tutorial_progress } end end # GET /tutorial_progresses/1/edit def edit @tutorial_progress = TutorialProgress.find(params[:id]) end # POST /tutorial_progresses # POST /tutorial_progresses.json def create @tutorial_progress = TutorialProgress.new(params[:tutorial_progress]) respond_to do |format| if @tutorial_progress.save format.html { redirect_to @tutorial_progress, notice: 'Tutorial progress was successfully created.' } format.json { render json: @tutorial_progress, status: :created, location: @tutorial_progress } else format.html { render action: 'new' } format.json { render json: @tutorial_progress.errors, status: :unprocessable_entity } end end end # PUT /tutorial_progresses/1 # PUT /tutorial_progresses/1.json def update @tutorial_progress = TutorialProgress.find(params[:id]) respond_to do |format| if @tutorial_progress.update_attributes(params[:tutorial_progress]) format.html { redirect_to @tutorial_progress, notice: 'Tutorial progress was successfully updated.' } format.json { head :ok } else format.html { render action: 'edit' } format.json { render json: @tutorial_progress.errors, status: :unprocessable_entity } end end end # DELETE /tutorial_progresses/1 # DELETE /tutorial_progresses/1.json def destroy @tutorial_progress = TutorialProgress.find(params[:id]) @tutorial_progress.destroy respond_to do |format| format.html { redirect_to tutorial_progresses_url } format.json { head :ok } end end end
zmdroid/Airesis
app/controllers/tutorial_progresses_controller.rb
Ruby
agpl-3.0
2,464
/* * SessionRnwWeave.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_MODULES_RNW_WEAVE_HPP #define SESSION_MODULES_RNW_WEAVE_HPP #include <boost/function.hpp> #include <core/tex/TexLogParser.hpp> #include <core/tex/TexMagicComment.hpp> #include <core/json/Json.hpp> #include "SessionRnwConcordance.hpp" namespace core { class Error; class FilePath; } namespace session { namespace modules { namespace tex { namespace rnw_weave { core::json::Array supportedTypes(); void getTypesInstalledStatus(core::json::Object* pObj); core::json::Value chunkOptions(const std::string& weaveType); struct Result { static Result error(const std::string& errorMessage) { Result result; result.succeeded = false; result.errorMessage = errorMessage; return result; } static Result error(const core::tex::LogEntries& logEntries) { Result result; result.succeeded = false; result.errorLogEntries = logEntries; return result; } static Result success( const tex::rnw_concordance::Concordances& concordances) { Result result; result.succeeded = true; result.concordances = concordances; return result; } bool succeeded; std::string errorMessage; core::tex::LogEntries errorLogEntries; tex::rnw_concordance::Concordances concordances; }; typedef boost::function<void(const Result&)> CompletedFunction; void runTangle(const std::string& filePath, const std::string& rnwWeave); void runWeave(const core::FilePath& filePath, const std::string& encoding, const core::tex::TexMagicComments& magicComments, const boost::function<void(const std::string&)>& onOutput, const CompletedFunction& onCompleted); } // namespace rnw_weave } // namespace tex } // namespace modules } // namesapce session #endif // SESSION_MODULES_RNW_WEAVE_HPP
nvoron23/rstudio
src/cpp/session/modules/tex/SessionRnwWeave.hpp
C++
agpl-3.0
2,449
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.server.channel.handlers; import client.MapleCharacter; import client.MapleClient; import client.MapleDisease; import client.inventory.Item; import client.inventory.MapleInventoryType; import config.YamlConfig; import constants.inventory.ItemConstants; import net.AbstractMaplePacketHandler; import client.inventory.manipulator.MapleInventoryManipulator; import server.MapleItemInformationProvider; import server.MapleStatEffect; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; /** * @author Matze */ public final class UseItemHandler extends AbstractMaplePacketHandler { @Override public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { MapleCharacter chr = c.getPlayer(); if (!chr.isAlive()) { c.announce(MaplePacketCreator.enableActions()); return; } MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); slea.readInt(); short slot = slea.readShort(); int itemId = slea.readInt(); Item toUse = chr.getInventory(MapleInventoryType.USE).getItem(slot); if (toUse != null && toUse.getQuantity() > 0 && toUse.getItemId() == itemId) { if (itemId == 2050004) { chr.dispelDebuffs(); remove(c, slot); return; } else if (itemId == 2050001) { chr.dispelDebuff(MapleDisease.DARKNESS); remove(c, slot); return; } else if (itemId == 2050002) { chr.dispelDebuff(MapleDisease.WEAKEN); chr.dispelDebuff(MapleDisease.SLOW); remove(c, slot); return; } else if (itemId == 2050003) { chr.dispelDebuff(MapleDisease.SEAL); chr.dispelDebuff(MapleDisease.CURSE); remove(c, slot); return; } else if (ItemConstants.isTownScroll(itemId)) { int banMap = chr.getMapId(); int banSp = chr.getMap().findClosestPlayerSpawnpoint(chr.getPosition()).getId(); long banTime = currentServerTime(); if (ii.getItemEffect(toUse.getItemId()).applyTo(chr)) { if(YamlConfig.config.server.USE_BANISHABLE_TOWN_SCROLL) { chr.setBanishPlayerData(banMap, banSp, banTime); } remove(c, slot); } return; } else if (ItemConstants.isAntibanishScroll(itemId)) { if (ii.getItemEffect(toUse.getItemId()).applyTo(chr)) { remove(c, slot); } else { chr.dropMessage(5, "You cannot recover from a banish state at the moment."); } return; } remove(c, slot); if(toUse.getItemId() != 2022153) { ii.getItemEffect(toUse.getItemId()).applyTo(chr); } else { MapleStatEffect mse = ii.getItemEffect(toUse.getItemId()); for(MapleCharacter player : chr.getMap().getCharacters()) { mse.applyTo(player); } } } } private void remove(MapleClient c, short slot) { MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.USE, slot, (short) 1, false); c.announce(MaplePacketCreator.enableActions()); } }
ronancpl/MapleSolaxiaV2
src/net/server/channel/handlers/UseItemHandler.java
Java
agpl-3.0
4,510
<?php /*-------------------------------------------------------+ | PHP-Fusion Content Management System | Copyright (C) PHP-Fusion Inc | https://www.phpfusion.com/ +--------------------------------------------------------+ | Filename: gallery/photo_submit.php | Author: Core Development Team (coredevs@phpfusion.com) +--------------------------------------------------------+ | This program is released as free software under the | Affero GPL license. You can redistribute it and/or | modify it under the terms of this license which you | can read by viewing the included agpl.txt or online | at www.gnu.org/licenses/agpl.html. Removal of this | copyright header is strictly prohibited without | written permission from the original author(s). +--------------------------------------------------------*/ defined('IN_FUSION') || die('Access Denied'); $locale = fusion_get_locale('', [GALLERY_LOCALE, GALLERY_ADMIN_LOCALE]); $gll_settings = get_settings("gallery"); add_to_title($locale['global_200'].$locale['gallery_0100']); opentable("<i class='fa fa-camera-retro m-r-5 fa-lg'></i> ".$locale['gallery_0100']); if ($gll_settings['gallery_allow_submission']) { $criteriaArray = [ 'album_id' => 0, 'photo_title' => '', 'photo_description' => '', 'photo_filename' => '', 'photo_thumb1' => '', 'photo_thumb2' => '', 'photo_keywords' => '', ]; if (isset($_POST['submit_photo'])) { $criteriaArray = [ 'album_id' => form_sanitizer($_POST['album_id'], 0, 'album_id'), 'photo_title' => form_sanitizer($_POST['photo_title'], '', 'photo_title'), 'photo_keywords' => form_sanitizer($_POST['photo_keywords'], '', 'photo_keywords'), 'photo_description' => form_sanitizer($_POST['photo_description'], '', 'photo_description'), 'photo_filename' => '', 'photo_thumb1' => '', 'photo_thumb2' => '', ]; if (fusion_safe()) { if (!empty($_FILES['photo_image']) && is_uploaded_file($_FILES['photo_image']['tmp_name'])) { $upload = form_sanitizer($_FILES['photo_image'], "", "photo_image"); if (isset($upload['error']) && !$upload['error']) { if (isset($upload['image_name']) && isset($upload['thumb1_name']) && isset($upload['thumb2_name'])) { $criteriaArray['photo_filename'] = $upload['image_name']; $criteriaArray['photo_thumb1'] = $upload['thumb1_name']; $criteriaArray['photo_thumb2'] = $upload['thumb2_name']; } else { \Defender::stop(); \Defender::setInputError("photo_image"); add_notice("danger", $locale['photo_0014']); } } } else { \Defender::stop(); \Defender::setInputError('photo_image'); add_notice('danger', $locale['photo_0014']); } } if (fusion_safe()) { $inputArray = [ "submit_id" => 0, "submit_type" => 'p', "submit_user" => fusion_get_userdata('user_id'), "submit_datestamp" => TIME, "submit_criteria" => addslashes(serialize($criteriaArray)) ]; dbquery_insert(DB_SUBMISSIONS, $inputArray, "save"); add_notice("success", $locale['gallery_0101']); redirect(clean_request("submitted=p", ["stype"], TRUE)); } } if (isset($_GET['submitted']) && $_GET['submitted'] == "p") { echo "<div class='well text-center'><p><strong>".$locale['gallery_0101']."</strong></p>"; echo "<p><a href='submit.php?stype=p'>".$locale['gallery_0102']."</a></p>"; echo "<p><a href='index.php'>".str_replace('[SITENAME]', fusion_get_settings('sitename'), $locale['gallery_0113'])."</a></p>\n"; echo "</div>\n"; } else { $result = dbquery("SELECT album_id, album_title FROM ".DB_PHOTO_ALBUMS." ".(multilang_table("PG") ? "WHERE ".in_group('album_language', LANGUAGE)." AND" : "WHERE")." ".groupaccess("album_access")." ORDER BY album_title"); if (dbrows($result) > 0) { $opts = []; while ($data = dbarray($result)) { $opts[$data['album_id']] = $data['album_title']; } echo openform('submit_form', 'post', BASEDIR."submit.php?stype=p", ["enctype" => TRUE]); echo "<div class='alert alert-info m-b-20 submission-guidelines'>".str_replace('[SITENAME]', fusion_get_settings('sitename'), $locale['gallery_0107'])."</div>\n"; echo form_select('album_id', $locale['photo_0003'], '', ["options" => $opts, "inline" => TRUE]); echo form_text('photo_title', $locale['photo_0001'], '', ['required' => TRUE, "inline" => TRUE]); echo form_select('photo_keywords', $locale['photo_0005'], '', [ 'placeholder' => $locale['album_0006'], 'inline' => TRUE, 'multiple' => TRUE, "tags" => TRUE, 'width' => '100%', 'inner_width' => '100%', ]); echo form_fileinput('photo_image', $locale['photo_0004'], '', [ 'upload_path' => INFUSIONS.'gallery/submissions/', 'required' => TRUE, 'thumbnail_folder' => 'thumbs', 'thumbnail' => TRUE, 'thumbnail_w' => $gll_settings['thumb_w'], 'thumbnail_h' => $gll_settings['thumb_h'], 'thumbnail_suffix' => '_t1', 'thumbnail2' => TRUE, 'thumbnail2_w' => $gll_settings['photo_w'], 'thumbnail2_h' => $gll_settings['photo_h'], 'thumbnail2_suffix' => '_t2', 'max_width' => $gll_settings['photo_max_w'], 'max_height' => $gll_settings['photo_max_h'], 'max_byte' => $gll_settings['photo_max_b'], 'delete_original' => FALSE, 'multiple' => FALSE, 'inline' => TRUE, 'error_text' => $locale['photo_0014'], 'template' => 'thumbnail', 'valid_ext' => $gll_settings['gallery_file_types'], ]); echo "<div class='m-b-10 col-xs-12 col-sm-9 col-sm-offset-3'>".sprintf($locale['album_0010'], parsebytesize($gll_settings['photo_max_b']), $gll_settings['gallery_file_types'], $gll_settings['photo_max_w'], $gll_settings['photo_max_h'])."</div>\n"; $textArea_opts = [ 'required' => $gll_settings['gallery_extended_required'] ? TRUE : FALSE, 'autosize' => TRUE, 'form_name' => 'submit_form', ]; echo form_textarea('photo_description', $locale['photo_0008'], '', $textArea_opts); echo form_button('submit_photo', $locale['gallery_0111'], $locale['gallery_0111'], ['class' => 'btn-success', 'icon' => 'fa fa-hdd-o']); echo closeform(); } else { echo "<div class='well' style='text-align:center'><br />".$locale['gallery_0024']."<br /><br /></div>\n"; } } } else { echo "<div class='well text-center'>".$locale['gallery_0112']."</div>\n"; } closetable();
php-fusion/PHP-Fusion
infusions/gallery/photo_submit.php
PHP
agpl-3.0
7,592
/** * Copyright (C) 2000 - 2011 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.socialNetwork.myProfil.control; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.silverpeas.socialNetwork.model.SocialInformation; import com.silverpeas.socialNetwork.model.SocialInformationType; import com.silverpeas.socialNetwork.relationShip.RelationShipService; import com.silverpeas.socialNetwork.status.Status; import com.silverpeas.socialNetwork.status.StatusService; import com.silverpeas.util.StringUtil; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.util.DateUtil; /** * * @author Bensalem Nabil */ public class SocialNetworkService { private String myId; public SocialNetworkService(String myId) { this.myId = myId; } /** * get the List of social Information of my according the type of social information * and the UserId * @return: Map<Date, List<SocialInformation> * @param:SocialInformationType socialInformationType, String userId,String classification, int limit ,int offset */ public Map<Date, List<SocialInformation>> getSocialInformation(SocialInformationType type, Date begin, Date end) { com.silverpeas.calendar.Date dBegin = new com.silverpeas.calendar.Date(begin); com.silverpeas.calendar.Date dEnd = new com.silverpeas.calendar.Date(end); List<SocialInformation> socialInformationsFull = new ProviderService().getSocialInformationsList(type, myId, null, dEnd, dBegin); if (SocialInformationType.ALL.equals(type)) { Collections.sort(socialInformationsFull); } return processResults(socialInformationsFull); } private Map<Date, List<SocialInformation>> processResults(List<SocialInformation> socialInformationsFull) { String date = null; LinkedHashMap<Date, List<SocialInformation>> hashtable = new LinkedHashMap<Date, List<SocialInformation>>(); List<SocialInformation> lsi = new ArrayList<SocialInformation>(); for (SocialInformation information : socialInformationsFull) { if (DateUtil.formatDate(information.getDate()).equals(date)) { lsi.add(information); } else { date = DateUtil.formatDate(information.getDate()); lsi = new ArrayList<SocialInformation>(); lsi.add(information); hashtable.put(information.getDate(), lsi); } } return hashtable; } /** * get the List of social Information of my contatc according the type of social information * and the UserId * @return: Map<Date, List<SocialInformation> * @param:SocialInformationType socialInformationType, String userId,String classification, int limit ,int offset */ public Map<Date, List<SocialInformation>> getSocialInformationOfMyContacts( SocialInformationType type, Date begin, Date end) { com.silverpeas.calendar.Date dBegin = new com.silverpeas.calendar.Date(begin); com.silverpeas.calendar.Date dEnd = new com.silverpeas.calendar.Date(end); List<String> myContactIds = getMyContactsIds(); myContactIds.add(myId); // add myself List<SocialInformation> socialInformationsFull = new ProviderService().getSocialInformationsListOfMyContact(type, myId, myContactIds, dEnd, dBegin); if (SocialInformationType.ALL.equals(type)) { Collections.sort(socialInformationsFull); } return processResults(socialInformationsFull); } public Map<Date, List<SocialInformation>> getSocialInformationOfMyContact(String myContactId, SocialInformationType type, Date begin, Date end) { com.silverpeas.calendar.Date dBegin = new com.silverpeas.calendar.Date(begin); com.silverpeas.calendar.Date dEnd = new com.silverpeas.calendar.Date(end); List<String> myContactIds = new ArrayList<String>(); myContactIds.add(myContactId); List<SocialInformation> socialInformationsFull = new ProviderService().getSocialInformationsListOfMyContact(type, myId, myContactIds, dEnd, dBegin); if (SocialInformationType.ALL.equals(type)) { Collections.sort(socialInformationsFull); } return processResults(socialInformationsFull); } /** * update my status * @param textStatus * @return String */ public String changeStatusService(String textStatus) { Status status = new Status(Integer.parseInt(myId), new Date(), textStatus); return new StatusService().changeStatusService(status); } /** * get my last status * @return String */ public String getLastStatusService() { Status status = new StatusService().getLastStatusService(Integer.parseInt(myId)); if (StringUtil.isDefined(status.getDescription())) { return status.getDescription(); } return " "; } public List<String> getMyContactsIds() { try { return new RelationShipService().getMyContactsIds(Integer.parseInt(myId)); } catch (SQLException ex) { SilverTrace.error("socialNetworkService", "SocialNetworkService.getMyContactsIds", "", ex); } return new ArrayList<String>(); } }
stephaneperry/Silverpeas-Core
war-core/src/main/java/com/silverpeas/socialNetwork/myProfil/control/SocialNetworkService.java
Java
agpl-3.0
6,341
class MH_Intel { idd=-1; fadein = 0; duration = 1e+1000; fadeout = 0; movingEnable=1; name="IntelDisplay"; enableSimulation=1; onLoad="uiNamespace setVariable [""mh_inteldialog"", _this select 0]"; onUnLoad="uiNamespace setVariable [""mh_inteldialog"", nil]"; class controls { class MH_IntelDisplay { type = CT_STATIC; idc = 50; style = ST_LEFT; colorBackground[] = {0, 0, 0, 0}; colorText[] = {0.6, 1.0, 0.6, 0.75}; font = PuristaMedium; sizeEx = 0.0295; h = 0.02; x = -0.3; y = safeZoneY + 0.01; w = 0.4; text = "Intel: 0"; }; }; };
mtusnio/Manhunt
ManhuntUI.hpp
C++
agpl-3.0
751
import loadPolyfills from '../mastodon/load_polyfills'; import ready from '../mastodon/ready'; window.addEventListener('message', e => { const data = e.data || {}; if (!window.parent || data.type !== 'setHeight') { return; } ready(() => { window.parent.postMessage({ type: 'setHeight', id: data.id, height: document.getElementsByTagName('html')[0].scrollHeight, }, '*'); }); }); function main() { const { length } = require('stringz'); const IntlRelativeFormat = require('intl-relativeformat').default; const { delegate } = require('rails-ujs'); const emojify = require('../mastodon/features/emoji/emoji').default; const { getLocale } = require('../mastodon/locales'); const { localeData } = getLocale(); const VideoContainer = require('../mastodon/containers/video_container').default; const MediaGalleryContainer = require('../mastodon/containers/media_gallery_container').default; const CardContainer = require('../mastodon/containers/card_container').default; const React = require('react'); const ReactDOM = require('react-dom'); localeData.forEach(IntlRelativeFormat.__addLocaleData); ready(() => { const locale = document.documentElement.lang; const dateTimeFormat = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', }); const relativeFormat = new IntlRelativeFormat(locale); [].forEach.call(document.querySelectorAll('.emojify'), (content) => { content.innerHTML = emojify(content.innerHTML); }); [].forEach.call(document.querySelectorAll('time.formatted'), (content) => { const datetime = new Date(content.getAttribute('datetime')); const formattedDate = dateTimeFormat.format(datetime); content.title = formattedDate; content.textContent = formattedDate; }); [].forEach.call(document.querySelectorAll('time.time-ago'), (content) => { const datetime = new Date(content.getAttribute('datetime')); content.title = dateTimeFormat.format(datetime); content.textContent = relativeFormat.format(datetime); }); [].forEach.call(document.querySelectorAll('.logo-button'), (content) => { content.addEventListener('click', (e) => { e.preventDefault(); window.open(e.target.href, 'mastodon-intent', 'width=400,height=400,resizable=no,menubar=no,status=no,scrollbars=yes'); }); }); [].forEach.call(document.querySelectorAll('[data-component="Video"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<VideoContainer locale={locale} {...props} />, content); }); [].forEach.call(document.querySelectorAll('[data-component="MediaGallery"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<MediaGalleryContainer locale={locale} {...props} />, content); }); [].forEach.call(document.querySelectorAll('[data-component="Card"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<CardContainer locale={locale} {...props} />, content); }); }); delegate(document, '.webapp-btn', 'click', ({ target, button }) => { if (button !== 0) { return true; } window.location.href = target.href; return false; }); delegate(document, '.status__content__spoiler-link', 'click', ({ target }) => { const contentEl = target.parentNode.parentNode.querySelector('.e-content'); if (contentEl.style.display === 'block') { contentEl.style.display = 'none'; target.parentNode.style.marginBottom = 0; } else { contentEl.style.display = 'block'; target.parentNode.style.marginBottom = null; } return false; }); delegate(document, '.account_display_name', 'input', ({ target }) => { const nameCounter = document.querySelector('.name-counter'); if (nameCounter) { nameCounter.textContent = 30 - length(target.value); } }); delegate(document, '.account_note', 'input', ({ target }) => { const noteCounter = document.querySelector('.note-counter'); if (noteCounter) { noteCounter.textContent = 333 - length(target.value); } }); delegate(document, '#account_avatar', 'change', ({ target }) => { const avatar = document.querySelector('.card.compact .avatar img'); const [file] = target.files || []; const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc; avatar.src = url; }); delegate(document, '#account_header', 'change', ({ target }) => { const header = document.querySelector('.card.compact'); const [file] = target.files || []; const url = file ? URL.createObjectURL(file) : header.dataset.originalSrc; header.style.backgroundImage = `url(${url})`; }); } loadPolyfills().then(main).catch(error => { console.error(error); });
WitchesTown/mastodon
app/javascript/packs/public.js
JavaScript
agpl-3.0
4,984
<?php use Maslosoft\EmbeDi\EmbeDi; use Maslosoft\Ilmatar\Widgets\Interfaces\ButtonInterface; use Maslosoft\Ilmatar\Widgets\Menu\ActionButton; use Maslosoft\Ilmatar\Widgets\Menu\DropDownButton; use Maslosoft\Ilmatar\Widgets\Menu\Toolbar; ?> <?php /* @var $this Toolbar */ ?> <?php if ($this->floating): ?> <div class="ovr toolbar-floating" id="ovr-<?= $this->getId(); ?>"> <?php endif; ?> <?php if ($this->caption): ?> <div class="caption"><?= $this->caption ?></div> <div class="clearfix"></div> <?php endif; ?> <div id="<?= $this->htmlId(); ?>" class="toolbar <?php if($this->inlined):?>toolbar-inlined<?php endif;?>" data-bind=" widget: Maslosoft.Ilmatar.Widgets.Menu.Toolbar, params: <?= $this->getWidgetParams(); ?> " > <div class="btn-group"> <?php $after = []; $buttons = $this->buttons instanceof Closure ? call_user_func($this->buttons) : $this->buttons; foreach ($buttons as $action => $button) { if (!$button instanceof ButtonInterface) { if (!isset($button->class)) { /** * TODO Below should be moved to Toolbar class */ if (is_array($button->action) || $button->action instanceof Closure) { $button->class = DropDownButton::class; } else { $button->class = ActionButton::class; } } $button = EmbeDi::fly()->apply((array) $button); $button->init($this); } echo $button; } ?> </div> </div> <?php if ($this->floating): ?> </div> <?php endif; ?> <?php // Extra markup, for modals etc foreach ($after as $html) { echo $html; } ?>
Maslosoft/IlmatarWidgets
src/Menu/views/toolbar.php
PHP
agpl-3.0
1,672
'use strict'; define(['bitcoinjs-lib', 'crypto-js', 'sjcl'], function(Bitcoin, CryptoJS, sjcl) { function TLCrypto() { } TLCrypto.wordsToBytes = function(words) { var bytes = [] for (var b = 0; b < words.length * 32; b += 8) { bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) } return bytes }; TLCrypto.wordArrayToBytes = function(wordArray) { return TLCrypto.wordsToBytes(wordArray.words) }; TLCrypto.hexStringToData = function(hexString) { return new Bitcoin.Buffer(hexString, 'hex'); }; TLCrypto.getPasswordDigest = function(password) { var SHA256 = CryptoJS.SHA256; var passwordDigest = TLCrypto.wordArrayToBytes(SHA256(SHA256(SHA256(password)))); return new Bitcoin.Buffer(passwordDigest).toString('hex'); // maybe go with this password digest or something to that effect //return sjcl.codec.base64.fromBits(sjcl.misc.pbkdf2(password, email, 1000)); }; TLCrypto.getPasswordHash = function(password) { var SHA256 = CryptoJS.SHA256; var passwordDigest = TLCrypto.wordArrayToBytes(SHA256(SHA256(SHA256(SHA256(SHA256(password)))))); return new Bitcoin.Buffer(passwordDigest).toString('hex'); }; TLCrypto.encrypt = function(plainText, password) { var passwordDigest = TLCrypto.getPasswordDigest(password); var privData = sjcl.encrypt(passwordDigest, plainText, {ks: 256, ts: 128}); return privData; }; TLCrypto.decrypt = function(cipherText, password) { var passwordDigest = TLCrypto.getPasswordDigest(password); var data = sjcl.decrypt(passwordDigest, cipherText); return data; }; return TLCrypto; });
arcbit/arcbit-web
src/js/model/TLCrypto.js
JavaScript
agpl-3.0
1,918
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2022 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import android.os.Parcel; import com.google.gson.JsonObject; import com.kaltura.client.Params; import com.kaltura.client.utils.request.MultiRequestBuilder; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") @MultiRequestBuilder.Tokenizer(WatchLaterUserEntry.Tokenizer.class) public class WatchLaterUserEntry extends UserEntry { public interface Tokenizer extends UserEntry.Tokenizer { } public WatchLaterUserEntry() { super(); } public WatchLaterUserEntry(JsonObject jsonObject) throws APIException { super(jsonObject); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaWatchLaterUserEntry"); return kparams; } public static final Creator<WatchLaterUserEntry> CREATOR = new Creator<WatchLaterUserEntry>() { @Override public WatchLaterUserEntry createFromParcel(Parcel source) { return new WatchLaterUserEntry(source); } @Override public WatchLaterUserEntry[] newArray(int size) { return new WatchLaterUserEntry[size]; } }; public WatchLaterUserEntry(Parcel in) { super(in); } }
kaltura/KalturaGeneratedAPIClientsAndroid
KalturaClient/src/main/java/com/kaltura/client/types/WatchLaterUserEntry.java
Java
agpl-3.0
2,657
/*global plupload */ /*global qiniu */ function FileProgress(file, targetID) { this.fileProgressID = file.id; this.file = file; this.opacity = 100; this.height = 0; this.fileProgressWrapper = $('#' + this.fileProgressID); if (!this.fileProgressWrapper.length) { // <div class="progress"> // <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> // <span class="sr-only">20% Complete</span> // </div> // </div> this.fileProgressWrapper = $('<tr></tr>'); var Wrappeer = this.fileProgressWrapper; Wrappeer.attr('id', this.fileProgressID).addClass('progressContainer'); var progressText = $("<td/>"); progressText.addClass('progressName').text(file.name); var fileSize = plupload.formatSize(file.size).toUpperCase(); var progressSize = $("<td/>"); progressSize.addClass("progressFileSize").text(fileSize); var progressBarTd = $("<td/>"); var progressBarBox = $("<div/>"); progressBarBox.addClass('info'); var progressBarWrapper = $("<div/>"); progressBarWrapper.addClass("progress progress-striped"); var progressBar = $("<div/>"); progressBar.addClass("progress-bar progress-bar-info") .attr('role', 'progressbar') .attr('aria-valuemax', 100) .attr('aria-valuenow', 0) .attr('aria-valuein', 0) .width('0%'); var progressBarPercent = $('<span class=sr-only />'); progressBarPercent.text(fileSize); var progressCancel = $('<a href=javascript:; />'); progressCancel.show().addClass('progressCancel').text('×'); progressBar.append(progressBarPercent); progressBarWrapper.append(progressBar); progressBarBox.append(progressBarWrapper); progressBarBox.append(progressCancel); var progressBarStatus = $('<div class="status text-center"/>'); progressBarBox.append(progressBarStatus); progressBarTd.append(progressBarBox); Wrappeer.append(progressText); Wrappeer.append(progressSize); Wrappeer.append(progressBarTd); $('#' + targetID).append(Wrappeer); } else { this.reset(); } this.height = this.fileProgressWrapper.offset().top; this.setTimer(null); } FileProgress.prototype.setTimer = function(timer) { this.fileProgressWrapper.FP_TIMER = timer; }; FileProgress.prototype.getTimer = function(timer) { return this.fileProgressWrapper.FP_TIMER || null; }; FileProgress.prototype.reset = function() { this.fileProgressWrapper.attr('class', "progressContainer"); this.fileProgressWrapper.find('td .progress .progress-bar-info').attr('aria-valuenow', 0).width('0%').find('span').text(''); this.appear(); }; FileProgress.prototype.setChunkProgess = function(chunk_size) { var chunk_amount = Math.ceil(this.file.size / chunk_size); if (chunk_amount === 1) { return false; } var viewProgess = $('<button class="btn btn-default">查看分块上传进度</button>'); var progressBarChunkTr = $('<tr class="chunk-status-tr"><td colspan=3></td></tr>'); var progressBarChunk = $('<div/>'); for (var i = 1; i <= chunk_amount; i++) { var col = $('<div class="col-md-2"/>'); var progressBarWrapper = $('<div class="progress progress-striped"></div'); var progressBar = $("<div/>"); progressBar.addClass("progress-bar progress-bar-info text-left") .attr('role', 'progressbar') .attr('aria-valuemax', 100) .attr('aria-valuenow', 0) .attr('aria-valuein', 0) .width('0%') .attr('id', this.file.id + '_' + i) .text(''); var progressBarStatus = $('<span/>'); progressBarStatus.addClass('chunk-status').text(); progressBarWrapper.append(progressBar); progressBarWrapper.append(progressBarStatus); col.append(progressBarWrapper); progressBarChunk.append(col); } if(!this.fileProgressWrapper.find('td:eq(2) .btn-default').length){ this.fileProgressWrapper.find('td>div').append(viewProgess); } progressBarChunkTr.hide().find('td').append(progressBarChunk); progressBarChunkTr.insertAfter(this.fileProgressWrapper); }; FileProgress.prototype.setProgress = function(percentage, speed, chunk_size) { this.fileProgressWrapper.attr('class', "progressContainer green"); var file = this.file; var uploaded = file.loaded; var size = plupload.formatSize(uploaded).toUpperCase(); var formatSpeed = plupload.formatSize(speed).toUpperCase(); var progressbar = this.fileProgressWrapper.find('td .progress').find('.progress-bar-info'); if (this.fileProgressWrapper.find('.status').text() === '取消上传'){ return; } this.fileProgressWrapper.find('.status').text("已上传: " + size + " 上传速度: " + formatSpeed + "/s"); percentage = parseInt(percentage, 10); if (file.status !== plupload.DONE && percentage === 100) { percentage = 99; } progressbar.attr('aria-valuenow', percentage).css('width', percentage + '%'); if (chunk_size) { var chunk_amount = Math.ceil(file.size / chunk_size); if (chunk_amount === 1) { return false; } var current_uploading_chunk = Math.ceil(uploaded / chunk_size); var pre_chunk, text; for (var index = 0; index < current_uploading_chunk; index++) { pre_chunk = $('#' + file.id + "_" + index); pre_chunk.width('100%').removeClass().addClass('alert-success').attr('aria-valuenow', 100); text = "块" + index + "上传进度100%"; pre_chunk.next().html(text); } var currentProgessBar = $('#' + file.id + "_" + current_uploading_chunk); var current_chunk_percent; if (current_uploading_chunk < chunk_amount) { if (uploaded % chunk_size) { current_chunk_percent = ((uploaded % chunk_size) / chunk_size * 100).toFixed(2); } else { current_chunk_percent = 100; currentProgessBar.removeClass().addClass('alert-success'); } } else { var last_chunk_size = file.size - chunk_size * (chunk_amount - 1); var left_file_size = file.size - uploaded; if (left_file_size % last_chunk_size) { current_chunk_percent = ((uploaded % chunk_size) / last_chunk_size * 100).toFixed(2); } else { current_chunk_percent = 100; currentProgessBar.removeClass().addClass('alert-success'); } } currentProgessBar.width(current_chunk_percent + '%'); currentProgessBar.attr('aria-valuenow', current_chunk_percent); text = "块" + current_uploading_chunk + "上传进度" + current_chunk_percent + '%'; currentProgessBar.next().html(text); } this.appear(); }; FileProgress.prototype.setComplete = function(up, info) { var td = this.fileProgressWrapper.find('td:eq(2)'), tdProgress = td.find('.progress'); var res = Qiniu.parseJSON(info); var url; if (res.url) { url = res.url; str = "<div><strong>Link:</strong><a href=" + res.url + " target='_blank' > " + res.url + "</a></div>" + "<div class=hash><strong>Hash:</strong>" + res.hash + "</div>"; } else { var domain = up.getOption('domain'); url = domain + encodeURI(res.key); var link = domain + res.key; str = "<div><strong>Link:</strong><a href=" + url + " target='_blank' > " + link + "</a></div>" + "<div class=hash><strong>Hash:</strong>" + res.hash + "</div>"; } tdProgress.html(str).removeClass().next().next('.status').hide(); td.find('.progressCancel').hide(); var progressNameTd = this.fileProgressWrapper.find('.progressName'); var imageView = '?imageView2/1/w/100/h/100'; var isImage = function(url) { var res, suffix = ""; var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"]; var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/; if (!url || !suffixMatch.test(url)) { return false; } res = suffixMatch.exec(url); suffix = res[1].toLowerCase(); for (var i = 0, l = imageSuffixes.length; i < l; i++) { if (suffix === imageSuffixes[i]) { return true; } } return false; }; var isImg = isImage(url); var Wrapper = $('<div class="Wrapper"/>'); var imgWrapper = $('<div class="imgWrapper col-md-3"/>'); var linkWrapper = $('<a class="linkWrapper" target="_blank"/>'); var showImg = $('<img src="images/loading.gif"/>'); progressNameTd.append(Wrapper); if (!isImg) { showImg.attr('src', 'images/default.png'); Wrapper.addClass('default'); imgWrapper.append(showImg); Wrapper.append(imgWrapper); } else { linkWrapper.append(showImg); imgWrapper.append(linkWrapper); Wrapper.append(imgWrapper); var img = new Image(); if (!/imageView/.test(url)) { url += imageView } $(img).attr('src', url); var height_space = 340; $(img).on('load', function() { showImg.attr('src', url); linkWrapper.attr('href', url).attr('title', '查看原图'); function initImg(url, key, height) { $('#myModal-img').modal(); var modalBody = $('#myModal-img').find('.modal-body'); if (height <= 300) { $('#myModal-img').find('.text-warning').show(); } var newImg = new Image(); modalBody.find('img').attr('src', 'images/loading.gif'); newImg.onload = function() { modalBody.find('img').attr('src', url).data('key', key).data('h', height); modalBody.find('.modal-body-wrapper').find('a').attr('href', url); }; newImg.src = url; } var infoWrapper = $('<div class="infoWrapper col-md-6"></div>'); var fopLink = $('<a class="fopLink"/>'); fopLink.attr('data-key', res.key).text('查看处理效果'); infoWrapper.append(fopLink); fopLink.on('click', function() { var key = $(this).data('key'); var height = parseInt($(this).parents('.Wrapper').find('.origin-height').text(), 10); if (height > $(window).height() - height_space) { height = parseInt($(window).height() - height_space, 10); } else { height = parseInt(height, 10) || 300; //set a default height 300 for ie9- } var fopArr = []; fopArr.push({ fop: 'imageView2', mode: 3, h: height, q: 100, format: 'png' }); fopArr.push({ fop: 'watermark', mode: 1, image: 'http://www.b1.qiniudn.com/images/logo-2.png', dissolve: 100, gravity: 'SouthEast', dx: 100, dy: 100 }); var url = Qiniu.pipeline(fopArr, key); $('#myModal-img').on('hide.bs.modal', function() { $('#myModal-img').find('.btn-default').removeClass('disabled'); $('#myModal-img').find('.text-warning').hide(); }).on('show.bs.modal', function() { $('#myModal-img').find('.imageView').find('a:eq(0)').addClass('disabled'); $('#myModal-img').find('.watermark').find('a:eq(3)').addClass('disabled'); $('#myModal-img').find('.text-warning').hide(); }); initImg(url, key, height); return false; }); var ie = Qiniu.detectIEVersion(); if (!(ie && ie <= 9)) { var exif = Qiniu.exif(res.key); if (exif) { var exifLink = $('<a href="" target="_blank">查看exif</a>'); exifLink.attr('href', url + '?exif'); infoWrapper.append(exifLink); } var imageInfo = Qiniu.imageInfo(res.key); var infoArea = $('<div/>'); var infoInner = '<div>格式:<span class="origin-format">' + imageInfo.format + '</span></div>' + '<div>宽度:<span class="orgin-width">' + imageInfo.width + 'px</span></div>' + '<div>高度:<span class="origin-height">' + imageInfo.height + 'px</span></div>'; infoArea.html(infoInner); infoWrapper.append(infoArea); } Wrapper.append(infoWrapper); }).on('error', function() { showImg.attr('src', 'default.png'); Wrapper.addClass('default'); }); } }; FileProgress.prototype.setError = function() { this.fileProgressWrapper.find('td:eq(2)').attr('class', 'text-warning'); this.fileProgressWrapper.find('td:eq(2) .progress').css('width', 0).hide(); this.fileProgressWrapper.find('button').hide(); this.fileProgressWrapper.next('.chunk-status-tr').hide(); }; FileProgress.prototype.setCancelled = function(manual) { var progressContainer = 'progressContainer'; if (!manual) { progressContainer += ' red'; } this.fileProgressWrapper.attr('class', progressContainer); this.fileProgressWrapper.find('td .progress').remove(); this.fileProgressWrapper.find('td:eq(2) .btn-default').hide(); this.fileProgressWrapper.find('td:eq(2) .progressCancel').hide(); }; FileProgress.prototype.setStatus = function(status, isUploading) { if (!isUploading) { this.fileProgressWrapper.find('.status').text(status).attr('class', 'status text-left'); } }; // 绑定取消上传事件 FileProgress.prototype.bindUploadCancel = function(up) { var self = this; if (up) { self.fileProgressWrapper.find('td:eq(2) .progressCancel').on('click', function(){ self.setCancelled(false); self.setStatus("取消上传"); self.fileProgressWrapper.find('.status').css('left', '0'); up.removeFile(self.file); }); } }; FileProgress.prototype.appear = function() { if (this.getTimer() !== null) { clearTimeout(this.getTimer()); this.setTimer(null); } if (this.fileProgressWrapper[0].filters) { try { this.fileProgressWrapper[0].filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. this.fileProgressWrapper.css('filter', "progid:DXImageTransform.Microsoft.Alpha(opacity=100)"); } } else { this.fileProgressWrapper.css('opacity', 1); } this.fileProgressWrapper.css('height', ''); this.height = this.fileProgressWrapper.offset().top; this.opacity = 100; this.fileProgressWrapper.show(); };
edxzw/edx-platform
cms/static/cms/js/ui.js
JavaScript
agpl-3.0
16,012
OC.L10N.register( "settings", { "Enabled" : "Aktiviert", "Not enabled" : "Nicht aktiviert", "Wrong password" : "Falsches Passwort", "Saved" : "Gespeichert", "No user supplied" : "Kein Benutzer angegeben", "Unable to change password" : "Passwort konnte nicht geändert werden", "Authentication error" : "Authentifizierungsfehler", "Please provide an admin recovery password, otherwise all user data will be lost" : "Bitte geben Sie ein Wiederherstellungspasswort für das Administratorkonto an, da sonst alle Benutzerdaten verlorengehen können", "Wrong admin recovery password. Please check the password and try again." : "Falsches Wiederherstellungspasswort für das Admin-Konto. Bitte überprüfen Sie das Passwort und versuchen Sie es erneut.", "Backend doesn't support password change, but the user's encryption key was successfully updated." : "Das Backend unterstützt die Passwortänderung nicht, aber der Benutzerschlüssel wurde erfolgreich aktualisiert.", "installing and updating apps via the app store or Federated Cloud Sharing" : "Das Installieren und Aktualisieren von Apps durch den App-Store oder durch Federated Cloud Sharing", "Federated Cloud Sharing" : "Federated-Cloud-Sharing", "cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably." : "cURL verwendet eine veraltete %s Version (%s). Bitte aktualisieren Sie ihr Betriebssystem, da ansonsten Funktionen, wie z.B. %s, nicht zuverlässig funktionieren werden.", "A problem occurred, please check your log files (Error: %s)" : "Es ist ein Problem aufgetreten, bitte überprüfen Sie Ihre Logdateien (Fehler: %s)", "Migration Completed" : "Migration abgeschlossen", "Group already exists." : "Gruppe existiert bereits.", "Unable to add group." : "Gruppe konnte nicht angelegt werden.", "Unable to delete group." : "Gruppe konnte nicht gelöscht werden.", "test email settings" : "E-Mail-Einstellungen testen", "A problem occurred while sending the email. Please revise your settings. (Error: %s)" : "Beim Senden der E-Mail ist ein Problem aufgetreten. Bitte überprüfen Sie Ihre Einstellungen. (Fehler: %s)", "Email sent" : "E-Mail gesendet", "You need to set your user email before being able to send test emails." : "Sie müssen Ihre Benutzer-E-Mail-Adresse einstellen, bevor Sie Test-E-Mails versenden können.", "Invalid request" : "Ungültige Anforderung", "Invalid mail address" : "Ungültige E-Mail-Adresse", "No valid group selected" : "Keine gültige Gruppe ausgewählt", "A user with that name already exists." : "Ein Benutzer mit diesem Namen existiert bereits.", "To send a password link to the user an email address is required." : "Um einen Passwort-Link an einen Benutzer zu versenden wird eine E-Mail-Adresse benötigt.", "Unable to create user." : "Benutzer konnte nicht erstellt werden.", "Your %s account was created" : "Ihr %s-Konto wurde erstellt", "Unable to delete user." : "Benutzer konnte nicht gelöscht werden.", "Settings saved" : "Einstellungen gespeichert", "Unable to change full name" : "Der vollständige Name konnte nicht geändert werden", "Unable to change email address" : "E-Mail-Adresse konnte nicht geändert werden", "Your full name has been changed." : "Ihr vollständiger Name ist geändert worden.", "Forbidden" : "Verboten", "Invalid user" : "Ungültiger Benutzer", "Unable to change mail address" : "E-Mail-Adresse konnte nicht geändert werden", "Email saved" : "E-Mail-Adresse gespeichert", "Password confirmation is required" : "Passwortbestätigung erforderlich", "Couldn't remove app." : "Die App konnte nicht entfernt werden.", "Couldn't update app." : "Die App konnte nicht aktualisiert werden.", "Are you really sure you want add {domain} as trusted domain?" : "Sind Sie sich wirklich sicher, dass Sie {domain} als vertrauenswürdige Domain hinzufügen möchten?", "Add trusted domain" : "Vertrauenswürdige Domain hinzufügen", "Migration in progress. Please wait until the migration is finished" : "Migration in Arbeit. Bitte warten Sie, bis die Migration beendet ist", "Migration started …" : "Migration begonnen…", "Not saved" : "Nicht gespeichert", "Sending..." : "Wird gesendet…", "Official" : "Offiziell", "All" : "Alle", "Update to %s" : "Aktualisierung auf %s", "_You have %n app update pending_::_You have %n app updates pending_" : ["Es ist %n App-Aktualisierung verfügbar","Es sind %n App-Aktualisierungen verfügbar"], "No apps found for your version" : "Es wurden keine Apps für Ihre Version gefunden", "The app will be downloaded from the app store" : "Die App wird aus dem App-Store heruntergeladen", "Official apps are developed by and within the community. They offer central functionality and are ready for production use." : "Offizielle Apps werden von und innerhalb der Community entwickelt. Sie stellen die zentralen Funktionen bereit und sind für den produktiven Einsatz geeignet.", "Approved apps are developed by trusted developers and have passed a cursory security check. They are actively maintained in an open code repository and their maintainers deem them to be stable for casual to normal use." : "Geprüfte Apps werden von vertrauenswürdigen Entwicklern entwickelt und haben eine oberflächliche Sicherheitsprüfung durchlaufen. Sie werden innerhalb eines offenen Code-Repositorys aktiv gepflegt und ihre Betreuer erachten sie als stabil genug für für den gelegentlichen bis normalen Einsatz.", "This app is not checked for security issues and is new or known to be unstable. Install at your own risk." : "Diese App ist nicht auf Sicherheitsprobleme hin überprüft und ist neu oder bekanntermaßen instabil. Die Installation erfolgt auf eigenes Risiko.", "Disabling app …" : "App wird deaktiviert …", "Error while disabling app" : "Beim Deaktivieren der App ist ein Fehler aufgetreten", "Disable" : "Deaktivieren", "Enable" : "Aktivieren", "Enabling app …" : "Aktiviere App ...", "Error while enabling app" : "Beim Aktivieren der App ist ein Fehler aufgetreten", "Error: this app cannot be enabled because it makes the server unstable" : "Fehler: Diese App kann nicht aktiviert werden, da es den Server instabil macht.", "Error: could not disable broken app" : "Fehler: Die beschädigte Anwendung konnte nicht deaktiviert werden", "Error while disabling broken app" : "Beim Deaktivieren der defekten App ist ein Fehler aufgetreten", "Updating...." : "Aktualisiere…", "Error while updating app" : "Es ist ein Fehler während der Aktualisierung aufgetreten", "Updated" : "Aktualisiert", "Uninstalling ...." : "Wird deinstalliert…", "Error while uninstalling app" : "Fehler beim Deinstallieren der App", "Uninstall" : "Deinstallieren", "The app has been enabled but needs to be updated. You will be redirected to the update page in 5 seconds." : "Die App wurde aktiviert, aber sie benötigt ein Update. Sie werden zur Update Seite in 5 Sekunden weitergeleitet.", "App update" : "App aktualisieren", "Approved" : "Geprüft", "Experimental" : "Experimentell", "No apps found for {query}" : "Keine Applikationen für {query} gefunden", "Allow filesystem access" : "Erlaube Dateisystem-Zugriff", "Disconnect" : "Trennen", "Revoke" : "Widerrufen", "Internet Explorer" : "Internet Explorer", "Edge" : "Edge", "Firefox" : "Firefox", "Google Chrome" : "Google Chrome", "Safari" : "Safari", "Google Chrome for Android" : "Google Chrome für Android", "iPhone iOS" : "iPhone iOS", "iPad iOS" : "iPad iOS", "iOS Client" : "iOS-Client", "Android Client" : "Android-Client", "Sync client - {os}" : "Sync-Client - {os}", "This session" : "Diese Sitzung", "Copy" : "Kopieren", "Copied!" : "Kopiert!", "Not supported!" : "Nicht unterstützt!", "Press ⌘-C to copy." : "⌘-C zum Kopieren drücken.", "Press Ctrl-C to copy." : "Ctrl-C zum Kopieren drücken.", "Error while loading browser sessions and device tokens" : "Fehler beim Laden der Browser-Sitzungen und Geräte-Token", "Error while creating device token" : "Fehler beim Erstellen des Geräte-Tokens", "Error while deleting the token" : "Fehler beim Löschen des Geräte-Tokens", "An error occurred. Please upload an ASCII-encoded PEM certificate." : "Es ist ein Fehler aufgetreten. Bitte laden Sie ein ASCII-kodiertes PEM-Zertifikat hoch.", "Valid until {date}" : "Gültig bis {date}", "Delete" : "Löschen", "Local" : "Lokal", "Private" : "Privat", "Only visible to local users" : "Nur für lokale Benutzer sichtbar", "Only visible to you" : "Nur für Sie sichtbar", "Contacts" : "Kontakte", "Visible to local users and to trusted servers" : "Sichtbar für lokale Nutzer und vertrauenswürdige Server", "Public" : "Öffentlich", "Will be synced to a global and public address book" : "Wird mit einem globalen und einem öffentlichen Adressbuch synchronisiert", "Select a profile picture" : "Wählen Sie ein Profilbild", "Very weak password" : "Sehr schwaches Passwort", "Weak password" : "Schwaches Passwort", "So-so password" : "Akzeptables Passwort", "Good password" : "Gutes Passwort", "Strong password" : "Starkes Passwort", "Groups" : "Gruppen", "Unable to delete {objName}" : "Löschen von {objName} nicht möglich", "Error creating group: {message}" : "Fehler beim Erstellen einer Gruppe: {message}", "A valid group name must be provided" : "Ein gültiger Gruppenname muss angegeben werden", "deleted {groupName}" : "{groupName} gelöscht", "undo" : "rückgängig machen", "never" : "niemals", "deleted {userName}" : "{userName} gelöscht", "Unable to add user to group {group}" : "Benutzer kann nicht zur Gruppe {group} hinzugefügt werden ", "Unable to remove user from group {group}" : "Benutzer kann nicht aus der Gruppe {group} entfernt werden ", "Add group" : "Gruppe hinzufügen", "Invalid quota value \"{val}\"" : "Ungültiger Grenzwert \"{val}\"", "no group" : "Keine Gruppe", "Password successfully changed" : "Das Passwort wurde erfolgreich geändert", "Changing the password will result in data loss, because data recovery is not available for this user" : "Die Änderung des Passworts führt zu Datenverlust, weil die Datenwiederherstellung für diesen Benutzer nicht verfügbar ist", "Could not change the users email" : "Die E-Mail-Adresse des Nutzers konnte nicht geändert werden", "A valid username must be provided" : "Es muss ein gültiger Benutzername angegeben werden", "Error creating user: {message}" : "Fehler beim Erstellen eines Benutzers: {message}", "A valid password must be provided" : "Es muss ein gültiges Passwort angegeben werden", "A valid email must be provided" : "Es muss eine gültige E-Mail-Adresse angegeben werden", "__language_name__" : "Deutsch (Förmlich: Sie)", "Unlimited" : "Unbegrenzt", "Personal info" : "Persönliche Informationen", "Sessions" : "Sitzungen", "App passwords" : "App-PINs", "Sync clients" : "Sync-Clients", "None" : "Keine", "Login" : "Anmelden", "Plain" : "Klartext", "NT LAN Manager" : "NT-LAN-Manager", "SSL/TLS" : "SSL/TLS", "STARTTLS" : "STARTTLS", "Email server" : "E-Mail-Server", "Open documentation" : "Dokumentation öffnen", "This is used for sending out notifications." : "Dies wird für das Senden von Benachrichtigungen verwendet.", "Send mode" : "Sendemodus", "Encryption" : "Verschlüsselung", "From address" : "Absenderadresse", "mail" : "Mail", "Authentication method" : "Authentifizierungsmethode", "Authentication required" : "Authentifizierung benötigt", "Server address" : "Serveradresse", "Port" : "Port", "Credentials" : "Zugangsdaten", "SMTP Username" : "SMTP-Benutzername", "SMTP Password" : "SMTP-Passwort", "Store credentials" : "Anmeldeinformationen speichern", "Test email settings" : "E-Mail-Einstellungen testen", "Send email" : "E-Mail senden", "Server-side encryption" : "Serverseitige Verschlüsselung", "Enable server-side encryption" : "Serverseitige Verschlüsselung aktivieren", "Please read carefully before activating server-side encryption: " : "Bitte lesen Sie ganz genau, bevor Sie die serverseitige Verschlüsselung aktivieren:", "Once encryption is enabled, all files uploaded to the server from that point forward will be encrypted at rest on the server. It will only be possible to disable encryption at a later date if the active encryption module supports that function, and all pre-conditions (e.g. setting a recover key) are met." : "Wird die Verschlüsselung einmal aktiviert, so werden alle ab diesem Zeitpunkt hochgeladene Dateien verschlüsselt. Sie kann nur wieder deaktiviert werden, wenn das Verschlüsselungsmodul dies unterstützt und alle Voraussetzungen (wie das Setzen eines Wiederherstellungsschlüssels) im Vorhinein erfüllt wurden.", "Encryption alone does not guarantee security of the system. Please see documentation for more information about how the encryption app works, and the supported use cases." : "Verschlüsselung alleine garantiert nicht die Systemsicherheit. Bitte lese in der Dokumentation nach, wie die Verschlüsselungs-app funktioniert und welche Anwendungsfälle unterstützt werden.", "Be aware that encryption always increases the file size." : "Bedenken Sie, dass durch die Verschlüsselung die Dateigröße zunimmt. ", "It is always good to create regular backups of your data, in case of encryption make sure to backup the encryption keys along with your data." : "Es ist immer gut, regelmäßig Sicherungskopien von ihren Daten zu machen. Falls Sie die Verschlüsselung nutzen, sollten Sie auch eine Sicherung der Verschlüsselungsschlüssel zusammen mit ihren Daten machen.", "This is the final warning: Do you really want to enable encryption?" : "Dies ist die letzte Warnung: Wollen Sie die Verschlüsselung wirklich aktivieren?", "Enable encryption" : "Verschlüsselung aktivieren", "No encryption module loaded, please enable an encryption module in the app menu." : "Kein Verschlüsselungs-Modul geladen, bitte aktiviere ein Verschlüsselungs-Modul im Anwendungs-Menü.", "Select default encryption module:" : "Standard-Verschlüsselungs-Modul auswählen:", "You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please enable the \"Default encryption module\" and run 'occ encryption:migrate'" : "Sie müssen Ihre Verschlüsselungsschlüssel von der alten Verschlüsselung (ownCloud <= 8.0) zur Neuen migrieren. Bitte aktivieren Sie das \"Default Encryption Module\" und rufen Sie 'occ encryption:migrate' auf.", "You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one." : "Sie müssen Ihre Verschlüsselungsschlüssel von der alten Verschlüsselung (ownCloud <= 8.0) zur Neuen migrieren.", "Start migration" : "Migration beginnen", "Security & setup warnings" : "Sicherheits- & Einrichtungswarnungen", "php does not seem to be setup properly to query system environment variables. The test with getenv(\"PATH\") only returns an empty response." : "PHP scheint zur Abfrage von Systemumgebungsvariablen nicht richtig eingerichtet zu sein. Der Test mit getenv (\"PATH\") liefert nur eine leere Antwort zurück.", "Please check the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">installation documentation ↗</a> for php configuration notes and the php configuration of your server, especially when using php-fpm." : "Bitte schauen Sie in der <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Installationsdokumentation ↗</a>auf Hinweise zur PHP-Konfiguration, sowie die PHP-Konfiguration ihres Servers, insbesondere dann, wenn Sie PHP-FPM einsetzten.", "The Read-Only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Die schreibgeschützte Konfiguration wurde aktiviert. Dies verhindert das Setzen einiger Einstellungen über die Web-Schnittstelle. Weiterhin muss bei jedem Update der Schreibzugriff auf die Datei händisch aktiviert werden.", "PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." : "PHP ist offenbar so konfiguriert, dass PHPDoc-Blöcke in der Anweisung entfernt werden. Dadurch sind mehrere Kern-Apps nicht erreichbar.", "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Dies wird wahrscheinlich durch Zwischenspeicher/Beschleuniger wie etwa Zend OPcache oder eAccelerator verursacht.", "Your database does not run with \"READ COMMITTED\" transaction isolation level. This can cause problems when multiple actions are executed in parallel." : "Ihre Datenbank läuft nicht mit der \"READ COMMITED\" Transaktionsisolationsstufe. Dies kann Probleme hervorrufen, wenn mehrere Aktionen parallel ausgeführt werden.", "%1$s below version %2$s is installed, for stability and performance reasons we recommend updating to a newer %1$s version." : "%1$s ist in einer älteren Version als %2$s installiert. Aus Stabilitäts- und Performancegründen empfehlen wir eine Aktualisierung auf eine neuere %1$s-Version", "The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "Das PHP-Modul 'fileinfo' fehlt. Wir empfehlen Ihnen dieses Modul zu aktivieren, um die besten Resultate bei der Bestimmung der Dateitypen zu erzielen.", "Transactional file locking is disabled, this might lead to issues with race conditions. Enable 'filelocking.enabled' in config.php to avoid these problems. See the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a> for more information." : "Transaktionales Sperren ist deaktiviert, was zu Problemen mit Laufzeitbedingungen führen kann. Aktivieren Sie 'filelocking.enabled' in der config.php diese Probleme zu vermeiden. Weitere Informationen findest Sie in unserer <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Dokumentation ↗</a>.", "System locale can not be set to a one which supports UTF-8." : "Es kann kein Systemgebietsschema gesetzt werden, das UTF-8 unterstützt.", "This means that there might be problems with certain characters in file names." : "Dies bedeutet, dass es zu Problemen mit bestimmten Zeichen in Dateinamen kommen kann.", "We strongly suggest installing the required packages on your system to support one of the following locales: %s." : "Wir empfehlen dringend, die erforderlichen Pakete auf Ihrem System zu installieren, damit eines der folgenden Gebietsschemata unterstützt wird: %s.", "If your installation is not installed in the root of the domain and uses system cron, there can be issues with the URL generation. To avoid these problems, please set the \"overwrite.cli.url\" option in your config.php file to the webroot path of your installation (Suggested: \"%s\")" : "Wenn sich Ihre Installation nicht im Wurzelverzeichnis der Domain befindet und Cron aus dem System genutzt wird, kann es zu Fehlern bei der URL-Generierung kommen. Um dies zu verhindern, setzen Sie bitte die „overwrite.cli.url“-Option in Ihrer config.php auf das Web-Wurzelverzeichnis Ihrer Installation (Vorschlag: „%s“).", "It was not possible to execute the cronjob via CLI. The following technical errors have appeared:" : "Die Ausführung des Cron-Jobs über die Kommandozeile war nicht möglich. Die folgenden technischen Fehler sind dabei aufgetreten:", "Please double check the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">installation guides ↗</a>, and check for any errors or warnings in the <a href=\"%s\">log</a>." : "Bitte überprüfen Sie noch einmal die <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Installationsanleitungen ↗</a> und kontrollieren Sie das <a href=\"%s\">Log</a> auf mögliche Fehler oder Warnungen.", "All checks passed." : "Alle Checks bestanden.", "Cron" : "Cron", "Last cron job execution: %s." : "Letzte Cron-Job-Ausführung: %s.", "Last cron job execution: %s. Something seems wrong." : "Letzte Cron-Job-Ausführung: %s. Möglicherweise liegt ein Fehler vor.", "Cron was not executed yet!" : "Cron wurde bislang noch nicht ausgeführt!", "Execute one task with each page loaded" : "Eine Aufgabe bei jedem Laden einer Seite ausführen", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php ist als Webcron-Dienst registriert, der die cron.php alle 15 Minuten per HTTP aufruft.", "Use system's cron service to call the cron.php file every 15 minutes." : "Benutzen Sie den systemeigenen Cron-Dienst, um die cron.php alle 15 Minuten aufzurufen.", "The cron.php needs to be executed by the system user \"%s\"." : "Die cron.php muss durch den Systemnutzer \"%s\" ausgeführt werden.", "To run this you need the PHP posix extension. See {linkstart}PHP documentation{linkend} for more details." : "Um dies auszuführen, benötigen Sie die PHP-Posix Erweiterung. Weitere Informationen in der {linkstart}PHP-Dokumentation{linkend}.", "Version" : "Version", "Sharing" : "Teilen", "Allow apps to use the Share API" : "Apps die Benutzung der Share-API erlauben", "Allow users to share via link" : "Benutzern erlauben, Inhalte über Links zu teilen", "Allow public uploads" : "Öffentliches Hochladen erlauben", "Enforce password protection" : "Passwortschutz erzwingen", "Set default expiration date" : "Standardmäßiges Ablaufdatum setzen", "Expire after " : "Ablauf nach ", "days" : "Tagen", "Enforce expiration date" : "Ablaufdatum erzwingen", "Allow resharing" : "Weiterteilen erlauben", "Allow sharing with groups" : "Mit Gruppen teilen erlauben", "Restrict users to only share with users in their groups" : "Benutzer auf das Teilen innerhalb ihrer Gruppen beschränken", "Exclude groups from sharing" : "Gruppen von Freigaben ausschließen", "These groups will still be able to receive shares, but not to initiate them." : "Diese Gruppen können weiterhin Freigaben empfangen, aber selbst keine mehr initiieren.", "Allow username autocompletion in share dialog. If this is disabled the full username needs to be entered." : "Die Auto-Vervollständigung von Benutzernamen im Teilen-Dialog erlauben. Wenn dies deaktiviert ist, muss der vollständige Benutzername eingegeben werden.", "Show disclaimer text on the public link upload page. (Only shown when the file list is hidden.)" : "Zeige Haftungsausschluss auf der öffentlichen Upload-Seite. (Wird nur gezeigt wenn die Dateiliste nicht angezeigt wird.) ", "This text will be shown on the public link upload page when the file list is hidden." : "Dieser Text wird auf der öffentlichen Upload-Seite angezeigt wenn die Dateiliste nicht angezeigt wird.", "Tips & tricks" : "Tipps & Tricks", "SQLite is currently being used as the backend database. For larger installations we recommend that you switch to a different database backend." : "SQLite wird als Datenbank verwendet. Bei größeren Installationen empfehlen wir, auf ein anderes Datenbank-Backend zu wechseln.", "This is particularly recommended when using the desktop client for file synchronisation." : "Dies wird insbesondere bei der Benutzung des Dektop-Clients zur Synchronisierung empfohlen.", "To migrate to another database use the command line tool: 'occ db:convert-type', or see the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a>." : "Um zu einer anderen Datenbank zu migrieren, benutzen Sie bitte die Kommandozeile: 'occ db:convert-type', oder in die <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Dokumentation ↗</a> schauen.", "How to do backups" : "Wie man Datensicherungen anlegt", "Advanced monitoring" : "Erweitertes Monitoring", "Performance tuning" : "Leistungsoptimierung", "Improving the config.php" : "Die config.php optimieren", "Theming" : "Themes verwenden", "Hardening and security guidance" : "Systemhärtung und Sicherheitsempfehlungen", "Developer documentation" : "Dokumentation für Entwickler", "by %s" : "von %s", "%s-licensed" : "%s-Lizensiert", "Documentation:" : "Dokumentation:", "User documentation" : "Benutzer-Dokumentation", "Admin documentation" : "Administratoren-Dokumentation", "Visit website" : "Webseite besuchen", "Report a bug" : "Melden Sie einen technischen Fehler", "Show description …" : "Beschreibung anzeigen…", "Hide description …" : "Beschreibung ausblenden…", "This app has an update available." : "Für diese Anwendung ist eine Aktualisierung verfügbar.", "This app has no minimum Nextcloud version assigned. This will be an error in the future." : "Für diese App wurde keine untere Versionsgrenze für Nextcloud gesetzt. Dies wird zukünftig als Fehler behandelt.", "This app has no maximum Nextcloud version assigned. This will be an error in the future." : "Für diese App wurde keine obere Versionsgrenze für Nextcloud gesetzt. Dies wird zukünftig als Fehler behandelt.", "This app cannot be installed because the following dependencies are not fulfilled:" : "Diese App kann nicht installiert werden, weil die folgenden Abhängigkeiten nicht erfüllt sind:", "Enable only for specific groups" : "Nur für bestimmte Gruppen aktivieren", "Uninstall app" : "App deinstallieren", "SSL Root Certificates" : "SSL Root Zertifikate", "Common Name" : "Allgemeiner Name", "Valid until" : "Gültig bis", "Issued By" : "Ausgestellt von:", "Valid until %s" : "Gültig bis %s", "Import root certificate" : "Root-Zertifikat importieren", "Hey there,<br><br>just letting you know that you now have a %s account.<br><br>Your username: <strong>%s</strong><br>Access it: <strong><a href=\"%s\">%s</a></strong><br><br>" : "Hallo,<br><br>hier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.<br><br>Ihr Benutzername: <strong>%s</strong><br>Greifen Sie darauf zu: <strong><a href=\"%s\">%s</a></strong><br><br>", "Cheers!" : "Noch einen schönen Tag!", "Hey there,\n\njust letting you know that you now have a %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Hallo,\n\nhier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.\n\nIhr Benutzername: %s\nZugriff: %s\n\n", "Administrator documentation" : "Dokumentation für Administratoren", "Online documentation" : "Online-Dokumentation", "Forum" : "Forum", "Getting help" : "Hilfe bekommen", "Commercial support" : "Kommerzieller Support", "You are using <strong>%s</strong> of <strong>%s</strong>" : "Sie verwenden <strong>%s</strong> der verfügbaren <strong>%s</strong>", "Profile picture" : "Profilbild", "Upload new" : "Neues hochladen", "Select from Files" : "Aus Dateien wählen", "Remove image" : "Bild entfernen", "png or jpg, max. 20 MB" : "png oder jpg, max. 20 MB", "Picture provided by original account" : "Bild von Original-Konto zur Verfügung gestellt", "Cancel" : "Abbrechen", "Choose as profile picture" : "Als Profilbild auswählen", "Full name" : "Vollständiger Name", "No display name set" : "Kein Anzeigename angegeben", "Email" : "E-Mail", "Your email address" : "Ihre E-Mail-Adresse", "No email address set" : "Keine E-Mail-Adresse angegeben", "For password reset and notifications" : "Für Passwort-Wiederherstellung und Benachrichtigungen", "Phone number" : "Telefonnummer", "Your phone number" : "Ihre Telefonnummer", "Address" : "Adresse", "Your postal address" : "Ihre Postadresse", "Website" : "Webseite", "Your website" : "Ihre Internetseite", "Twitter" : "Twitter", "Your Twitter handle" : "Ihr Twitter-Handle", "You are member of the following groups:" : "Sie sind Mitglied folgender Gruppen:", "Password" : "Passwort", "Current password" : "Aktuelles Passwort", "New password" : "Neues Passwort", "Change password" : "Passwort ändern", "Language" : "Sprache", "Help translate" : "Helfen Sie bei der Übersetzung", "Get the apps to sync your files" : "Installieren Sie die Anwendungen, um Ihre Dateien zu synchronisieren", "Desktop client" : "Desktop-Client", "Android app" : "Android-App", "iOS app" : "iOS-App", "If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!" : "Wenn Sie das Projekt unterstützen wollen {contributeopen} helfen Sie bei der Entwicklung{linkclose} oder {contributeopen} verbreiten Sie es{linkclose}!", "Show First Run Wizard again" : "Den Einrichtungsassistenten erneut anzeigen", "Web, desktop and mobile clients currently logged in to your account." : "Aktuell in Ihrem Konto eingeloggte Web-, Desktop- und Mobil-Clients.", "Device" : "Gerät", "Last activity" : "Letzte Aktivität", "Passcodes that give an app or device permissions to access your account." : "PINs mit denen Apps oder Geräte auf Ihr Konto zugreifen können.", "Name" : "Name", "App name" : "App-Name", "Create new app password" : "Neues App-Passwort erstellen", "Use the credentials below to configure your app or device." : "Nutzen Sie die unten angebenen Anmeldeinformationen, um ihre App oder ihr Gerät zu konfigurieren.", "For security reasons this password will only be shown once." : "Aus Sicherheitsgründen wird das Passwort nur einmal angezeigt.", "Username" : "Benutzername", "Done" : "Erledigt", "Developed by the {communityopen}Nextcloud community{linkclose}, the {githubopen}source code{linkclose} is licensed under the {licenseopen}AGPL{linkclose}." : "Entwickelt von der {communityopen}Nextcloud Community{linkclose}, der {githubopen}Quellcode{linkclose} ist lizensiert unter {licenseopen}AGPL{linkclose}-Lizenz.", "Follow us on Google Plus!" : "Folgen Sie uns zu Google Plus!", "Like our facebook page!" : "Liken Sie uns auf unserer Facebook-Seite!", "Subscribe to our twitter channel!" : "Abonnieren Sie unseren Twitter-Kanal!", "Subscribe to our news feed!" : "Abonnieren Sie unseren RSS-Feed!", "Subscribe to our newsletter!" : "Abonnieren Sie unseren Newsletter!", "Show storage location" : "Speicherort anzeigen", "Show last log in" : "Letzte Anmeldung anzeigen", "Show user backend" : "Benutzer-Backend anzeigen", "Send email to new user" : "E-Mail an neuen Benutzer senden", "When the password of the new user is left empty an activation email with a link to set the password is send to the user" : "Wenn das Passwort für den neuen Benutzer leer gelassen wird, wird an ihn eine Aktivierungs-E-Mail mit einem Link zur Passwortvergabe versandt.", "Show email address" : "E-Mail Adresse anzeigen", "E-Mail" : "E-Mail", "Create" : "Erstellen", "Admin Recovery Password" : "Admin-Passwort-Wiederherstellung", "Enter the recovery password in order to recover the users files during password change" : "Geben Sie das Wiederherstellungspasswort ein, um die Benutzerdateien während der Passwortänderung wiederherzustellen", "Group name" : "Gruppenname", "Everyone" : "Jeder", "Admins" : "Administratoren", "Default quota" : "Standard-Kontingent", "Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Bitte Speicherkontingent eingeben (z.B.: „512 MB“ oder „12 GB“)", "Other" : "Andere", "Group admin for" : "Gruppenadministrator für", "Quota" : "Kontingent", "Storage location" : "Speicherort", "User backend" : "Benutzer-Backend", "Last login" : "Letzte Anmeldung", "change full name" : "Vollständigen Namen ändern", "set new password" : "Neues Passwort setzen", "change email address" : "E-Mail-Adresse ändern", "Default" : "Standard", "log-level out of allowed range" : "Log-Level außerhalb des erlaubten Bereichs", "Language changed" : "Sprache geändert", "Admins can't remove themself from the admin group" : "Administratoren können sich nicht selbst aus der admin-Gruppe löschen", "Unable to add user to group %s" : "Der Benutzer konnte nicht zur Gruppe %s hinzugefügt werden", "Unable to remove user from group %s" : "Der Benutzer konnte nicht aus der Gruppe %s entfernt werden", "Are you really sure you want add \"{domain}\" as trusted domain?" : "Sind Sie sich wirklich sicher, dass Sie \"{domain}\" als vertrauenswürdige Domain hinzufügen möchten?", "Please wait...." : "Bitte warten…", "add group" : "Gruppe hinzufügen", "Everything (fatal issues, errors, warnings, info, debug)" : "Alles (fatale Probleme, Fehler, Warnungen, Infos, Fehlerdiagnose)", "Info, warnings, errors and fatal issues" : "Infos, Warnungen, Fehler und fatale Probleme", "Warnings, errors and fatal issues" : "Warnungen, Fehler und fatale Probleme", "Errors and fatal issues" : "Fehler und fatale Probleme", "Fatal issues only" : "Nur kritische Fehler", "Log" : "Log", "What to log" : "Was geloggt wird", "Download logfile" : "Logdatei herunterladen", "More" : "Mehr", "Less" : "Weniger", "The logfile is bigger than 100 MB. Downloading it may take some time!" : "Die Logdatei ist größer als 100 MB. Es kann etwas Zeit beanspruchen, sie herunterzuladen!", "Allow users to send mail notification for shared files" : "Benutzern erlauben, E-Mail-Benachrichtigungen für freigegebene Dateien zu senden", "Allow users to send mail notification for shared files to other users" : "Benutzern erlauben, E-Mail-Benachrichtigungen für freigegebene Dateien an andere Benutzer zu senden", "SQLite is used as database. For larger installations we recommend to switch to a different database backend." : "SQLite wird als Datenbank verwendet. Bei größeren Installationen wird empfohlen, auf ein anderes Datenbank-Backend zu wechseln.", "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "Insbesondere bei der Nutzung des Desktop Clients zur Dateisynchronisierung wird vom Einsatz von SQLite abgeraten.", "Experimental applications ahead" : "Experimentelle Apps nachfolgend", "Experimental apps are not checked for security issues, new or known to be unstable and under heavy development. Installing them can cause data loss or security breaches." : "Experimentelle Apps sind nicht auf Sicherheitsprobleme hin überprüft, sind neu oder bekanntermaßen instabil und befinden sich in intensiver Entwicklung. Ihre Installation kann Datenverlust oder Sicherheitslücken hervorrufen.", "Uninstall App" : "App deinstallieren", "Enable experimental apps" : "Experimentelle Apps aktivieren", "Hey there,<br><br>just letting you know that you now have an %s account.<br><br>Your username: %s<br>Access it: <a href=\"%s\">%s</a><br><br>" : "Hallo,<br><br>hier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.<br><br>Ihr Benutzername: %s<br>Greifen Sie darauf zu: <a href=\"%s\">%s</a><br><br>", "Hey there,\n\njust letting you know that you now have an %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Hallo,\n\nhier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.\n\nIhr Benutzername: %s\nGreifen Sie darauf zu: %s\n\n", "For password recovery and notifications" : "Für Passwort-Wiederherstellung und Benachrichtigungen", "If you want to support the project\n\t\t<a href=\"https://nextcloud.com/contribute\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">join development</a>\n\t\tor\n\t\t<a href=\"https://nextcloud.com/contribute\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">spread the word</a>!" : "Wenn Sie das Projekt unterstützen möchten\n⇥⇥<a href=\"https://nextcloud.com/contribute\"\n⇥⇥⇥target=\"_blank\" rel=\"noreferrer\">helfen Sie bei der Weiterentwicklung</a>\n⇥⇥oder\n⇥⇥<a href=\"https://nextcloud.com/contribute\"\n⇥⇥⇥target=\"_blank\" rel=\"noreferrer\">empfehlen Sie es weiter</a>!", "Add Group" : "Gruppe hinzufügen", "Group" : "Gruppe", "Default Quota" : "Standard-Quota", "Full Name" : "Vollständiger Name", "Group Admin for" : "Gruppenadministrator für", "Storage Location" : "Speicherort", "User Backend" : "Benutzer-Backend", "Last Login" : "Letzte Anmeldung" }, "nplurals=2; plural=(n != 1);");
whitekiba/server
settings/l10n/de_DE.js
JavaScript
agpl-3.0
36,870
<?php namespace SPHERE\Application\People\Relationship; use SPHERE\Application\Corporation\Company\Company; use SPHERE\Application\Corporation\Company\Service\Entity\TblCompany; use SPHERE\Application\People\Meta\Common\Common; use SPHERE\Application\People\Person\Person; use SPHERE\Application\People\Person\Service\Entity\TblPerson; use SPHERE\Application\People\Relationship\Service\Data; use SPHERE\Application\People\Relationship\Service\Entity\TblGroup; use SPHERE\Application\People\Relationship\Service\Entity\TblSiblingRank; use SPHERE\Application\People\Relationship\Service\Entity\TblToCompany; use SPHERE\Application\People\Relationship\Service\Entity\TblToPerson; use SPHERE\Application\People\Relationship\Service\Entity\TblType; use SPHERE\Application\People\Relationship\Service\Entity\ViewRelationshipFromPerson; use SPHERE\Application\People\Relationship\Service\Entity\ViewRelationshipToCompany; use SPHERE\Application\People\Relationship\Service\Entity\ViewRelationshipToPerson; use SPHERE\Application\People\Relationship\Service\Setup; use SPHERE\Common\Frontend\Form\IFormInterface; use SPHERE\Common\Frontend\Form\Structure\FormColumn; use SPHERE\Common\Frontend\Form\Structure\FormGroup; use SPHERE\Common\Frontend\Form\Structure\FormRow; use SPHERE\Common\Frontend\Icon\Repository\Ban; use SPHERE\Common\Frontend\Message\Repository\Danger; use SPHERE\Common\Frontend\Message\Repository\Success; use SPHERE\Common\Window\Redirect; use SPHERE\System\Database\Binding\AbstractService; /** * Class Service * * @package SPHERE\Application\People\Relationship */ class Service extends AbstractService { /** * @return false|ViewRelationshipToPerson[] */ public function viewRelationshipToPerson() { return (new Data($this->getBinding()))->viewRelationshipToPerson(); } /** * @return false|ViewRelationshipFromPerson[] */ public function viewRelationshipFromPerson() { return ( new Data($this->getBinding()) )->viewRelationshipFromPerson(); } /** * @return false|ViewRelationshipToCompany[] */ public function viewRelationshipToCompany() { return ( new Data($this->getBinding()) )->viewRelationshipToCompany(); } /** * @param bool $doSimulation * @param bool $withData * * @return string */ public function setupService($doSimulation, $withData) { $Protocol = (new Setup($this->getStructure()))->setupDatabaseSchema($doSimulation); if (!$doSimulation && $withData) { (new Data($this->getBinding()))->setupDatabaseContent(); } return $Protocol; } /** * @param TblPerson $tblPerson * @param TblType|null $tblType * * @return bool|TblToPerson[] */ public function getPersonRelationshipAllByPerson(TblPerson $tblPerson, TblType $tblType = null) { return (new Data($this->getBinding()))->getPersonRelationshipAllByPerson($tblPerson, $tblType); } /** * @param TblToPerson[] $tblToPersonList * * @return array|TblPerson[] * sortet by Gender (0 => mother - 1 = father - 2... => unknown) * without hits on Mother or Father the unknown get the 0 and 1 */ public function getPersonGuardianAllByToPersonList($tblToPersonList) { $GuardianList = array(); if ($tblToPersonList && !empty($tblToPersonList)) { $i = 2; foreach ($tblToPersonList as $tblToPerson) { $tblPersonGuardian = $tblToPerson->getServiceTblPersonFrom(); // get Gender $Gender = ''; if ($tblPersonGuardian && ($common = Common::useService()->getCommonByPerson($tblPersonGuardian))) { if (($tblCommonBirthDates = $common->getTblCommonBirthDates())) { if (($tblCommonGender = $tblCommonBirthDates->getTblCommonGender())) { $Gender = $tblCommonGender->getName(); } } } if ($Gender == '') { $Salutation = $tblPersonGuardian->getSalutation(); if ($Salutation == 'Frau') { $Gender = 'Weiblich'; } elseif ($Salutation == 'Herr') { $Gender = 'Männlich'; } } // get sorted List (0 => Mother; 1 => Father; 2.. => Other ) if ($Gender == 'Weiblich') { if (isset($GuardianList[0])) { if (!isset($GuardianList[1])) { $GuardianList[1] = $GuardianList[0]; } else { $GuardianList[$i++] = $GuardianList[0]; } } $GuardianList[0] = $tblToPerson->getServiceTblPersonFrom(); } elseif (!isset($GuardianList[1]) && $Gender == 'Männlich') { if (isset($GuardianList[1])) { if (!isset($GuardianList[0])) { $GuardianList[0] = $GuardianList[1]; } else { $GuardianList[$i++] = $GuardianList[1]; } } $GuardianList[1] = $tblToPerson->getServiceTblPersonFrom(); } else { // if no matches set unknown to Mother/Father to keep it running $GuardianList[] = $tblToPerson->getServiceTblPersonFrom(); } } } return $GuardianList; } /** * @param TblPerson $tblPerson * * @return bool|TblToCompany[] */ public function getCompanyRelationshipAllByPerson(TblPerson $tblPerson) { return (new Data($this->getBinding()))->getCompanyRelationshipAllByPerson($tblPerson); } /** * @param TblCompany $tblCompany * * @return bool|TblToCompany[] */ public function getCompanyRelationshipAllByCompany(TblCompany $tblCompany) { return (new Data($this->getBinding()))->getCompanyRelationshipAllByCompany($tblCompany); } /** * @param IFormInterface $Form * @param TblPerson $tblPersonFrom * @param int $tblPersonTo * @param array $Type * * @return IFormInterface|string */ public function createRelationshipToPerson( IFormInterface $Form, TblPerson $tblPersonFrom, $tblPersonTo, $Type ) { /** * Skip to Frontend */ if (null === $Type) { return $Form; } $Error = false; if (empty($tblPersonTo)) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Person'))))); $Error = true; } else { $tblPersonTo = Person::useService()->getPersonById($tblPersonTo); if (!$tblPersonTo){ $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Person'))))); $Error = true; } elseif ($tblPersonFrom->getId() == $tblPersonTo->getId()) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger( 'Eine Person kann nur mit einer anderen Person verknüpft werden'))))); $Error = true; } } if (!($tblType = $this->getTypeById($Type['Type']))){ $Form->setError('Type[Type]', 'Bitte geben Sie einen Typ an'); $Error = true; } else { $Form->setSuccess('Type[Type]'); } if (!$Error) { if ((new Data($this->getBinding()))->addPersonRelationshipToPerson($tblPersonFrom, $tblPersonTo, $tblType, $Type['Remark']) ) { return new Success(new \SPHERE\Common\Frontend\Icon\Repository\Success() . ' Die Beziehung wurde erfolgreich hinzugefügt') . new Redirect('/People/Person', Redirect::TIMEOUT_SUCCESS, array('Id' => $tblPersonFrom->getId())); } else { return new Danger(new Ban() . ' Die Beziehung konnte nicht hinzugefügt werden') . new Redirect('/People/Person', Redirect::TIMEOUT_ERROR, array('Id' => $tblPersonFrom->getId())); } } return $Form; } /** * @param integer $Id * * @return bool|TblType */ public function getTypeById($Id) { return (new Data($this->getBinding()))->getTypeById($Id); } /** * @param TblGroup|null $tblGroup * * @return bool|TblType[] */ public function getTypeAllByGroup(TblGroup $tblGroup = null) { return (new Data($this->getBinding()))->getTypeAllByGroup($tblGroup); } /** * @param integer $Id * * @return bool|TblGroup */ public function getGroupById($Id) { return (new Data($this->getBinding()))->getGroupById($Id); } /** * @param string $Identifier * * @return bool|TblGroup */ public function getGroupByIdentifier($Identifier) { return (new Data($this->getBinding()))->getGroupByIdentifier($Identifier); } /** * @param IFormInterface $Form * @param TblPerson $tblPersonFrom * @param int $tblCompanyTo * @param array $Type * * @return IFormInterface|string */ public function createRelationshipToCompany( IFormInterface $Form, TblPerson $tblPersonFrom, $tblCompanyTo, $Type ) { /** * Skip to Frontend */ if (null === $Type) { return $Form; } $Error = false; if (empty($tblCompanyTo)) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Institution'))))); $Error = true; } else { $tblCompanyTo = Company::useService()->getCompanyById($tblCompanyTo); if (!$tblCompanyTo){ $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Institution'))))); $Error = true; } } if (!($tblType = $this->getTypeById($Type['Type']))){ $Form->setError('Type[Type]', 'Bitte geben Sie einen Typ an'); $Error = true; } else { $Form->setSuccess('Type[Type]'); } if (!$Error) { if ((new Data($this->getBinding()))->addCompanyRelationshipToPerson($tblCompanyTo, $tblPersonFrom, $tblType, $Type['Remark']) ) { return new Success(new \SPHERE\Common\Frontend\Icon\Repository\Success() . ' Die Beziehung wurde erfolgreich hinzugefügt') . new Redirect('/People/Person', Redirect::TIMEOUT_SUCCESS, array('Id' => $tblPersonFrom->getId())); } else { return new Danger(new Ban() . ' Die Beziehung konnte nicht hinzugefügt werden') . new Redirect('/People/Person', Redirect::TIMEOUT_ERROR, array('Id' => $tblPersonFrom->getId())); } } return $Form; } /** * @param IFormInterface $Form * @param TblToPerson $tblToPerson * @param TblPerson $tblPersonFrom * @param int $tblPersonTo * @param array $Type * * @return IFormInterface|string */ public function updateRelationshipToPerson( IFormInterface $Form, TblToPerson $tblToPerson, TblPerson $tblPersonFrom, $tblPersonTo, $Type ) { /** * Skip to Frontend */ if (null === $Type) { return $Form; } $Error = false; if (empty($tblPersonTo)) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger(new Ban() . ' Bitte wählen Sie eine Person'))))); $Error = true; } else { $tblPersonTo = Person::useService()->getPersonById($tblPersonTo); if (!$tblPersonTo){ $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Person'))))); $Error = true; } elseif ($tblPersonFrom->getId() == $tblPersonTo->getId()) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger(new Ban() . ' Eine Person kann nur mit einer anderen Person verknüpft werden'))))); $Error = true; } } if (!($tblType = $this->getTypeById($Type['Type']))){ $Form->setError('Type[Type]', 'Bitte geben Sie einen Typ an'); $Error = true; } else { $Form->setSuccess('Type[Type]'); } if (!$Error) { // Remove current (new Data($this->getBinding()))->removePersonRelationshipToPerson($tblToPerson); // Add new if ((new Data($this->getBinding()))->addPersonRelationshipToPerson($tblPersonFrom, $tblPersonTo, $tblType, $Type['Remark']) ) { return new Success(new \SPHERE\Common\Frontend\Icon\Repository\Success() . ' Die Beziehung wurde erfolgreich geändert') . new Redirect('/People/Person', Redirect::TIMEOUT_SUCCESS, array('Id' => $tblToPerson->getServiceTblPersonFrom() ? $tblToPerson->getServiceTblPersonFrom()->getId() : 0)); } else { return new Danger(new Ban() . ' Die Beziehung konnte nicht geändert werden') . new Redirect('/People/Person', Redirect::TIMEOUT_ERROR, array('Id' => $tblToPerson->getServiceTblPersonFrom() ? $tblToPerson->getServiceTblPersonFrom()->getId() : 0)); } } return $Form; } /** * @param IFormInterface $Form * @param TblToCompany $tblToCompany * @param TblPerson $tblPersonFrom * @param int $tblCompanyTo * @param array $Type * * @return IFormInterface|string */ public function updateRelationshipToCompany( IFormInterface $Form, TblToCompany $tblToCompany, TblPerson $tblPersonFrom, $tblCompanyTo, $Type ) { /** * Skip to Frontend */ if (null === $Type) { return $Form; } $Error = false; if (empty($tblCompanyTo)) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Institution'))))); $Error = true; } else { $tblCompanyTo = Company::useService()->getCompanyById($tblCompanyTo); if (!$tblCompanyTo){ $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Institution'))))); $Error = true; } } if (!($tblType = $this->getTypeById($Type['Type']))){ $Form->setError('Type[Type]', 'Bitte geben Sie einen Typ an'); $Error = true; } else { $Form->setSuccess('Type[Type]'); } if (!$Error) { // Remove current (new Data($this->getBinding()))->removeCompanyRelationshipToPerson($tblToCompany); // Add new if ((new Data($this->getBinding()))->addCompanyRelationshipToPerson($tblCompanyTo, $tblPersonFrom, $tblType, $Type['Remark']) ) { return new Success(new \SPHERE\Common\Frontend\Icon\Repository\Success() . ' Die Beziehung wurde erfolgreich geändert') . new Redirect('/People/Person', Redirect::TIMEOUT_SUCCESS, array('Id' => $tblToCompany->getServiceTblPerson() ? $tblToCompany->getServiceTblPerson()->getId() : 0)); } else { return new Danger(new Ban() . ' Die Beziehung konnte nicht geändert werden') . new Redirect('/People/Person', Redirect::TIMEOUT_ERROR, array('Id' => $tblToCompany->getServiceTblPerson() ? $tblToCompany->getServiceTblPerson()->getId() : 0)); } } return $Form; } /** * @return bool|TblType[] */ public function getTypeAll() { return (new Data($this->getBinding()))->getTypeAll(); } /** * @param $Name * @return false|TblType */ public function getTypeByName($Name) { return (new Data($this->getBinding()))->getTypeByName($Name); } /** * @param TblToPerson $tblToPerson * @param bool $IsSoftRemove * * @return bool */ public function removePersonRelationshipToPerson(TblToPerson $tblToPerson, $IsSoftRemove = false) { return (new Data($this->getBinding()))->removePersonRelationshipToPerson($tblToPerson, $IsSoftRemove); } /** * @param TblToCompany $tblToCompany * @param bool $IsSoftRemove * * @return bool */ public function removeCompanyRelationshipToPerson(TblToCompany $tblToCompany, $IsSoftRemove = false) { return (new Data($this->getBinding()))->removeCompanyRelationshipToPerson($tblToCompany, $IsSoftRemove); } /** * @param integer $Id * * @return bool|TblToPerson */ public function getRelationshipToPersonById($Id) { return (new Data($this->getBinding()))->getRelationshipToPersonById($Id); } /** * @param integer $Id * * @return bool|TblToCompany */ public function getRelationshipToCompanyById($Id) { return (new Data($this->getBinding()))->getRelationshipToCompanyById($Id); } /** * @param TblCompany $tblCompany * @param TblPerson $tblPerson * @param TblType $tblType * @param string $Remark * * @return TblToCompany */ public function addCompanyRelationshipToPerson( TblCompany $tblCompany, TblPerson $tblPerson, TblType $tblType, $Remark = '' ) { return (new Data($this->getBinding()))->addCompanyRelationshipToPerson( $tblCompany, $tblPerson, $tblType, $Remark ); } /** * @param TblPerson $tblPersonFrom * @param TblPerson $tblPersonTo * @param TblType $tblType * @param string $Remark * * @return bool */ public function insertRelationshipToPerson( TblPerson $tblPersonFrom, TblPerson $tblPersonTo, TblType $tblType, $Remark ) { if ((new Data($this->getBinding()))->addPersonRelationshipToPerson($tblPersonFrom, $tblPersonTo, $tblType, $Remark) ) { return true; } else { return false; } } /** * @param integer $Id * * @return bool|TblSiblingRank */ public function getSiblingRankById($Id) { return (new Data($this->getBinding()))->getSiblingRankById($Id); } /** * @return bool|TblSiblingRank[] */ public function getSiblingRankAll() { return (new Data($this->getBinding()))->getSiblingRankAll(); } /** * @param TblPerson $tblPerson * @param bool $IsSoftRemove */ public function removeRelationshipAllByPerson(TblPerson $tblPerson, $IsSoftRemove = false) { if (($tblRelationshipToPersonList = $this->getPersonRelationshipAllByPerson($tblPerson))){ foreach($tblRelationshipToPersonList as $tblToPerson){ $this->removePersonRelationshipToPerson($tblToPerson, $IsSoftRemove); } } if (($tblRelationshipToPersonList = $this->getCompanyRelationshipAllByPerson($tblPerson))){ foreach($tblRelationshipToPersonList as $tblToPerson){ $this->removeCompanyRelationshipToPerson($tblToPerson, $IsSoftRemove); } } } }
hannesk001/SPHERE-Framework
Application/People/Relationship/Service.php
PHP
agpl-3.0
20,135
/* Copyright 2008 Clipperz Srl This file is part of Clipperz Community Edition. Clipperz Community Edition is a web-based password manager and a digital vault for confidential data. For further information about its features and functionalities please refer to http://www.clipperz.com * Clipperz Community Edition is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * Clipperz Community Edition is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Clipperz Community Edition. If not, see <http://www.gnu.org/licenses/>. */ if (typeof(Clipperz) == 'undefined') { Clipperz = {}; } if (typeof(Clipperz.PM) == 'undefined') { Clipperz.PM = {}; } if (typeof(Clipperz.PM.Components) == 'undefined') { Clipperz.PM.Components = {}; } if (typeof(Clipperz.PM.Components.Panels) == 'undefined') { Clipperz.PM.Components.Panels = {}; } //############################################################################# Clipperz.PM.Components.Panels.ContactsPanel = function(anElement, args) { args = args || {}; Clipperz.PM.Components.Panels.ContactsPanel.superclass.constructor.call(this, anElement, args); this.render(); return this; } //============================================================================= YAHOO.extendX(Clipperz.PM.Components.Panels.ContactsPanel, Clipperz.PM.Components.Panels.BasePanel, { 'toString': function() { return "Clipperz.PM.Components.ContactsPanel component"; }, //------------------------------------------------------------------------- 'render': function() { // var tabPanelControllerConfig; Clipperz.YUI.DomHelper.append(this.element().dom, {tag:'table', border:'0', cellspacing:'0', cellpadding:'0', children:[ {tag:'tbody', children:[ {tag:'tr', children:[ {tag:'td', valign:'top', width:'200', children:[ {tag:'ul', id:"dataSubMenu", cls:'subMenu', children:[ {tag:'li', id:this.getId('contacts'), htmlString:Clipperz.PM.Strings['contactsTabLabel']}, ]} ]}, {tag:'td', valign:'top', children:[ {tag:'ul', cls:'clipperzTabPanels', children:[ {tag:'li', id:this.getId('contactsPanel'), children:[ {tag:'div', cls:'clipperzSubPanel', children:[ {tag:'h5', htmlString:Clipperz.PM.Strings['contactsTabTitle']}, {tag:'div', htmlString:Clipperz.PM.Strings['comingSoon']} ]} ]} ]} ]} ]} ]} ]}); // tabPanelControllerConfig = {} // tabPanelControllerConfig[this.getId('contacts')] = this.getId('contactsPanel'); // new Clipperz.PM.Components.TabPanel.TabPanelController({ config:tabPanelControllerConfig, selectedTab:this.getId('contacts') }); this.tabPanelController().setUp(); }, //------------------------------------------------------------------------- 'tabPanelController': function() { if (this._tabPanelController == null) { var tabPanelControllerConfig; tabPanelControllerConfig = {} tabPanelControllerConfig[this.getId('contacts')] = this.getId('contactsPanel'); this._tabPanelController = new Clipperz.PM.Components.TabPanel.TabPanelController({ config:tabPanelControllerConfig, selectedTab:this.getId('contacts') }); } return this._tabPanelController; }, //------------------------------------------------------------------------- __syntaxFix__: "syntax fix" });
weisslj/clipperz-communityEdition
js/src/Clipperz/PM/Components/Panels/ContactsPanel.js
JavaScript
agpl-3.0
3,757
class ResetSearch025 < ActiveRecord::Migration[5.0] def change UserIndex.reset! end end
myplaceonline/myplaceonline_rails
db/migrate/20170205065206_reset_search025.rb
Ruby
agpl-3.0
96
/** * Copyright (C) 2013 The Language Archive, Max Planck Institute for * Psycholinguistics * * 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. */ package nl.mpi.yams.client.ui; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.text.shared.Renderer; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ValueListBox; import com.google.gwt.user.client.ui.VerticalPanel; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Logger; import nl.mpi.yams.client.DatabaseInformation; import nl.mpi.yams.client.controllers.HistoryController; import nl.mpi.yams.client.HistoryListener; import nl.mpi.yams.client.SearchOptionsServiceAsync; import nl.mpi.yams.client.controllers.SearchHandler; import nl.mpi.yams.common.data.QueryDataStructures.CriterionJoinType; import nl.mpi.yams.common.data.QueryDataStructures.SearchOption; import nl.mpi.yams.common.data.SearchParameters; /** * Created on : Jan 29, 2013, 2:50:44 PM * * @author Peter Withers <peter.withers@mpi.nl> */ public class SearchWidgetsPanel extends VerticalPanel implements HistoryListener { private static final Logger logger = Logger.getLogger(""); private static final String SEARCH_LABEL = "Search"; private static final String SEARCHING_LABEL = "<img src='./loader.gif'/>&nbsp;Searching"; private static final String ADD_SEARCH_TERM = "add search term"; private static final String sendButtonStyle = "sendButton"; private static final String NO_VALUE = "<no value>"; private static final String DEMO_LIST_BOX_STYLE = "demo-ListBox"; private final SearchOptionsServiceAsync searchOptionsService; private final HistoryController historyController; private String lastUsedDatabase = ""; private Button searchButton; private SearchHandler searchHandler; private final ResultsPanel resultsPanel; private final ValueListBox<CriterionJoinType> joinTypeListBox; private final VerticalPanel verticalPanel; private final ArrayList<SearchCriterionPanel> criterionPanelList = new ArrayList<SearchCriterionPanel>(); private final DatabaseInformation databaseInfo; public SearchWidgetsPanel(SearchOptionsServiceAsync searchOptionsService, final HistoryController historyController, DatabaseInformation databaseInfo, ResultsPanel resultsPanel, DataNodeTable dataNodeTable, final ArchiveBranchSelectionPanel archiveTreePanel) { this.searchOptionsService = searchOptionsService; this.historyController = historyController; this.databaseInfo = databaseInfo; this.resultsPanel = resultsPanel; verticalPanel = new VerticalPanel(); this.add(verticalPanel); initSearchHandler(); final SearchCriterionPanel searchCriterionPanel = new SearchCriterionPanel(SearchWidgetsPanel.this, searchOptionsService); if (archiveTreePanel != null) { verticalPanel.add(archiveTreePanel); historyController.addHistoryListener(archiveTreePanel); } verticalPanel.add(searchCriterionPanel); criterionPanelList.add(searchCriterionPanel); Button addRowButton = new Button(ADD_SEARCH_TERM, new ClickHandler() { public void onClick(ClickEvent event) { addSearchCriterionPanel(new SearchCriterionPanel(SearchWidgetsPanel.this, SearchWidgetsPanel.this.searchOptionsService)); } }); this.add(addRowButton); final HorizontalPanel buttonsPanel = new HorizontalPanel(); this.add(buttonsPanel); joinTypeListBox = getJoinTypeListBox(); buttonsPanel.add(joinTypeListBox); buttonsPanel.add(searchButton); this.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); } public void userSelectionChange() { final String databaseName = historyController.getDatabaseName(); if (databaseName != null && !databaseName.isEmpty() && !databaseName.equals(lastUsedDatabase)) { historyChange(); } } public void historyChange() { searchHandler.updateDbName(); final CriterionJoinType criterionJoinType = historyController.getCriterionJoinType(); if (criterionJoinType == null) { joinTypeListBox.setValue(CriterionJoinType.values()[0]); } else { joinTypeListBox.setValue(criterionJoinType); } final ArrayList<SearchParameters> searchParametersList = historyController.getSearchParametersList(); if (searchParametersList != null && !searchParametersList.isEmpty()) { while (searchParametersList.size() < criterionPanelList.size()) { removeSearchCriterionPanel(criterionPanelList.get(criterionPanelList.size() - 1)); } while (searchParametersList.size() > criterionPanelList.size()) { addSearchCriterionPanel(new SearchCriterionPanel(SearchWidgetsPanel.this, SearchWidgetsPanel.this.searchOptionsService)); } for (int panelIndex = 0; panelIndex < criterionPanelList.size(); panelIndex++) { final SearchParameters historyValues = searchParametersList.get(panelIndex); criterionPanelList.get(panelIndex).setDefaultValues(historyValues.getFileType(), historyValues.getFieldType(), historyValues.getSearchNegator(), historyValues.getSearchType(), historyValues.getSearchString()); } } else { while (!criterionPanelList.isEmpty()) { removeSearchCriterionPanel(criterionPanelList.get(0)); } if (historyController.getDatabaseName() != null) { final SearchCriterionPanel searchCriterionPanel = new SearchCriterionPanel(SearchWidgetsPanel.this, SearchWidgetsPanel.this.searchOptionsService); addSearchCriterionPanel(searchCriterionPanel); } } final String databaseName = historyController.getDatabaseName(); if (databaseName != null && !databaseName.isEmpty() && !databaseName.equals(lastUsedDatabase)) { lastUsedDatabase = databaseName; for (SearchCriterionPanel eventCriterionPanel : criterionPanelList) { eventCriterionPanel.setDatabase(databaseName); } } } protected void addSearchCriterionPanel(SearchCriterionPanel criterionPanel) { criterionPanelList.add(criterionPanel); verticalPanel.add(criterionPanel); if (!lastUsedDatabase.isEmpty()) { criterionPanel.setDatabase(lastUsedDatabase); } joinTypeListBox.setVisible(criterionPanelList.size() > 1); } protected void removeSearchCriterionPanel(SearchCriterionPanel criterionPanel) { criterionPanelList.remove(criterionPanel); verticalPanel.remove(criterionPanel); joinTypeListBox.setVisible(criterionPanelList.size() > 1); } private void initSearchHandler() { searchButton = new Button(SEARCH_LABEL); searchButton.addStyleName(sendButtonStyle); searchHandler = new SearchHandler(historyController, databaseInfo, searchOptionsService, resultsPanel) { @Override protected void prepareSearch() { searchButton.setEnabled(false); searchButton.setHTML(SEARCHING_LABEL); ArrayList<SearchParameters> searchParametersList = new ArrayList<SearchParameters>(); for (SearchCriterionPanel eventCriterionPanel : criterionPanelList) { //logger.info("eventCriterionPanel"); searchParametersList.add(new SearchParameters(eventCriterionPanel.getMetadataFileType(), eventCriterionPanel.getMetadataFieldType(), eventCriterionPanel.getSearchNegator(), eventCriterionPanel.getSearchType(), eventCriterionPanel.getSearchText())); } historyController.setSearchParameters(joinTypeListBox.getValue(), searchParametersList); } protected @Override void finaliseSearch() { searchButton.setEnabled(true); searchButton.setHTML(SEARCH_LABEL); } }; searchButton.addClickHandler(searchHandler); } protected ValueListBox getSearchOptionsListBox() { final ValueListBox<SearchOption> widget = new ValueListBox<SearchOption>(new Renderer<SearchOption>() { public String render(SearchOption object) { if (object == null) { return NO_VALUE; } else { return object.toString(); } } public void render(SearchOption object, Appendable appendable) throws IOException { if (object != null) { appendable.append(object.toString()); } } }); widget.addStyleName(DEMO_LIST_BOX_STYLE); widget.setValue(SearchOption.equals); widget.setAcceptableValues(Arrays.asList(SearchOption.values())); return widget; } private ValueListBox getJoinTypeListBox() { final ValueListBox<CriterionJoinType> widget = new ValueListBox<CriterionJoinType>(new Renderer<CriterionJoinType>() { public String render(CriterionJoinType object) { if (object == null) { return NO_VALUE; } else { return object.toString(); } } public void render(CriterionJoinType object, Appendable appendable) throws IOException { if (object != null) { appendable.append(object.toString()); } } }); widget.addStyleName(DEMO_LIST_BOX_STYLE); widget.setValue(CriterionJoinType.intersect); widget.setAcceptableValues(Arrays.asList(CriterionJoinType.values())); // widget.addValueChangeHandler(new ValueChangeHandler<CriterionJoinType>() { // // public void onValueChange(ValueChangeEvent<CriterionJoinType> event) { // historyController.setCriterionJoinType(event.getValue()); // } // }); return widget; } public SearchHandler getSearchHandler() { return searchHandler; } }
TheLanguageArchive/YAMS
web/src/main/java/nl/mpi/yams/client/ui/SearchWidgetsPanel.java
Java
agpl-3.0
11,217
package com.welaika.menadi.db; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import com.activeandroid.query.Select; import java.util.ArrayList; import java.util.List; @Table(name = "RelatorsEvents") public class RelatorEvent extends Model { @Column(name = "IdR") public Integer idR; @Column(name = "Relator") public Relator relator; @Column(name = "IdEInD") public Integer idEInD; @Column(name = "EventInD") public EventInDate eventInD; public RelatorEvent() { super(); } public RelatorEvent(int idR, Relator relator, int idEInD, EventInDate eventInD) { this.idR = idR; this.relator = relator; this.idEInD = idEInD; this.eventInD = eventInD; } public static List<RelatorEvent> getEvents(int idRel) { return new Select() .from(RelatorEvent.class) .where("IdR = ?", idRel) .execute(); } public static List<Relator> getRelators(int idEventInDate) { List<RelatorEvent> list_r2e = new Select() .from(RelatorEvent.class) .where("IdEInD = ?", idEventInDate) .execute(); List<Relator> relators = new ArrayList<Relator>(); for(RelatorEvent r2e : list_r2e){ relators.add(r2e.relator); } return relators; } }
welaika/menadi
Menadi/src/main/java/com/welaika/menadi/db/RelatorEvent.java
Java
agpl-3.0
1,447
#!/usr/bin/python3 ###### Памятка по статусам ##### # OK -- сервис онлайн, обрабатывает запросы, получает и отдает флаги. # MUMBLE -- сервис онлайн, но некорректно работает # CORRUPT -- сервис онлайн, но установленные флаги невозможно получить. # DOWN -- сервис оффлайн. from sys import argv from socket import socket, AF_INET, SOCK_STREAM from string import ascii_letters from random import randint, shuffle from time import sleep from tinfoilhat import Checker, \ ServiceMumbleException, \ ServiceCorruptException, \ ServiceDownException class DummyChecker(Checker): BUFSIZE = 1024 """ Сгенерировать логин @return строка логина из 10 символов английского алфавита """ def random_login(self): symbols = list(ascii_letters) shuffle(symbols) return ''.join(symbols[0:10]) """ Сгенерировать пароль @return строка пароля из 10 цифр """ def random_password(self): return str(randint(100500**2, 100500**3))[0:10] """ Отправить логин и пароль сервису. @param sock сокет @param login логин @param password пароль """ def send_cred(self, s, login, password): s.send(login.encode('utf-8')) if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() s.send(password.encode('utf-8')) if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() """ Положить флаг в сервис @param host адрес хоста @param port порт сервиса @param flag флаг @return состояние, необходимое для получения флага """ def put(self, host, port, flag): try: s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) s.send(b'REG\n') if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() login = self.random_login() password = self.random_password() self.send_cred(s, login, password) s.close() s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) s.send(b'PUT\n') if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() self.send_cred(s, login, password) s.send(flag.encode('utf-8')) if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() return login + ":" + password except (OSError, IOError) as e: if e.errno == 111: # ConnectionRefusedError raise ServiceDownException() else: raise ServiceMumbleException() """ Получить флаг из сервиса @param host адрес хоста @param port порт сервиса @param state состояние @return флаг """ def get(self, host, port, state): login, password = state.split(':') s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) s.send(b'GET\n') if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() try: self.send_cred(s, login, password) except ServiceMumbleException: raise ServiceCorruptException() try: flag, ret = s.recv(self.BUFSIZE).split() return flag.decode('utf-8') except ValueError: raise ServiceCorruptException() """ Проверить состояние сервиса @param host адрес хоста @param port порт сервиса """ def chk(self, host, port): # Так как сервис реализует только логику хранилища, # её и проверяем. # Это отличается от put и get тем, что происходит в один момент, # тем самым наличие данных по прошествии времени не проверяется. data = self.random_password() try: state = self.put(host, port, data) new_data = self.get(host, port, state) except (OSError, IOError) as e: if e.errno == 111: # ConnectionRefusedError raise ServiceDownException() else: raise ServiceMumbleException() if data != new_data: raise ServiceMumbleException() if __name__ == '__main__': DummyChecker(argv)
jollheef/tin_foil_hat
checker/python-api/dummy_checker.py
Python
agpl-3.0
4,904
<?php namespace Concerto\PanelBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table * @ORM\Entity(repositoryClass="Concerto\PanelBundle\Repository\TestSessionRepository") */ class TestSession extends AEntity { const STATUS_RUNNING = 0; const STATUS_SERIALIZED = 1; /** * @ORM\ManyToOne(targetEntity="Test", inversedBy="sessions") */ private $test; /** * * @ORM\Column(type="string") */ private $testServerNodeId; /** * * @ORM\Column(type="integer", nullable=true) */ private $testServerNodePort; /** * * @ORM\Column(type="string") */ private $rServerNodeId; /** * * @ORM\Column(type="integer", nullable=true) */ private $rServerNodePort; /** * * @ORM\Column(type="integer") */ private $status; /** * @ORM\ManyToOne(targetEntity="ViewTemplate") * @ORM\JoinColumn(nullable=true, onDelete="CASCADE") */ private $template; /** * * @ORM\Column(type="text", nullable=true) */ private $templateHtml; /** * * @ORM\Column(type="text", nullable=true) */ private $templateHead; /** * @ORM\ManyToOne(targetEntity="ViewTemplate") * @ORM\JoinColumn(name="loader_id", referencedColumnName="id", nullable=true) */ private $loader; /** * * @ORM\Column(type="text", nullable=true) */ private $loaderHtml; /** * * @ORM\Column(type="text", nullable=true) */ private $loaderHead; /** * * @ORM\Column(type="integer") */ private $timeLimit; /** * * @ORM\Column(type="text", nullable=true) */ private $params; /** * * @ORM\Column(type="text", nullable=true) */ private $returns; /** * * @ORM\Column(type="text", nullable=true) */ private $error; /** * * @ORM\Column(type="text", nullable=true) */ private $clientIp; /** * * @ORM\Column(type="text", nullable=true) */ private $clientBrowser; /** * * @ORM\Column(type="text", nullable=true, length=40) */ private $hash; /** * * @ORM\Column(type="boolean") */ private $debug; public function __construct() { parent::__construct(); $this->hash = sha1(rand(1000, 9999)); $this->status = self::STATUS_RUNNING; $this->timeLimit = 0; $this->finalize = 0; } /** * Set test server node id * * @param string $testServerNodeId * @return TestSession */ public function setTestServerNodeId($testServerNodeId) { $this->testServerNodeId = $testServerNodeId; return $this; } /** * Get test server node if * * @return string */ public function getTestServerNodeId() { return $this->testServerNodeId; } /** * Set test server node port * * @param integer $testServerNodePort * @return TestSession */ public function setTestServerNodePort($testServerNodePort) { $this->testServerNodePort = $testServerNodePort; return $this; } /** * Get test server node port * * @return integer */ public function getTestServerNodePort() { return $this->testServerNodePort; } /** * Set R server node id * * @param string $rServerNodeId * @return TestSession */ public function setRServerNodeId($rServerNodeId) { $this->rServerNodeId = $rServerNodeId; return $this; } /** * Get R server node id * * @return string */ public function getRServerNodeId() { return $this->rServerNodeId; } /** * Set R server node port * * @param integer $rServerNodePort * @return TestSession */ public function setRServerNodePort($rServerNodePort) { $this->rServerNodePort = $rServerNodePort; return $this; } /** * Get R server node port * * @return integer */ public function getRServerNodePort() { return $this->rServerNodePort; } /** * Set status * * @param integer $status * @return TestSession */ public function setStatus($status) { $this->status = $status; return $this; } /** * Get status * * @return integer */ public function getStatus() { return $this->status; } /** * Set templateHtml * * @param string $templateHtml * @return TestSession */ public function setTemplateHtml($templateHtml) { $this->templateHtml = $templateHtml; return $this; } /** * Get templateHtml * * @return string */ public function getTemplateHtml() { return $this->templateHtml; } /** * Set templateHead * * @param string $templateHead * @return TestSession */ public function setTemplateHead($templateHead) { $this->templateHead = $templateHead; return $this; } /** * Get templateHead * * @return string */ public function getTemplateHead() { return $this->templateHead; } /** * Set loaderHtml * * @param string $loaderHtml * @return TestSession */ public function setLoaderHtml($loaderHtml) { $this->loaderHtml = $loaderHtml; return $this; } /** * Get loaderHtml * * @return string */ public function getLoaderHtml() { return $this->loaderHtml; } /** * Set loaderHead * * @param string $loaderHead * @return TestSession */ public function setLoaderHead($loaderHead) { $this->loaderHead = $loaderHead; return $this; } /** * Get loaderHead * * @return string */ public function getLoaderHead() { return $this->loaderHead; } /** * Set test * * @param Test $test * @return TestSession */ public function setTest(Test $test = null) { $this->test = $test; return $this; } /** * Get test * * @return Test */ public function getTest() { return $this->test; } /** * Set template * * @param ViewTemplate $template * @return TestSession */ public function setTemplate(ViewTemplate $template = null) { $this->template = $template; return $this; } /** * Get template * * @return ViewTemplate */ public function getTemplate() { return $this->template; } /** * Set loader * * @param ViewTemplate $loader * @return TestSession */ public function setLoader(ViewTemplate $loader = null) { $this->loader = $loader; return $this; } /** * Get loader * * @return ViewTemplate */ public function getLoader() { return $this->loader; } /** * Set time limit * * @param integer $timeLimit * @return TestSession */ public function setTimeLimit($timeLimit) { $this->timeLimit = $timeLimit; return $this; } /** * Get time limit (in seconds) * * @return integer */ public function getTimeLimit() { return $this->timeLimit; } /** * Set params * * @param string $params * @return TestSession */ public function setParams($params) { $this->params = $params; return $this; } /** * Get params * * @return string */ public function getParams() { return $this->params; } /** * Set returns * * @param string $returns * @return TestSession */ public function setReturns($returns) { $this->returns = $returns; return $this; } /** * Get returns * * @return string */ public function getReturns() { return $this->returns; } /** * Set error * * @param string $error * @return TestSession */ public function setError($error) { $this->error = $error; return $this; } /** * Get error * * @return string */ public function getError() { return $this->error; } /** * Set client ip * * @param string $clientIp * @return TestSession */ public function setClientIp($clientIp) { $this->clientIp = $clientIp; return $this; } /** * Get client ip * * @return string */ public function getClientIp() { return $this->clientIp; } /** * Set client browser * * @param string $clientBrowser * @return TestSession */ public function setClientBrowser($clientBrowser) { $this->clientBrowser = $clientBrowser; return $this; } /** * Get client browser * * @return string */ public function getClientBrowser() { return $this->clientBrowser; } /** * Set hash * * @param string $hash * @return TestSession */ public function setHash($hash) { $this->hash = $hash; return $this; } /** * Get hash * * @return string */ public function getHash() { return $this->hash; } /** * Set debug * * @param boolean $debug * @return TestSession */ public function setDebug($debug) { $this->debug = $debug; return $this; } /** * Get debug * * @return boolean */ public function isDebug() { return $this->debug; } }
davidstillwell/concerto-platform
src/Concerto/PanelBundle/Entity/TestSession.php
PHP
agpl-3.0
9,985
/* * StuReSy - Student Response System * Copyright (C) 2012-2014 StuReSy-Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package sturesy.util; /** * Contains the current program version * * @author w.posdorfer * */ public class Version { public static final String CURRENTVERSION = "0.6.2"; /** * Checks if provided version is higher than currentversion * * @param version * version to be compared to current version * @return <code>true</code> if version is higher than current version */ public static boolean isHigherVersion(String version) { if (!version.matches("[0-9]*\\.[0-9]*\\.[0-9]*")) { return false; } String[] split = version.split("\\."); String[] current = CURRENTVERSION.split("\\."); for (int i = 0; i < current.length; i++) { int s = Integer.parseInt(split[i]); int c = Integer.parseInt(current[i]); if (s > c) { return true; } else if (s < c) { return false; } // else continue; } return false; } }
sturesy/client
src/src-main/sturesy/util/Version.java
Java
agpl-3.0
1,852
<? /** * Nooku Framework - http://www.nooku.org * * @copyright Copyright (C) 2011 - 2017 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU AGPLv3 <https://www.gnu.org/licenses/agpl.html> * @link https://github.com/timble/openpolice-platform */ ?> <div class="scopebar"> <div class="scopebar__group"> <a class="<?= is_null($state->published) ? 'active' : ''; ?>" href="<?= route('published=' ) ?>"> <?= translate('All') ?> </a> </div> <div class="scopebar__group"> <a class="<?= $state->published === true ? 'active' : ''; ?>" href="<?= route($state->published === true ? 'published=' : 'published=1') ?>"> <?= translate('Published') ?> </a> <a class="<?= $state->published === false ? 'active' : ''; ?>" href="<?= route($state->published === false ? 'published=' : 'published=0' ) ?>"> <?= translate('Unpublished') ?> </a> </div> <div class="scopebar__group"> <a class="<?= $state->access === true ? 'active' : ''; ?>" href="<?= route($state->access === true ? 'access=' : 'access=1' ) ?>"> <?= 'Registered' ?> </a> </div> <div class="scopebar__search"> <?= helper('grid.search') ?> </div> </div>
timble/openpolice-platform
application/admin/component/categories/view/categories/templates/default_scopebar.html.php
PHP
agpl-3.0
1,269
# Fat Free CRM # Copyright (C) 2008-2011 by Michael Dvorkin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #------------------------------------------------------------------------------ class DatePairInput < SimpleForm::Inputs::Base # Output two date fields: start and end #------------------------------------------------------------------------------ def input add_autocomplete! out = "<br />".html_safe field1, field2 = get_fields [field1, field2].compact.each do |field| out << '<div>'.html_safe label = field==field1 ? I18n.t('pair.start') : I18n.t('pair.end') [:required, :disabled].each {|k| input_html_options.delete(k)} # ensure these come from field not default options input_html_options.merge!(field.input_options) input_html_options.merge!(:value => value(field)) out << "<label#{' class="req"' if input_html_options[:required]}>#{label}</label>".html_safe text = @builder.text_field(field.name, input_html_options) out << text << '</div>'.html_safe end out end private # Returns true if either field is required? #------------------------------------------------------------------------------ def required_field? get_fields.map(&:required).any? end # Turns autocomplete off unless told otherwise. #------------------------------------------------------------------------------ def add_autocomplete! input_html_options[:autocomplete] ||= 'off' end # Datepicker latches onto the 'date' class. #------------------------------------------------------------------------------ def input_html_classes super.push('date') end # Returns the pair as [field1, field2] #------------------------------------------------------------------------------ def get_fields @field1 ||= Field.where(:name => attribute_name).first @field2 ||= @field1.try(:paired_with) [@field1, @field2] end # Serialize into a value recognised by datepicker #------------------------------------------------------------------------------ def value(field) val = object.send(field.name) val.present? ? val.strftime('%Y-%m-%d') : nil end end
nazeels/fat_free
app/inputs/date_pair_input.rb
Ruby
agpl-3.0
2,789
package edu.arizona.kfs.sys.dataaccess.impl; import java.util.HashMap; import java.util.Map; import org.kuali.kfs.coreservice.framework.parameter.ParameterService; import edu.arizona.kfs.sys.batch.BuildingImportStep; import edu.arizona.kfs.sys.dataaccess.BuildingAndRoomImportsDao; public class BuildingAndRoomImportsDaoOjb implements BuildingAndRoomImportsDao { private ParameterService parameterService; public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } // Returns a list of routeCodes with their respective campusCode public Map<String, String> PopulateRoutecodeToCampusCodeMap() { Map<String, String> routecodeToCampuscodeMap = new HashMap<String, String>(); String[] keyPairs = parameterService.getParameterValueAsString(BuildingImportStep.class, "ROUTE_CODE_BY_CAMPUS_CODE").split(";"); for (String keyValues : keyPairs) { String[] tokens = keyValues.split("="); String campusCode = tokens[0]; String values = tokens[1]; String[] valueTokens = values.split(","); for (String routeCode : valueTokens) { routecodeToCampuscodeMap.put(routeCode, campusCode); } } return routecodeToCampuscodeMap; } }
quikkian-ua-devops/will-financials
kfs-core/src/main/java/edu/arizona/kfs/sys/dataaccess/impl/BuildingAndRoomImportsDaoOjb.java
Java
agpl-3.0
1,215
from django.db import models from submissions.models.utils import strip_punc from django.contrib.auth.models import User from submissions.models.album import Album from django.contrib.contenttypes.models import ContentType class Track(models.Model): """ A single track(song) for an album. """ URL_CHOICES = ( ('download', 'download'), ('stream','stream'), ('buy','buy'), ) title = models.CharField(max_length=255) cleaned_name = models.CharField(max_length=255, blank=True, null=True, editable=False, help_text="A cleaned name without punctuation or weird stuff.") track_number = models.IntegerField(blank=True, null=True) #Replace by regexfield r'[0-9:]+' in forms duration = models.CharField(max_length=255, blank=True, null=True) url = models.URLField('URL', blank=True, null=True) url_type = models.CharField('Type', max_length=255, choices=URL_CHOICES, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) uploader = models.ForeignKey(User, blank=True, null=True, help_text="The uploader of this track.") album = models.ForeignKey(Album, related_name="tracks", help_text="The album to which this track belongs.") mbid = models.CharField(max_length=255, blank=True, null=True) class Meta: app_label = "submissions" ordering = ('track_number', 'title') def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('album-detail', (), {'artist': self.album.artist.slug, 'album': self.album.slug }) def save(self, *args, **kwargs): if not self.cleaned_name: self.cleaned_name = strip_punc(self.title) super(Track, self).save(*args, **kwargs)
tsoporan/tehorng
submissions/models/track.py
Python
agpl-3.0
1,835
import { Pipe, PipeTransform } from '@angular/core'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { KalturaMediaType } from 'kaltura-ngx-client'; import { KalturaMediaEntry } from 'kaltura-ngx-client'; import { KalturaExternalMediaEntry } from 'kaltura-ngx-client'; @Pipe({ name: 'entryDuration' }) export class EntryDurationPipe implements PipeTransform { constructor(private appLocalization: AppLocalization) { } transform(value: string, entry: KalturaMediaEntry = null): string { let duration = value; if (entry && entry instanceof KalturaExternalMediaEntry && !entry.duration) { duration = this.appLocalization.get('app.common.n_a'); } else if (entry && entry instanceof KalturaMediaEntry && entry.mediaType) { const type = entry.mediaType.toString(); if (type === KalturaMediaType.liveStreamFlash.toString() || type === KalturaMediaType.liveStreamQuicktime.toString() || type === KalturaMediaType.liveStreamRealMedia.toString() || type === KalturaMediaType.liveStreamWindowsMedia.toString() ) { duration = this.appLocalization.get('app.common.n_a'); } } return duration; } }
kaltura/kmc-ng
src/shared/content-shared/entries/pipes/entry-duration.pipe.ts
TypeScript
agpl-3.0
1,191
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Deck' db.create_table(u'djecks_anki_deck', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), ('description', self.gf('django.db.models.fields.TextField')(blank=True)), ('apkg', self.gf('django.db.models.fields.files.FileField')(max_length=100, blank=True)), )) db.send_create_signal(u'djecks_anki', ['Deck']) def backwards(self, orm): # Deleting model 'Deck' db.delete_table(u'djecks_anki_deck') models = { u'djecks_anki.deck': { 'Meta': {'object_name': 'Deck'}, 'apkg': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['djecks_anki']
bdunnette/djecks_anki
migrations/0002_auto__add_deck.py
Python
agpl-3.0
1,388
<?php # FFMPEG SETTING 404_pal $vb = '960k'; # video rate kbs $s = '540x404'; # scale $g = 75; # keyframes interval (gob) $vcodec = 'libx264'; # default libx264 $progresivo = "-vf yadif"; # desentrelazar $gamma_y = "0.97"; # correccion de luminancia $gamma_u = "1.01"; # correccion de B-y $gamma_v = "0.98"; # correccion de R-y $gammma = "-vf lutyuv=\"u=gammaval($gamma_u):v=gammaval($gamma_v):y=gammaval($gamma_y)\""; # corrección de gamma $force = 'mp4'; # default mp4 $ar = 44100; # audio sample rate (22050) $ab = '64k'; # adio rate kbs $ac = "1"; # numero de canales de audio 2 = stereo, 1 = nomo $acodec = 'libvo_aacenc'; # default libvo_aacenc $target_path = "404"; # like '404' ?>
renderpci/dedalo-4
lib/dedalo/media_engine/lib/ffmpeg_settings/404_pal_4x3.php
PHP
agpl-3.0
752
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.extensions.calcium.system; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import org.apache.log4j.Logger; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.extensions.calcium.environment.FileServerClient; import org.objectweb.proactive.extensions.calcium.environment.StoredFile; import org.objectweb.proactive.extensions.calcium.statistics.Timer; /** * This class is a Proxy for the real File class. * * @author The ProActive Team */ public class ProxyFile extends File { private static final long serialVersionUID = 54L; static Logger logger = ProActiveLogger.getLogger(Loggers.SKELETONS_SYSTEM); File wspace; public File relative; File current; //current = wspace+"/"+relative StoredFile remote; FileServerClient fserver; long lastmodified; long cachedSize; public long blockedFetchingTime; public long downloadedBytes; public long uploadedBytes; public int refCBefore; public int refCAfter; public ProxyFile(File wspace, File relative) { super(relative.getName()); this.current = new File(wspace, relative.getPath()); this.relative = relative; this.remote = null; setWSpace(null, wspace); this.lastmodified = this.cachedSize = 0; this.blockedFetchingTime = this.uploadedBytes = this.downloadedBytes = 0; this.refCBefore = this.refCAfter = 0; } public ProxyFile(File wspace, String name) { this(wspace, new File(name)); } public void setWSpace(FileServerClient fserver, File wspace) { this.fserver = fserver; this.wspace = wspace; } public void store(FileServerClient fserver, int refCount) throws IOException { this.cachedSize = current.length(); this.uploadedBytes += current.length(); this.remote = fserver.store(current, refCount); this.lastmodified = current.lastModified(); } public void saveRemoteDataInWSpace() throws IOException { int i = 1; if (isLocallyStored()) { return; //Nothing to do, data already donwloaded } current = new File(wspace, relative.getPath()); while (current.exists()) { current = new File(wspace, relative.getPath() + "-" + i++); } if (logger.isDebugEnabled()) { logger.debug("Fetching data into:" + this.current); } fserver.fetch(remote, this.current); this.lastmodified = this.current.lastModified(); this.downloadedBytes += current.length(); } public boolean isRemotelyStored() { return remote != null; } public boolean isLocallyStored() { return current != null; } public boolean hasBeenModified() { /* TODO improve by: * * 1. Also considering the hashcode. * 2. Keeping track of lastModified access. */ if (current == null) { return false; } return lastmodified != current.lastModified(); } public void handleStageOut(FileServerClient fserver) throws IOException { if (isNew()) { if (logger.isDebugEnabled()) { logger.debug("Storing new file: [" + refCBefore + "," + refCAfter + "] " + relative + " (" + current + ")"); } store(fserver, refCAfter); return; } if (isModified()) { if (logger.isDebugEnabled()) { logger.debug("Storing modified file: [" + refCBefore + "," + refCAfter + "] " + relative + " (" + current + ")"); } fserver.commit(remote.fileId, -refCBefore); store(fserver, refCAfter); return; } if (isNormal()) { //&& (refCAfter - refCBefore !=0)){ if (logger.isDebugEnabled()) { logger.debug("Updating normal file: [" + refCBefore + "," + refCAfter + "] " + "name=" + relative + " id=" + remote.fileId + " (" + current + ")"); } fserver.commit(remote.fileId, refCAfter - refCBefore); return; } logger.error("Illegal ProxyFile state: " + refCAfter + "a " + refCBefore + "b" + " data modified=" + hasBeenModified()); //Reached here, not good! throw new IOException("ProxyFile reached illegal state:" + this); } public void setStageOutState() { this.current = null; this.wspace = null; this.fserver = null; this.blockedFetchingTime = this.uploadedBytes = this.downloadedBytes = 0; this.refCBefore = this.refCAfter = 0; } private boolean isNew() { return (this.refCBefore == 0) && (this.refCAfter != 0); } private boolean isNormal() { return (this.refCBefore != 0) && !hasBeenModified(); } private boolean isModified() { return (this.refCBefore != 0) && (this.refCAfter != 0) && hasBeenModified(); } public File getWSpaceFile() { return wspace; } public File getCurrent() { if (current == null) { Timer t = new Timer(); t.start(); logger.debug("Blocking waiting for file's data:" + wspace + "/" + relative); /* try{ throw new Exception(); }catch(Exception e){ e.printStackTrace(); } */ try { saveRemoteDataInWSpace(); } catch (IOException e) { throw new IllegalArgumentException(e); //TODO change this exception type } t.stop(); this.blockedFetchingTime = 1 + t.getTime(); } return current; } /* *********************************************************** * * BEGIN EXTENDED FILE METHODS * * ***********************************************************/ @Override public String getName() { return relative.getName(); } @Override public String getParent() { return getCurrent().getParent(); } @Override public File getParentFile() { return getCurrent().getParentFile(); } @Override public String getPath() { return getCurrent().getPath(); } @Override public boolean isAbsolute() { return getCurrent().isAbsolute(); } @Override public String getAbsolutePath() { return getCurrent().getAbsolutePath(); } @Override public File getAbsoluteFile() { return getCurrent().getAbsoluteFile(); } @Override public String getCanonicalPath() throws IOException { return getCurrent().getCanonicalPath(); } @Override public File getCanonicalFile() throws IOException { return getCurrent().getCanonicalFile(); } @Deprecated @Override public URL toURL() throws MalformedURLException { return getCurrent().toURL(); } @Override public URI toURI() { return getCurrent().toURI(); } @Override public boolean canRead() { return getCurrent().canRead(); } @Override public boolean canWrite() { return getCurrent().canWrite(); } @Override public boolean exists() { return getCurrent().exists(); } @Override public boolean isDirectory() { return getCurrent().isDirectory(); } @Override public boolean isFile() { return getCurrent().isFile(); } @Override public boolean isHidden() { return getCurrent().isHidden(); } @Override public long lastModified() { return getCurrent().lastModified(); } @Override public long length() { if (!isLocallyStored()) { return cachedSize; } return getCurrent().length(); } @Override public boolean createNewFile() throws IOException { return getCurrent().createNewFile(); } @Override public boolean delete() { return getCurrent().delete(); } @Override public void deleteOnExit() { getCurrent().deleteOnExit(); } @Override public String[] list() { return getCurrent().list(); } @Override public String[] list(FilenameFilter filter) { return getCurrent().list(); } @Override public File[] listFiles() { return getCurrent().listFiles(); } @Override public File[] listFiles(FilenameFilter filter) { return getCurrent().listFiles(filter); } @Override public File[] listFiles(FileFilter filter) { return getCurrent().listFiles(filter); } @Override public boolean mkdir() { return getCurrent().mkdir(); } @Override public boolean mkdirs() { return getCurrent().mkdirs(); } @Override public boolean renameTo(File dest) { //TODO check this method boolean res = getCurrent().renameTo(new File(wspace, dest.getPath())); if (res) { relative = dest; } return res; } @Override public boolean setLastModified(long time) { return getCurrent().setLastModified(time); } @Override public boolean setReadOnly() { return getCurrent().setReadOnly(); } @Override public int compareTo(File pathname) { return getCurrent().compareTo(pathname); } @Override public boolean equals(Object obj) { return getCurrent().equals(obj); } @Override public int hashCode() { return getCurrent().hashCode(); } @Override public String toString() { return getCurrent().toString(); } public static void main(String[] args) throws Exception { WSpaceImpl wspace = new WSpaceImpl(new File("/tmp/calcium")); File f = wspace.copyInto(new File("/home/mleyton/IMG00070.jpg")); } }
nmpgaspar/PainlessProActive
src/Extensions/org/objectweb/proactive/extensions/calcium/system/ProxyFile.java
Java
agpl-3.0
11,732
from bottle import request class BottleHelper: """map Apify methods to Bottle magic and other helpers""" def __init__(self, app): self.app = app def route(self, path, function, methods=['GET']): self.app.route(path, method=methods, callback=function) def request(self, items=None): if request.json is not None: datas = request.json else: if hasattr(request, 'params'): datas = request.params.dict else: return None if items is None: return datas elif isinstance(items, list): ret = {} for i in items: data = datas.get(i) ret[i] = data return ret else: return datas.get(items)
abondis/api-hi
api_hi/helpers/bottle.py
Python
agpl-3.0
816
<?php namespace Minds\Core\Payments\Stripe\Customers; use Minds\Core\Di\Di; use Minds\Core\Payments\Stripe\Instances\CustomerInstance; use Minds\Core\Payments\Stripe\Instances\PaymentMethodInstance; class Manager { /** @var Lookup $lookup */ private $lookup; private $customerInstance; private $paymentMethodInstance; public function __construct($lookup = null, $customerInstance = null, $paymentMethodInstance = null) { $this->lookup = $lookup ?: Di::_()->get('Database\Cassandra\Lookup'); $this->customerInstance = $customerInstance ?? new CustomerInstance(); $this->paymentMethodInstance = $paymentMethodInstance ?? new PaymentMethodInstance(); } /** * Return a Customer from user guid * @param string $userGuid * @return Customer */ public function getFromUserGuid($userGuid): ?Customer { $customerId = $this->lookup->get("{$userGuid}:payments")['customer_id']; if (!$customerId) { return null; } $stripeCustomer = \Stripe\Customer::retrieve($customerId); if (!$stripeCustomer) { return null; } $customer = new Customer(); $customer->setPaymentSource($stripeCustomer->default_source) ->setUserGuid($userGuid) ->setId($customerId); return $customer; } /** * Add a customer to stripe * @param Customer $customer * @return boolean */ public function add(Customer $customer) : Customer { $stripeCustomer = $this->customerInstance->create([ 'payment_method' => $customer->getPaymentMethod(), ]); $this->lookup->set("{$customer->getUserGuid()}:payments", [ 'customer_id' => (string) $stripeCustomer->id ]); $customer->setId($stripeCustomer->id); return $customer; } }
Minds/engine
Core/Payments/Stripe/Customers/Manager.php
PHP
agpl-3.0
1,899
import mongoose from 'mongoose'; import Boom from 'boom'; import Bounce from 'bounce'; import { log, logErr } from '../../shared/utils'; import eventStore from '../stores/eventStore'; import alertStore from '../stores/alertStore'; import userStore from '../stores/userStore'; const ObjectId = mongoose.Types.ObjectId; const alertController = { async createAlert(req, h) { let alert = null; let user; let payloadEvent; try { if (!ObjectId.isValid(req.payload.event)) throw new Error("Event ID is not valid."); payloadEvent = await eventStore.getEvent(req.payload.event); if (!payloadEvent) throw new Error("Event not found."); if (req.payload && req.payload["sent.by"]) { if (!ObjectId.isValid(req.payload["sent.by"])) throw new Error("Sent by user ID is not valid."); user = await userStore.getUser(ObjectId(req.payload["sent.by"])); if (!user) throw new Error("Sent by user not found."); } const newLoad = { ...payloadEvent.toObject(), // TO-DO: add parser with string formatting type: payloadEvent.type.toString(), event: ObjectId(req.payload.event), sent: { by: (req.payload["sent.by"]) ? req.payload["sent.by"] : null, at: Date.now() } }; delete newLoad["id"]; alert = await alertStore.createAlert(newLoad); if (!alert) throw new Error("Alert returned empty."); const response = h.response(alert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController createAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error creating alert."); } }, async updateAlert(req, h) { // updateAlert just sets expireNow to true let alert; let updatedAlert; try { alert = await alertStore.updateAlert(req.params.alertID); if (!alert) throw new Error("Alert not found."); updatedAlert = await alertStore.getAlert(alert.id); const response = h.response(updatedAlert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController updateAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error updating alert."); } }, async getAlerts(req, h) { // only fetches unexpired alerts let alerts; try { alerts = await alertStore.getAlerts(); if (!alerts) throw new Error("No alerts found."); const response = h.response(alerts); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAlerts error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alerts."); } }, async getAlert(req, h) { let alert; try { alert = await alertStore.getAlert(ObjectId(req.params.alertID)); if (!alert) throw new Error("Alert not found."); const response = h.response(alert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alert."); } }, async getAllAlerts(req, h) { let alerts; try { alerts = await alertStore.getAllAlerts(); if (!alerts) throw new Error("No alerts found."); const response = h.response(alerts); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAllAlerts error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alerts."); } }, }; export default alertController;
Cosecha/redadalertas-api
src/server/app/api/controllers/alertController.js
JavaScript
agpl-3.0
3,644
namespace IntranetGJAK.Models { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using IntranetGJAK.Models.JSON.Blueimp_FileUpload; using IntranetGJAK; public class File { [Key] [Required] public string Id { get; set; } [Required] [Display(Name = "Název souboru")] public string Name { get; set; } [Required] public string Path { get; set; } [Required] [Display(Name = "Velikost")] public long Size { get; set; } [Required] [Display(Name = "Odesílatel")] public string Uploader { get; set; } [Required] [Display(Name = "Datum")] public DateTime DateUploaded { get; set; } public UploadSucceeded ToSerializeable() { return new UploadSucceeded { name = this.Name, size = this.Size, url = "/api/files/" + this.Id, thumbnailUrl = Thumbnails.GetThumbnail(this.Name), deleteUrl = "/api/files/" + this.Id, deleteType = "DELETE" }; } } public interface IFileRepository { void Add(File item); IEnumerable<File> GetAll(); File Find(string key); File Remove(string key); void Update(File item); } public class FileRepository : IFileRepository { private static ConcurrentDictionary<string, File> _Files = new ConcurrentDictionary<string, File>(); public FileRepository() { } public IEnumerable<File> GetAll() { return _Files.Values; } public void Add(File item) { item.Id = Guid.NewGuid().ToString(); _Files[item.Id] = item; } public File Find(string key) { File item; _Files.TryGetValue(key, out item); return item; } public File Remove(string key) { File item; _Files.TryGetValue(key, out item); _Files.TryRemove(key, out item); return item; } public void Update(File item) { _Files[item.Id] = item; } } }
j2ghz/IntranetGJAK
IntranetGJAK/Models/File.cs
C#
agpl-3.0
2,432
from django.core.management.base import BaseCommand, CommandError from voty.initproc.models import Quorum, IssueSupportersQuorum, IssueVotersQuorum from django.contrib.auth import get_user_model from django.utils import timezone from datetime import date from math import ceil """ - Bis 99 Abstimmungsberechtigten 10 Personen - ab 100 bis 299 Abstimmungsberechtigten 15 Personen - ab 300 bis 599 Abstimmungsberechtigten 20 Personen - ab 600 bis 999 Abstimmungsberechtigten 30 Personen - ab 1000 bis 1999 Abstimmungsberechtigten 35 Personen - ab 2000 bis 4999 Abstimmungsberechtigten 50 Personen - ab 5000 Abstimmungsberechtigten 1% der Abstimmungsberechtigten """ class Command(BaseCommand): help = "Calculate the next quorum and set it" def handle(self, *args, **options): now = timezone.now() year = now.year month = now.month # round to turn of month if now.day > 15: month += 1 month -= 6 if month < 1: year -= 1 month += 12 threshold = timezone.datetime(year=year, month=month, day=1, tzinfo=now.tzinfo) total = get_user_model().objects.filter(is_active=True, config__last_activity__gt=threshold).count() totalpartymembers = get_user_model().objects.filter(is_active=True, config__is_party_member=True, config__last_activity__gt=threshold).count() print("Total active users: {}".format(total)) print("Total active party members: {}".format(totalpartymembers)) #Quorum for Issue Support quorum = ceil(total / 20.0) if quorum < 5: quorum = 5 IssueSupportersQuorum(value=quorum).save() print("Issue Support Quorum set to {}".format(quorum)) #Quorum for Issue Voting quorum = ceil(totalpartymembers / 10.0) if quorum < 5: quorum = 5 #commented out because it is now set manually, 10% of all party members, not only of those who have a login or are active in Plenum #IssueVotersQuorum(value=quorum).save() #print("Issue Voting Quorum set to {}".format(quorum)) quorum = ceil(total / 100.0) if total < 100: quorum = 10 elif total < 300: quorum = 15 elif total < 600: quorum = 20 elif total < 1000: quorum = 30 elif total < 2000: quorum = 35 elif total < 5000: quorum = 50 Quorum(quorum=quorum).save() print("Initiatives Quorum set to {}".format(quorum))
DemokratieInBewegung/abstimmungstool
voty/initproc/management/commands/set_quorum.py
Python
agpl-3.0
2,590
/* * Axelor Business Solutions * * Copyright (C) 2019 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.axelor.apps.bankpayment.db.repo; import com.axelor.apps.account.db.Move; import com.axelor.apps.account.db.MoveLine; import com.axelor.apps.account.db.repo.MoveManagementRepository; import java.math.BigDecimal; import java.util.List; public class MoveBankPaymentRepository extends MoveManagementRepository { @Override public Move copy(Move entity, boolean deep) { Move copy = super.copy(entity, deep); List<MoveLine> moveLineList = copy.getMoveLineList(); if (moveLineList != null) { moveLineList.forEach(moveLine -> moveLine.setBankReconciledAmount(BigDecimal.ZERO)); } return copy; } }
ama-axelor/axelor-business-suite
axelor-bank-payment/src/main/java/com/axelor/apps/bankpayment/db/repo/MoveBankPaymentRepository.java
Java
agpl-3.0
1,337
<?php declare(strict_types=1); /** * @author Nicolas CARPi <nico-git@deltablot.email> * @copyright 2012 Nicolas CARPi * @see https://www.elabftw.net Official website * @license AGPL-3.0 * @package elabftw */ namespace Elabftw\Services; use function dirname; use Elabftw\Exceptions\DatabaseErrorException; use Elabftw\Exceptions\FilesystemErrorException; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; /** * This is used to find out if there are untracked files that should have been deleted * but were not deleted because of a bug fixed in 2.0.7 */ require_once dirname(__DIR__, 2) . '/vendor/autoload.php'; require_once dirname(__DIR__, 2) . '/config.php'; try { $uploadsDir = dirname(__DIR__, 2) . '/uploads'; $UploadsCleaner = new UploadsCleaner(new Filesystem(new Local($uploadsDir))); $deleted = $UploadsCleaner->cleanup(); printf("Deleted %d files\n", $deleted); } catch (FilesystemErrorException | DatabaseErrorException $e) { echo $e->getMessage(); }
elabftw/elabftw
src/tools/cleanup.php
PHP
agpl-3.0
1,014
package mkl.testarea.itext5.content; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.junit.BeforeClass; import org.junit.Test; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; /** * @author mkl */ public class CellsWithPercentileBackground { final static File RESULT_FOLDER = new File("target/test-outputs", "content"); @BeforeClass public static void setUpBeforeClass() throws Exception { RESULT_FOLDER.mkdirs(); } /** * <a href="https://stackoverflow.com/questions/46869670/itext-5-create-pdfpcell-containing-2-background-colors-with-text-overlap"> * iText 5: create PdfPcell containing 2 background colors with text overlap * </a> * <p> * This test creates a table with cells that have backgrounds * which represent percentile values. To do so it makes use of the * {@link PercentileCellBackground} cell event listener. * </p> * * @author mkl */ @Test public void testCreateTableWithCellsWithPercentileBackground() throws DocumentException, IOException { Document document = new Document(); try (OutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "TableWithCellsWithPercentileBackground.pdf"))) { PdfWriter.getInstance(document, os); document.open(); Font font = new Font(FontFamily.UNDEFINED, Font.UNDEFINED, Font.UNDEFINED, BaseColor.WHITE); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(40); PdfPCell cell = new PdfPCell(new Phrase("Group A")); table.addCell(cell); cell = new PdfPCell(new Phrase(new Chunk("60 Pass, 40 Fail", font))); cell.setCellEvent(new PercentileCellBackground(60, BaseColor.GREEN, BaseColor.RED)); table.addCell(cell); cell = new PdfPCell(new Phrase("Group B")); table.addCell(cell); cell = new PdfPCell(new Phrase(new Chunk("70 Pass, 30 Fail", font))); cell.setCellEvent(new PercentileCellBackground(70, BaseColor.GREEN, BaseColor.RED)); table.addCell(cell); cell = new PdfPCell(new Phrase("Group C")); table.addCell(cell); cell = new PdfPCell(new Phrase(new Chunk("50 Pass, 50 Fail", font))); cell.setCellEvent(new PercentileCellBackground(50, BaseColor.GREEN, BaseColor.RED)); table.addCell(cell); document.add(table); document.close(); } } }
mkl-public/testarea-itext5
src/test/java/mkl/testarea/itext5/content/CellsWithPercentileBackground.java
Java
agpl-3.0
2,894
using Pathfindax.Nodes; namespace Pathfindax.Factories { public class NodeGridCollisionMask { public int Width { get; private set; } public int Height { get; private set; } public NodeGridCollisionLayer[] Layers { get; private set; } public NodeGridCollisionMask(PathfindaxCollisionCategory collisionCategory, int width, int height) { Initialize(new []{collisionCategory}, width, height); } public NodeGridCollisionMask(PathfindaxCollisionCategory[] collisionCategories, int width, int height) { Initialize(collisionCategories, width, height); } private void Initialize(PathfindaxCollisionCategory[] collisionCategories, int width, int height) { Width = width; Height = height; Layers = new NodeGridCollisionLayer[collisionCategories.Length]; for (int i = 0; i < Layers.Length; i++) { Layers[i] = new NodeGridCollisionLayer(collisionCategories[i], width, height); } } } }
Barsonax/Pathfindax
src/Pathfindax/Factories/NodeGridCollisionMask.cs
C#
agpl-3.0
933
package main import ( "github.com/datatogether/api/apiutil" "github.com/datatogether/core" "net/http" ) func CollectionHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "OPTIONS": EmptyOkHandler(w, r) case "GET": GetCollectionHandler(w, r) default: NotFoundHandler(w, r) } } func CollectionsHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": ListCollectionsHandler(w, r) default: NotFoundHandler(w, r) } } func GetCollectionHandler(w http.ResponseWriter, r *http.Request) { res := &core.Collection{} args := &CollectionsGetParams{ Id: r.URL.Path[len("/collections/"):], // Collection: r.FormValue("collection"), // Hash: r.FormValue("hash"), } err := new(Collections).Get(args, res) if err != nil { apiutil.WriteErrResponse(w, http.StatusInternalServerError, err) return } apiutil.WriteResponse(w, res) } func ListCollectionsHandler(w http.ResponseWriter, r *http.Request) { p := apiutil.PageFromRequest(r) res := make([]*core.Collection, p.Size) args := &CollectionsListParams{ Limit: p.Limit(), Offset: p.Offset(), OrderBy: "created", } err := new(Collections).List(args, &res) if err != nil { apiutil.WriteErrResponse(w, http.StatusInternalServerError, err) return } apiutil.WritePageResponse(w, res, r, p) }
archivers-space/archivers-api
collection_handlers.go
GO
agpl-3.0
1,335
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.viewer; import com.rapidminer.operator.visualization.dependencies.ANOVAMatrix; import com.rapidminer.tools.Tools; import javax.swing.table.AbstractTableModel; /** * The model for the {@link com.rapidminer.gui.viewer.ANOVAMatrixViewerTable}. * * @author Ingo Mierswa */ public class ANOVAMatrixViewerTableModel extends AbstractTableModel { private static final long serialVersionUID = -5732155307505605893L; private ANOVAMatrix matrix; /** * Instantiates a new Anova matrix viewer table model. * * @param matrix the matrix */ public ANOVAMatrixViewerTableModel(ANOVAMatrix matrix) { this.matrix = matrix; } @Override public int getRowCount() { return matrix.getAnovaAttributeNames().size(); } @Override public int getColumnCount() { return matrix.getGroupingAttributeNames().size() + 1; } @Override public String getColumnName(int col) { if (col == 0) { return "ANOVA Attribute"; } else { return "group " + matrix.getGroupingAttributeNames().get(col - 1); } } @Override public Object getValueAt(int row, int col) { if (col == 0) { return matrix.getAnovaAttributeNames().get(row); } else { return Tools.formatNumber(matrix.getProbabilities()[row][col - 1]); } } }
cm-is-dog/rapidminer-studio-core
src/main/java/com/rapidminer/gui/viewer/ANOVAMatrixViewerTableModel.java
Java
agpl-3.0
2,174
import ENV from 'irene/config/environment'; class ENVHandler { constructor(envHandlerConst) { this.envHandlerConst = envHandlerConst; } isRuntimeAvailable() { return !(typeof runtimeGlobalConfig == 'undefined'); } getEnv(env_key) { const host_key = 'IRENE_API_HOST'; this.assertEnvKey(env_key); if (this.isAvailableInRuntimeENV(env_key)) { const runtimeValue = this.getRuntimeObject()[env_key]; if (env_key === host_key) { if (runtimeValue === '/') { return ''; } } return runtimeValue; } if (this.isAvailableInProcessENV(env_key)) { const processValue = this.envHandlerConst.processENV[env_key]; if (env_key === host_key) { if (processValue === '/') { return ''; } } return processValue; } return this.getDefault(env_key); } isRegisteredEnv(env_key) { return this.envHandlerConst.possibleENVS.indexOf(env_key) > -1; } isAvailableInENV(env_key) { return ( this.isAvailableInRuntimeENV(env_key) || this.isAvailableInProcessENV(env_key) ); } getRuntimeObject() { if (this.isRuntimeAvailable()) { return runtimeGlobalConfig; // eslint-disable-line } return {}; } isAvailableInRuntimeENV(env_key) { const runtimeObj = this.getRuntimeObject(); return env_key in runtimeObj; } isAvailableInProcessENV(env_key) { return env_key in this.envHandlerConst.processENV; } assertEnvKey(env_key) { if (!this.isRegisteredEnv(env_key)) { throw new Error(`ENV: ${env_key} not registered`); } } isTrue(value) { value = String(value).toLowerCase(); return value === 'true'; } getBoolean(env_key) { return this.isTrue(this.getEnv(env_key)); } getDefault(env_key) { this.assertEnvKey(env_key); return this.envHandlerConst.defaults[env_key]; } getValueForPlugin(env_key) { const enterpriseKey = 'ENTERPRISE'; this.assertEnvKey(enterpriseKey); this.assertEnvKey(env_key); if (this.isAvailableInENV(env_key)) { return this.getBoolean(env_key); } if (this.isAvailableInENV(enterpriseKey)) { return !this.getBoolean(enterpriseKey); } return this.getDefault(env_key); } } const handler = new ENVHandler(ENV.ENVHandlerCONST); const initialize = function (application) { // inject Ajax application.inject('route', 'ajax', 'service:ajax'); application.inject('component', 'ajax', 'service:ajax'); // Inject notify application.inject('route', 'notify', 'service:notifications'); application.inject('component', 'notify', 'service:notifications'); application.inject('authenticator', 'notify', 'service:notifications'); // Inject realtime application.inject('component', 'realtime', 'service:realtime'); // Inject Store application.inject('component', 'store', 'service:store'); ENV.host = handler.getEnv('IRENE_API_HOST'); ENV.devicefarmHost = handler.getEnv('IRENE_DEVICEFARM_HOST'); ENV.isEnterprise = handler.getBoolean('ENTERPRISE'); ENV.showLicense = handler.getBoolean('IRENE_SHOW_LICENSE'); ENV.whitelabel = Object.assign({}, ENV.whitelabel, { enabled: handler.getBoolean('WHITELABEL_ENABLED'), }); if (ENV.whitelabel.enabled) { ENV.whitelabel = Object.assign({}, ENV.whitelabel, { enabled: handler.getBoolean('WHITELABEL_ENABLED'), // adding for consistency name: handler.getEnv('WHITELABEL_NAME'), logo: handler.getEnv('WHITELABEL_LOGO'), theme: handler.getEnv('WHITELABEL_THEME'), favicon: handler.getEnv('WHITELABEL_FAVICON'), }); } ENV.enableHotjar = handler.getValueForPlugin('IRENE_ENABLE_HOTJAR'); ENV.enablePendo = handler.getValueForPlugin('IRENE_ENABLE_PENDO'); ENV.enableCSB = handler.getValueForPlugin('IRENE_ENABLE_CSB'); ENV.enableMarketplace = handler.getValueForPlugin('IRENE_ENABLE_MARKETPLACE'); ENV.emberRollbarClient = { enabled: handler.getValueForPlugin('IRENE_ENABLE_ROLLBAR'), }; // Inject ENV if (ENV.environment !== 'test') { // FIXME: Fix this test properly application.register('env:main', ENV, { singleton: true, instantiate: false, }); return application.inject('component', 'env', 'env:main'); } }; const IreneInitializer = { name: 'irene', initialize, }; export { initialize }; export default IreneInitializer;
appknox/irene
app/initializers/irene.js
JavaScript
agpl-3.0
4,399
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.12.12 at 03:51:35 PM CET // package org.dmtf.schemas.wbem.wscim._1.cim_schema._2.cim_softwarefeature; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.dmtf.schemas.wbem.wscim._1.common.CimString; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;simpleContent> * &lt;restriction base="&lt;http://schemas.dmtf.org/wbem/wscim/1/common>cimString"> * &lt;anyAttribute processContents='lax'/> * &lt;/restriction> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "ProductName") public class ProductName extends CimString { }
StratusLab/claudia
clotho/src/main/java/org/dmtf/schemas/wbem/wscim/_1/cim_schema/_2/cim_softwarefeature/ProductName.java
Java
agpl-3.0
1,261
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Scene.SceneNode import SceneNode from UM.Resources import Resources from UM.Math.Color import Color from UM.Math.Vector import Vector from UM.Mesh.MeshData import MeshData import numpy class ConvexHullNode(SceneNode): def __init__(self, node, hull, parent = None): super().__init__(parent) self.setCalculateBoundingBox(False) self._material = None self._original_parent = parent self._inherit_orientation = False self._inherit_scale = False self._node = node self._node.transformationChanged.connect(self._onNodePositionChanged) self._node.parentChanged.connect(self._onNodeParentChanged) #self._onNodePositionChanged(self._node) self._hull = hull hull_points = self._hull.getPoints() center = (hull_points.min(0) + hull_points.max(0)) / 2.0 mesh = MeshData() mesh.addVertex(center[0], 0.1, center[1]) for point in hull_points: mesh.addVertex(point[0], 0.1, point[1]) indices = [] for i in range(len(hull_points) - 1): indices.append([0, i + 1, i + 2]) indices.append([0, mesh.getVertexCount() - 1, 1]) mesh.addIndices(numpy.array(indices, numpy.int32)) self.setMeshData(mesh) def getWatchedNode(self): return self._node def render(self, renderer): if not self._material: self._material = renderer.createMaterial(Resources.getPath(Resources.ShadersLocation, "basic.vert"), Resources.getPath(Resources.ShadersLocation, "color.frag")) self._material.setUniformValue("u_color", Color(35, 35, 35, 128)) renderer.queueNode(self, material = self._material, transparent = True) return True def _onNodePositionChanged(self, node): #self.setPosition(node.getWorldPosition()) if hasattr(node, "_convex_hull"): delattr(node, "_convex_hull") self.setParent(None) #self._node.transformationChanged.disconnect(self._onNodePositionChanged) #self._node.parentChanged.disconnect(self._onNodeParentChanged) def _onNodeParentChanged(self, node): if node.getParent(): self.setParent(self._original_parent) else: self.setParent(None)
quillford/Cura
cura/ConvexHullNode.py
Python
agpl-3.0
2,406
<?php use IFW\App; /** * Global IFW class with static functions to access the application instance. * * eg. IFW::app()->config() access the application configuration */ class IFW { private static $app; /** * Register the application instance * * @param App $app * @throws Exception */ public static function setApp(App $app) { if(isset(self::$app)){ throw new Exception("You can only register one application"); } self::$app = $app; } /** * Get the application instance * * @return \IFW\Web\App|IFW\Cli\App */ public static function app() { return self::$app; } }
Intermesh/groupoffice-server
lib/IFW.php
PHP
agpl-3.0
613
# Copyright (C) 2015 Linaro Limited # # Author: Stevan Radakovic <stevan.radakovic@linaro.org> # # This file is part of Lava Server. # # Lava Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License version 3 # as published by the Free Software Foundation # # Lava Server 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 Affero General Public License # along with Lava Server. If not, see <http://www.gnu.org/licenses/>. from django import forms from lava_results_app.models import ( Chart, ChartQuery, ChartQueryUser, TestCase, ) class ChartForm(forms.ModelForm): class Meta: model = Chart exclude = ('is_published', 'chart_group', 'group', 'queries') widgets = {'owner': forms.HiddenInput} def __init__(self, owner, *args, **kwargs): super(ChartForm, self).__init__(*args, **kwargs) def save(self, commit=True, **kwargs): instance = super(ChartForm, self).save(commit=commit, **kwargs) return instance class ChartQueryForm(forms.ModelForm): class Meta: model = ChartQuery exclude = () widgets = {'chart': forms.HiddenInput, 'query': forms.HiddenInput, 'relative_index': forms.HiddenInput} def __init__(self, user, *args, **kwargs): super(ChartQueryForm, self).__init__(*args, **kwargs) def save(self, commit=True, **kwargs): instance = super(ChartQueryForm, self).save(commit=commit, **kwargs) return instance def clean(self): form_data = self.cleaned_data try: # Chart type validation. if form_data["query"].content_type.model_class() == TestCase and \ form_data["chart_type"] == "pass/fail": self.add_error( "chart_type", "Pass/fail is incorrect value for 'chart_type' with TestCase based queries.") except KeyError: # form_data will pick up the rest of validation errors. pass return form_data class ChartQueryUserForm(forms.ModelForm): class Meta: model = ChartQueryUser exclude = ['user', 'chart_query'] def __init__(self, user, *args, **kwargs): super(ChartQueryUserForm, self).__init__(*args, **kwargs)
Linaro/lava-server
lava_results_app/views/chart/forms.py
Python
agpl-3.0
2,583
<?php /* Smarty version Smarty-3.1.12, created on 2015-11-09 19:00:26 compiled from "/home/gam/themes/Frontend/Bare/frontend/listing/filter/facet-value-list.tpl" */ ?> <?php /*%%SmartyHeaderCode:11956854235640df3a270b21-87257079%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( '977cfeb9bb070320a1c6f58c27362cf6c3284590' => array ( 0 => '/home/gam/themes/Frontend/Bare/frontend/listing/filter/facet-value-list.tpl', 1 => 1445520152, 2 => 'file', ), ), 'nocache_hash' => '11956854235640df3a270b21-87257079', 'function' => array ( ), 'variables' => array ( 'facet' => 0, 'option' => 0, ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.12', 'unifunc' => 'content_5640df3a37bfc8_73766854', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_5640df3a37bfc8_73766854')) {function content_5640df3a37bfc8_73766854($_smarty_tpl) {?> <div class="filter-panel filter--property facet--<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFacetName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> " data-filter-type="value-list" data-field-name="<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> "> <div class="filter-panel--flyout"> <label class="filter-panel--title"> <?php echo htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getLabel(), ENT_QUOTES, 'utf-8', true);?> </label> <span class="filter-panel--icon"></span> <div class="filter-panel--content"> <ul class="filter-panel--option-list"> <?php $_smarty_tpl->tpl_vars['option'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['option']->_loop = false; $_from = $_smarty_tpl->tpl_vars['facet']->value->getValues(); if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['option']->key => $_smarty_tpl->tpl_vars['option']->value){ $_smarty_tpl->tpl_vars['option']->_loop = true; ?> <li class="filter-panel--option"> <div class="option--container"> <span class="filter-panel--checkbox"> <input type="checkbox" id="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> __<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> " name="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> __<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> " value="<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> " <?php if ($_smarty_tpl->tpl_vars['option']->value->isActive()){?>checked="checked" <?php }?>/> <span class="checkbox--state">&nbsp;</span> </span> <label class="filter-panel--label" for="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> __<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> "> <?php echo htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getLabel(), ENT_QUOTES, 'utf-8', true);?> </label> </div> </li> <?php } ?> </ul> </div> </div> </div> <?php }} ?>
gamchantoi/AgroSHop-UTUAWARDS
var/cache/production_201510221322/templates/frontend_Responsive_id_ID_1/97/7c/fe/977cfeb9bb070320a1c6f58c27362cf6c3284590.snippet.facet-value-list.tpl.php
PHP
agpl-3.0
5,114
# # Copyright (C) 2011 - 2015 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # # @API Moderated Grading # @subtopic Provisional Grades # @beta # # API for manipulating provisional grades # # Provisional grades are created by using the Submissions API endpoint "Grade or comment on a submission" with `provisional=true`. # They can be viewed by using "List assignment submissions", "Get a single submission", or "List gradeable students" with `include[]=provisional_grades`. # This API performs other operations on provisional grades for use with the Moderated Grading feature. # # @model ProvisionalGrade # { # "id": "ProvisionalGrade", # "description": "", # "properties": { # "provisional_grade_id": { # "description": "The identifier for the provisional grade", # "example": 23, # "type": "integer" # }, # "score": { # "description": "The numeric score", # "example": 90, # "type": "integer" # }, # "grade": { # "description": "The grade", # "example": "A-", # "type": "string" # }, # "grade_matches_current_submission": { # "description": "Whether the grade was applied to the most current submission (false if the student resubmitted after grading)", # "example": true, # "type": "boolean" # }, # "graded_at": { # "description": "When the grade was given", # "example": "2015-11-01T00:03:21-06:00", # "type": "datetime" # }, # "final": { # "description": "Whether this is the 'final' provisional grade created by the moderator", # "example": false, # "type": "boolean" # }, # "speedgrader_url": { # "description": "A link to view this provisional grade in SpeedGrader™", # "example": "http://www.example.com/courses/123/gradebook/speed_grader?...", # "type": "string" # } # } # } class ProvisionalGradesController < ApplicationController before_filter :require_user before_filter :load_assignment include Api::V1::Submission # @API Show provisional grade status for a student # # @argument student_id [Integer] # The id of the student to show the status for # # @example_request # # curl 'https://<canvas>/api/v1/courses/1/assignments/2/provisional_status?student_id=1' \ # -X POST # # @example_response # # { "needs_provisional_grade": false } # def status if authorized_action(@context, @current_user, [:manage_grades, :view_all_grades]) unless @context.feature_enabled?(:moderated_grading) && @assignment.moderated_grading? return render :json => { :message => "Assignment does not use moderated grading" }, :status => :bad_request end if @assignment.grades_published? return render :json => { :message => "Assignment grades have already been published" }, :status => :bad_request end # in theory we could apply visibility here, but for now we would rather be performant # e.g. @assignment.students_with_visibility(@context.students_visible_to(@current_user)).find(params[:student_id]) student = @context.students.find(params[:student_id]) render :json => { :needs_provisional_grade => @assignment.student_needs_provisional_grade?(student) } end end # @API Select provisional grade # # Choose which provisional grade the student should receive for a submission. # The caller must have :moderate_grades rights. # # @example_response # { # "assignment_id": 867, # "student_id": 5309, # "selected_provisional_grade_id": 53669 # } # def select if authorized_action(@context, @current_user, :moderate_grades) pg = @assignment.provisional_grades.find(params[:provisional_grade_id]) selection = @assignment.moderated_grading_selections.where(student_id: pg.submission.user_id).first return render :json => { :message => 'student not in moderation set' }, :status => :bad_request unless selection selection.provisional_grade = pg selection.save! render :json => selection.as_json(:include_root => false, :only => %w(assignment_id student_id selected_provisional_grade_id)) end end # @API Copy provisional grade # # Given a provisional grade, copy the grade (and associated submission comments and rubric assessments) # to a "final" mark which can be edited or commented upon by a moderator prior to publication of grades. # # Notes: # * The student must be in the moderation set for the assignment. # * The newly created grade will be selected. # * The caller must have "Moderate Grades" rights in the course. # # @returns ProvisionalGrade def copy_to_final_mark if authorized_action @context, @current_user, :moderate_grades pg = @assignment.provisional_grades.find(params[:provisional_grade_id]) return render :json => { :message => 'provisional grade is already final' }, :status => :bad_request if pg.final selection = @assignment.moderated_grading_selections.where(student_id: pg.submission.user_id).first return render :json => { :message => 'student not in moderation set' }, :status => :bad_request unless selection final_mark = pg.copy_to_final_mark!(@current_user) selection.provisional_grade = final_mark selection.save! render :json => provisional_grade_json(final_mark, pg.submission, @assignment, @current_user, %w(submission_comments rubric_assessment)) end end # @API Publish provisional grades for an assignment # # Publish the selected provisional grade for all submissions to an assignment. # Use the "Select provisional grade" endpoint to choose which provisional grade to publish # for a particular submission. # # Students not in the moderation set will have their one and only provisional grade published. # # WARNING: This is irreversible. This will overwrite existing grades in the gradebook. # # @example_request # # curl 'https://<canvas>/api/v1/courses/1/assignments/2/provisional_grades/publish' \ # -X POST # def publish if authorized_action(@context, @current_user, :moderate_grades) unless @context.feature_enabled?(:moderated_grading) && @assignment.moderated_grading? return render :json => { :message => "Assignment does not use moderated grading" }, :status => :bad_request end if @assignment.grades_published? return render :json => { :message => "Assignment grades have already been published" }, :status => :bad_request end submissions = @assignment.submissions.preload(:all_submission_comments, { :provisional_grades => :rubric_assessments }) selections = @assignment.moderated_grading_selections.index_by(&:student_id) submissions.each do |submission| if (selection = selections[submission.user_id]) # student in moderation: choose the selected provisional grade selected_provisional_grade = submission.provisional_grades .detect { |pg| pg.id == selection.selected_provisional_grade_id } else # student not in moderation: choose the first one with a grade (there should only be one) selected_provisional_grade = submission.provisional_grades .select { |pg| pg.graded_at.present? } .sort_by { |pg| pg.created_at } .first end if selected_provisional_grade selected_provisional_grade.publish! end end @assignment.update_attribute(:grades_published_at, Time.now.utc) render :json => { :message => "OK" } end end private def load_assignment @context = api_find(Course, params[:course_id]) @assignment = @context.assignments.active.find(params[:assignment_id]) end end
AndranikMarkosyan/lms
app/controllers/provisional_grades_controller.rb
Ruby
agpl-3.0
8,598
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/> // Copyright (C) 2010 Winch Gate Property Limited // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "stdpch.h" #include "reflect.h" // Yoyo: Act like a singleton, else registerClass may crash. CReflectSystem::TClassMap *CReflectSystem::_ClassMap= NULL; // hack to register the root class at startup static const struct CRootReflectableClassRegister { CRootReflectableClassRegister() { TReflectedProperties props; CReflectSystem::registerClass("CReflectable", "", props); } } _RootReflectableClassRegisterInstance; //=================================================================================== // release memory void CReflectSystem::release() { delete _ClassMap; _ClassMap = NULL; } //=================================================================================== void CReflectSystem::registerClass(const std::string &className, const std::string &parentName, const TReflectedProperties properties) { if(!_ClassMap) _ClassMap= new TClassMap; TClassMap::const_iterator it = _ClassMap->find(className); if (it != _ClassMap->end()) { nlerror("CReflectSystem::registerClass : Class registered twice : %s!", className.c_str()); } CClassInfo &ci = (*_ClassMap)[className]; ci.Properties = properties; ci.ClassName = className; for(uint k = 0; k < ci.Properties.size(); ++k) { ci.Properties[k].ParentClass = &ci; } if (parentName.empty()) { ci.ParentClass = NULL; } else { it = _ClassMap->find(parentName); if (it == _ClassMap->end()) { nlerror("CReflectSystem::registerClass : Parent class %s not found", parentName.c_str()); } ci.ParentClass = &(it->second); } } //=================================================================================== const CReflectedProperty *CReflectSystem::getProperty(const std::string &className, const std::string &propertyName, bool dspWarning) { if(!_ClassMap) _ClassMap= new TClassMap; TClassMap::const_iterator it = _ClassMap->find(className); if (it == _ClassMap->end()) { nlwarning("CReflectSystem::getProperty : Unkwown class : %s", className.c_str()); return NULL; } const CClassInfo *ci = &it->second; while (ci) { // Linear search should suffice for now for(uint k = 0; k < ci->Properties.size(); ++k) { if (ci->Properties[k].Name == propertyName) { return &(ci->Properties[k]); } } // search in parent ci = ci->ParentClass; } //\ TODO nico : possible optimization : instead of going up in the parents when // searching for a property, it would be simpler to concatenate properties // from parent class at registration. // All that would be left at the end would be a hash_map of properties ... if(dspWarning) nlwarning("CReflectSystem::getProperty : %s is not a property of class : %s", propertyName.c_str(), className.c_str()); return NULL; } //=================================================================================== const CClassInfo *CReflectable::getClassInfo() { if (!CReflectSystem::getClassMap()) return NULL; // TODO nico : a possible optimization would be to use the address of the static function // 'getReflectedProperties' as a key into the CClassInfo map. This pointer uniquely identify // classes that export properties CReflectSystem::TClassMap::const_iterator it = CReflectSystem::getClassMap()->find(this->getReflectedClassName()); if (it == CReflectSystem::getClassMap()->end()) { return NULL; } return &(it->second); } //=================================================================================== const CReflectedProperty *CReflectable::getReflectedProperty(const std::string &propertyName, bool dspWarning) const { return CReflectSystem::getProperty(this->getReflectedClassName(), propertyName, dspWarning); }
osgcc/ryzom
ryzom/client/src/interface_v3/reflect.cpp
C++
agpl-3.0
4,462
OC.L10N.register( "deck", { "Deck" : "Deck", "Personal" : "Personal", "Finished" : "Terminado", "To review" : "Para revisar", "Action needed" : "Acción requerida", "Later" : "Después", "copy" : "copiar", "Done" : "Hecho", "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" : "El archivo subido sobrepasa el valor MAX_FILE_SIZE especificada en el formulario HTML", "No file was uploaded" : "No se subió ningún archivo ", "Missing a temporary folder" : "Falta un directorio temporal", "Add board" : "Nuevo Tablero", "Cancel" : "Cancelar", "Hide archived cards" : "Ocultar tarjetas archivadas", "Show archived cards" : "Mostrar tarjetas archivadas", "Details" : "Detalles", "Sharing" : "Compartiendo", "Tags" : "Etiquetas", "Undo" : "Deshacer", "Can edit" : "Puede editar", "Can share" : "Puede compartir", "Delete" : "Eliminar", "Edit" : "Editar", "Members" : "Miembros", "Attachments" : "Adjuntos", "Comments" : "Comentarios", "Modified" : "Modificado", "Created" : "Creado", "Due date" : "Fecha de vencimiento", "Select Date" : "Seleccionar fecha", "Today" : "Hoy", "Tomorrow" : "Mañana", "Save" : "Guardar", "Reply" : "Responder", "Update" : "Actualizar", "Description" : "Descripción", "Formatting help" : "Ayuda de formato", "(group)" : "(grupo)", "seconds ago" : "segundos", "All boards" : "Todos los Tableros", "Shared with you" : "Compartido con usted", "Board details" : "Detalles del tablero", "Edit board" : "Editar Tablero", "Clone board" : "Clonar Tablero", "Delete board" : "Eliminar Tablero", "An error occurred" : "Ocurrió un error", "This week" : "Esta semana" }, "nplurals=2; plural=(n != 1);");
nextcloud/deck
l10n/es_AR.js
JavaScript
agpl-3.0
1,856
/* * Copyright 2015 - 2017 AZYVA INC. INC. * * This file is part of Dragom. * * Dragom is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dragom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Dragom. If not, see <http://www.gnu.org/licenses/>. */ package org.azyva.dragom.model.config; import java.util.List; import org.azyva.dragom.model.plugin.NodePlugin; /** * Transfer object for a {@link MutableNodeConfig} basic configuration data. * <p> * MutableNodeConfig and its sub-interfaces return and take as argument this * interface to allow getting and setting atomically data. See * {@link MutableConfig}. * <p> * It so happens that the only configuration data that can be transfered from and * to MutableNodeConfig's (and its sub-interfaces) are the same and are * represented by this interface. If MutableNodeConfig and its sub-interfaces * eventually contain other configuration data that are not common, the * orientation will probably be to introduce new transfer objects instead * implementing an interface hierarchy to factor out commonality. * <p> * Since this interface represents a transfer object, implementations are * generally straightforward, and in most cases, * SimpleNodeConfigTransferObject will be adequate. Specifically if an * implementation of MutableNodeConfig needs to manage concurrency with optimistic * locking, {@link OptimisticLockHandle} should be used instead of including some * hidden field within the NodeConfigTransferObject implementation. * * @author David Raymond */ public interface NodeConfigTransferObject { /** * @return Name. */ String getName(); /** * Sets the name. * * @param name See description. */ void setName(String name); /** * Returns a {@link PropertyDefConfig}. * <p> * If the PropertyDefConfig exists but is defined with the value field set to * null, a PropertyDefConfig is returned (instead of returning null). * * @param name Name of the PropertyDefConfig. * @return PropertyDefConfig. null if the PropertyDefConfig does not exist. */ PropertyDefConfig getPropertyDefConfig(String name); /** * Verifies if a {@link PropertyDefConfig} exists. * <p> * If the PropertyDefConfig exists but is defined with the value field set to * null, true is returned. * <p> * Returns true if an only if {@link #getPropertyDefConfig} does not return null. * * @param name Name of the PropertyDefConfig. * @return Indicates if the PropertyDefConfig exists. */ boolean isPropertyExists(String name); /** * Returns a List of all the {@link PropertyDefConfig}'s. * <p> * If no PropertyDefConfig is defined for the NodeConfig, an empty List is * returned (as opposed to null). * <p> * The order of the PropertyDefConfig is generally expected to be as defined * in the underlying storage for the configuration, hence the List return type. * But no particular order is actually guaranteed. * * @return See description. */ public List<PropertyDefConfig> getListPropertyDefConfig(); /** * Removes a {@link PropertyDefConfig}. * * @param name Name of the PropertyDefConfig. */ public void removePropertyDefConfig(String name); /** * Sets a {@link PropertyDefConfig}. * <p> * If one already exists with the same name, it is overwritten. Otherwise it is * added. * <p> * Mostly any implementation of PropertyDefConfig can be used, although * SimplePropertyDefConfig is generally the better choice. * * @param propertyDefConfig PropertyDefConfig. * @return Indicates if a new PropertyDefConfig was added (as opposed to an * existing one having been overwritten. */ public boolean setPropertyDefConfig(PropertyDefConfig propertyDefConfig); /** * Returns a {@link PluginDefConfig}. * <p> * If the PluginDefConfig exists but is defined with the pluginClass field set to * null, a PluginDefConfig is returned (instead of returning null). * * @param classNodePlugin Class of the {@link NodePlugin} interface. * @param pluginId Plugin ID to distinguish between multiple instances of the same * plugin. Can be null to get a PluginDefConfig whose field pluginId is null. * @return PluginDefConfig. null if the PluginDefConfig does not exist. */ public PluginDefConfig getPluginDefConfig(Class<? extends NodePlugin> classNodePlugin, String pluginId); /** * Verifies if a {@link PluginDefConfig} exists. * <p> * If the PluginDefConfig exists but is defined with the pluginClass field set to * null, true is returned. * <p> * Returns true if an only if {@link #getPluginDefConfig} does not return null. * * @param classNodePlugin Class of the {@link NodePlugin} interface. * @param pluginId Plugin ID to distinguish between multiple instances of the same * plugin. Can be null to get a PluginDefConfig whose field pluginId is null. * @return Indicates if the PluginDefConfig exists. */ public boolean isPluginDefConfigExists(Class<? extends NodePlugin> classNodePlugin, String pluginId); /** * Returns a List of all the {@link PluginDefConfig}'s. * <p> * If no PluginDefConfig is defined for the NodeConfig, an empty Set is returned * (as opposed to null). * <p> * The order of the PluginDefConfig is generally expected to be as defined * in the underlying storage for the configuration, hence the List return type. * But no particular order is actually guaranteed. * * @return See description. */ public List<PluginDefConfig> getListPluginDefConfig(); /** * Removes a {@link PropertyDefConfig}. * * @param classNodePlugin Class of the {@link NodePlugin} interface. * @param pluginId Plugin ID to distinguish between multiple instances of the same * plugin. Can be null to get a PluginDefConfig whose field pluginId is null. */ public void removePlugingDefConfig(Class<? extends NodePlugin> classNodePlugin, String pluginId); /** * Sets a {@link PluginDefConfig}. * <p> * If one already exists with the same {@link PluginKey}, it is overwritten. * Otherwise it is added. * <p> * Mostly any implementation of PluginDefConfig can be used, although * SimplePluginDefConfig is generally the better choice. * * @param pluginDefConfig PluginDefConfig. * @return Indicates if a new PluginDefConfig was added (as opposed to an existing * one having been overwritten. */ public boolean setPluginDefConfig(PluginDefConfig pluginDefConfig); }
azyva/dragom-api
src/main/java/org/azyva/dragom/model/config/NodeConfigTransferObject.java
Java
agpl-3.0
7,040
<?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Joas Schilling <coding@schilljs.com> * @author Morris Jobke <hey@morrisjobke.de> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCA\UpdateNotification\Notification; use OCP\IConfig; use OCP\IGroupManager; use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Notification\IManager; use OCP\Notification\INotification; use OCP\Notification\INotifier; class Notifier implements INotifier { /** @var IURLGenerator */ protected $url; /** @var IConfig */ protected $config; /** @var IManager */ protected $notificationManager; /** @var IFactory */ protected $l10NFactory; /** @var IUserSession */ protected $userSession; /** @var IGroupManager */ protected $groupManager; /** @var string[] */ protected $appVersions; /** * Notifier constructor. * * @param IURLGenerator $url * @param IConfig $config * @param IManager $notificationManager * @param IFactory $l10NFactory * @param IUserSession $userSession * @param IGroupManager $groupManager */ public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) { $this->url = $url; $this->notificationManager = $notificationManager; $this->config = $config; $this->l10NFactory = $l10NFactory; $this->userSession = $userSession; $this->groupManager = $groupManager; $this->appVersions = $this->getAppVersions(); } /** * @param INotification $notification * @param string $languageCode The code of the language that should be used to prepare the notification * @return INotification * @throws \InvalidArgumentException When the notification was not prepared by a notifier * @since 9.0.0 */ public function prepare(INotification $notification, $languageCode) { if ($notification->getApp() !== 'updatenotification') { throw new \InvalidArgumentException(); } $l = $this->l10NFactory->get('updatenotification', $languageCode); if ($notification->getSubject() === 'connection_error') { $errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0); if ($errors === 0) { $this->notificationManager->markProcessed($notification); throw new \InvalidArgumentException(); } $notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors])) ->setParsedMessage($l->t('Please check the nextcloud and server log files for errors.')); } elseif ($notification->getObjectType() === 'core') { $this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions()); $parameters = $notification->getSubjectParameters(); $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']])); if ($this->isAdmin()) { $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater'); } } else { $appInfo = $this->getAppInfo($notification->getObjectType()); $appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name']; if (isset($this->appVersions[$notification->getObjectType()])) { $this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]); } $notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()])) ->setRichSubject($l->t('Update for {app} to version %s is available.', $notification->getObjectId()), [ 'app' => [ 'type' => 'app', 'id' => $notification->getObjectType(), 'name' => $appName, ] ]); if ($this->isAdmin()) { $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType()); } } $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg'))); return $notification; } /** * Remove the notification and prevent rendering, when the update is installed * * @param INotification $notification * @param string $installedVersion * @throws \InvalidArgumentException When the update is already installed */ protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) { if (version_compare($notification->getObjectId(), $installedVersion, '<=')) { $this->notificationManager->markProcessed($notification); throw new \InvalidArgumentException(); } } /** * @return bool */ protected function isAdmin() { $user = $this->userSession->getUser(); if ($user instanceof IUser) { return $this->groupManager->isAdmin($user->getUID()); } return false; } protected function getCoreVersions() { return implode('.', \OCP\Util::getVersion()); } protected function getAppVersions() { return \OC_App::getAppVersions(); } protected function getAppInfo($appId) { return \OC_App::getAppInfo($appId); } }
Ardinis/server
apps/updatenotification/lib/Notification/Notifier.php
PHP
agpl-3.0
5,672
var error = require('parts/error'); exports.create = function(callback, millisec, cyclic){ if(typeof(setInterval) == 'undefined' &&typeof(setTimeout) == 'undefined') return new error('not supported', 'this platform is not supported timer functionality'); var id = cyclic ? setInterval(callback, millisec) : setTimeout(callback, millisec); return { destroy : function(){ cyclic ? clearInterval(id) : clearTimeout(id); } }; }
ixdu/capsule
modules/timer.js
JavaScript
agpl-3.0
457
# coding: utf-8 from django.contrib.auth.models import User, Permission from django.urls import reverse from django.utils import timezone from rest_framework import status from kpi.constants import ( ASSET_TYPE_COLLECTION, PERM_CHANGE_ASSET, PERM_MANAGE_ASSET, PERM_VIEW_ASSET, ) from kpi.models import Asset, ObjectPermission from kpi.tests.kpi_test_case import KpiTestCase from kpi.urls.router_api_v2 import URL_NAMESPACE as ROUTER_URL_NAMESPACE from kpi.utils.object_permission import get_anonymous_user class ApiAnonymousPermissionsTestCase(KpiTestCase): URL_NAMESPACE = ROUTER_URL_NAMESPACE def setUp(self): self.anon = get_anonymous_user() self.someuser = User.objects.get(username='someuser') self.someuser_password = 'someuser' # This was written when we allowed anons to create assets, but I'll # leave it here just to make sure it has no effect permission = Permission.objects.get(codename='add_asset') self.anon.user_permissions.add(permission) # Log in and create an asset that anon can access self.client.login(username=self.someuser.username, password=self.someuser_password) self.anon_accessible = self.create_asset('Anonymous can access this!') self.add_perm(self.anon_accessible, self.anon, 'view_') # Log out and become anonymous again self.client.logout() response = self.client.get(reverse('currentuser-detail')) self.assertFalse('username' in response.data) def test_anon_list_assets(self): # `view_` granted to anon means detail access, NOT list access self.assert_object_in_object_list(self.anon_accessible, in_list=False) def test_anon_asset_detail(self): self.assert_detail_viewable(self.anon_accessible) def test_cannot_create_asset(self): url = reverse(self._get_endpoint('asset-list')) data = {'name': 'my asset', 'content': ''} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, msg="anonymous user cannot create a asset") class ApiPermissionsPublicAssetTestCase(KpiTestCase): URL_NAMESPACE = ROUTER_URL_NAMESPACE def setUp(self): KpiTestCase.setUp(self) self.anon = get_anonymous_user() self.admin = User.objects.get(username='admin') self.admin_password = 'pass' self.someuser = User.objects.get(username='someuser') self.someuser_password = 'someuser' self.login(self.admin.username, self.admin_password) self.admins_public_asset = self.create_asset('admins_public_asset') self.add_perm(self.admins_public_asset, self.anon, 'view') self.login(self.someuser.username, self.someuser_password) self.someusers_public_asset = self.create_asset('someusers_public_asset') self.add_perm(self.someusers_public_asset, self.anon, 'view') def test_user_can_view_public_asset(self): self.assert_detail_viewable(self.admins_public_asset, self.someuser, self.someuser_password) def test_public_asset_not_in_list_user(self): self.assert_object_in_object_list(self.admins_public_asset, self.someuser, self.someuser_password, in_list=False) def test_public_asset_not_in_list_admin(self): self.assert_object_in_object_list(self.someusers_public_asset, self.admin, self.admin_password, in_list=False) def test_revoke_anon_from_asset_in_public_collection(self): self.login(self.someuser.username, self.someuser_password) public_collection = self.create_collection('public_collection') child_asset = self.create_asset('child_asset_in_public_collection') self.add_to_collection(child_asset, public_collection) child_asset.refresh_from_db() # Anon should have no access at this point self.client.logout() self.assert_viewable(child_asset, viewable=False) # Grant anon access to the parent collection self.login(self.someuser.username, self.someuser_password) self.add_perm(public_collection, self.anon, 'view_') # Verify anon can access the child asset self.client.logout() # Anon can only see a public asset by accessing the detail view # directly; `assert_viewble()` will always fail because it expects the # asset to be in the list view as well self.assert_detail_viewable(child_asset) # Revoke anon's access to the child asset self.login(self.someuser.username, self.someuser_password) self.remove_perm_v2_api(child_asset, self.anon, PERM_VIEW_ASSET) # Make sure anon cannot access the child asset any longer self.client.logout() self.assert_viewable(child_asset, viewable=False) class ApiPermissionsTestCase(KpiTestCase): fixtures = ['test_data'] URL_NAMESPACE = ROUTER_URL_NAMESPACE def setUp(self): self.admin = User.objects.get(username='admin') self.admin_password = 'pass' self.someuser = User.objects.get(username='someuser') self.someuser_password = 'someuser' self.anotheruser = User.objects.get(username='anotheruser') self.anotheruser_password = 'anotheruser' self.assertTrue(self.client.login(username=self.admin.username, password=self.admin_password)) self.admin_asset = self.create_asset('admin_asset') self.admin_collection = self.create_collection('admin_collection') self.child_collection = self.create_collection('child_collection') self.add_to_collection(self.child_collection, self.admin_collection) self.client.logout() ################# Asset tests ##################### def test_own_asset_in_asset_list(self): self.assert_viewable(self.admin_asset, self.admin, self.admin_password) def test_viewable_asset_in_asset_list(self): # Give "someuser" view permissions on an asset owned by "admin". self.add_perm(self.admin_asset, self.someuser, 'view_') # Test that "someuser" can now view the asset. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password) def test_non_viewable_asset_not_in_asset_list(self): # Wow, that's quite a function name... # Ensure that "someuser" doesn't have permission to view the survey # asset owned by "admin". perm_name = self._get_perm_name('view_', self.admin_asset) self.assertFalse(self.someuser.has_perm(perm_name, self.admin_asset)) # Verify they can't view the asset through the API. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password, viewable=False) def test_inherited_viewable_assets_in_asset_list(self): # Give "someuser" view permissions on a collection owned by "admin" and # add an asset also owned by "admin" to that collection. self.add_perm(self.admin_asset, self.someuser, 'view_') self.add_to_collection(self.admin_asset, self.admin_collection, self.admin, self.admin_password) # Test that "someuser" can now view the asset. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password) def test_viewable_asset_inheritance_conflict(self): # Log in as "admin", create a new child collection, and add an asset to # that collection. self.add_to_collection(self.admin_asset, self.child_collection, self.admin, self.admin_password) # Give "someuser" view permission on 'child_collection'. self.add_perm(self.child_collection, self.someuser, 'view_') # Give "someuser" view permission on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Revoke the view permissions of "someuser" on the parent collection. self.remove_perm(self.admin_collection, self.admin, self.admin_password, self.someuser, self.someuser_password, 'view_') # Confirm that "someuser" can view the contents of 'child_collection'. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password) def test_non_viewable_asset_inheritance_conflict(self): # Log in as "admin", create a new child collection, and add an asset to # that collection. self.add_to_collection(self.admin_asset, self.child_collection, self.admin, self.admin_password) # Give "someuser" view permission on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Revoke the view permissions of "someuser" on the child collection. self.remove_perm(self.child_collection, self.admin, self.admin_password, self.someuser, self.someuser_password, 'view_') # Confirm that "someuser" can't view the contents of 'child_collection'. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password, viewable=False) def test_viewable_asset_not_deletable(self): # Give "someuser" view permissions on an asset owned by "admin". self.add_perm(self.admin_asset, self.someuser, 'view_') # Confirm that "someuser" is not allowed to delete the asset. delete_perm = self._get_perm_name('delete_', self.admin_asset) self.assertFalse(self.someuser.has_perm(delete_perm, self.admin_asset)) # Test that "someuser" can't delete the asset. self.client.login(username=self.someuser.username, password=self.someuser_password) url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.admin_asset.uid}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_inherited_viewable_asset_not_deletable(self): # Give "someuser" view permissions on a collection owned by "admin" and # add an asset also owned by "admin" to that collection. self.add_perm(self.admin_asset, self.someuser, 'view_') self.add_to_collection(self.admin_asset, self.admin_collection, self.admin, self.admin_password) # Confirm that "someuser" is not allowed to delete the asset. delete_perm = self._get_perm_name('delete_', self.admin_asset) self.assertFalse(self.someuser.has_perm(delete_perm, self.admin_asset)) # Test that "someuser" can't delete the asset. self.client.login(username=self.someuser.username, password=self.someuser_password) url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.admin_asset.uid}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_shared_asset_remove_own_permissions_allowed(self): """ Ensuring that a non-owner who has been shared an asset is able to remove themselves from that asset if they want. """ self.client.login( username=self.someuser.username, password=self.someuser_password, ) new_asset = self.create_asset( name='a new asset', owner=self.someuser, ) perm = new_asset.assign_perm(self.anotheruser, 'view_asset') kwargs = { 'parent_lookup_asset': new_asset.uid, 'uid': perm.uid, } url = reverse( 'api_v2:asset-permission-assignment-detail', kwargs=kwargs ) self.client.logout() self.client.login( username=self.anotheruser.username, password=self.anotheruser_password, ) assert self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset) # `anotheruser` attempting to remove themselves from the asset res = self.client.delete(url) assert res.status_code == status.HTTP_204_NO_CONTENT assert not self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset) assert len(new_asset.get_perms(self.anotheruser)) == 0 def test_shared_asset_non_owner_remove_owners_permissions_not_allowed(self): """ Ensuring that a non-owner who has been shared an asset is not able to remove permissions from the owner of that asset """ self.client.login( username=self.someuser.username, password=self.someuser_password, ) new_asset = self.create_asset( name='a new asset', owner=self.someuser, ) # Getting existing permission for the owner of the asset perm = ObjectPermission.objects.filter(asset=new_asset).get( user=self.someuser, permission__codename=PERM_VIEW_ASSET ) new_asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) kwargs = { 'parent_lookup_asset': new_asset.uid, 'uid': perm.uid, } url = reverse( 'api_v2:asset-permission-assignment-detail', kwargs=kwargs ) self.client.logout() self.client.login( username=self.anotheruser.username, password=self.anotheruser_password, ) assert self.someuser.has_perm(PERM_VIEW_ASSET, new_asset) # `anotheruser` attempting to remove `someuser` from the asset res = self.client.delete(url) assert res.status_code == status.HTTP_403_FORBIDDEN assert self.someuser.has_perm(PERM_VIEW_ASSET, new_asset) def test_shared_asset_non_owner_remove_another_non_owners_permissions_not_allowed(self): """ Ensuring that a non-owner who has an asset shared with them cannot remove permissions from another non-owner with that same asset shared with them. """ yetanotheruser = User.objects.create( username='yetanotheruser', ) self.client.login( username=self.someuser.username, password=self.someuser_password, ) new_asset = self.create_asset( name='a new asset', owner=self.someuser, owner_password=self.someuser_password, ) new_asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) perm = new_asset.assign_perm(yetanotheruser, PERM_VIEW_ASSET) kwargs = { 'parent_lookup_asset': new_asset.uid, 'uid': perm.uid, } url = reverse( 'api_v2:asset-permission-assignment-detail', kwargs=kwargs ) self.client.logout() self.client.login( username=self.anotheruser.username, password=self.anotheruser_password, ) assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset) # `anotheruser` attempting to remove `yetanotheruser` from the asset res = self.client.delete(url) assert res.status_code == status.HTTP_404_NOT_FOUND assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset) def test_shared_asset_manage_asset_remove_another_non_owners_permissions_allowed(self): """ Ensure that a non-owner who has an asset shared with them and has `manage_asset` permissions is able to remove permissions from another non-owner with that same asset shared with them. """ yetanotheruser = User.objects.create( username='yetanotheruser', ) self.client.login( username=self.someuser.username, password=self.someuser_password, ) new_asset = self.create_asset( name='a new asset', owner=self.someuser, owner_password=self.someuser_password, ) new_asset.assign_perm(self.anotheruser, PERM_MANAGE_ASSET) perm = new_asset.assign_perm(yetanotheruser, PERM_VIEW_ASSET) kwargs = { 'parent_lookup_asset': new_asset.uid, 'uid': perm.uid, } url = reverse( 'api_v2:asset-permission-assignment-detail', kwargs=kwargs ) self.client.logout() self.client.login( username=self.anotheruser.username, password=self.anotheruser_password, ) assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset) # `anotheruser` attempting to remove `yetanotheruser` from the asset res = self.client.delete(url) assert res.status_code == status.HTTP_204_NO_CONTENT assert not yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset) def test_copy_permissions_between_assets(self): # Give "someuser" edit permissions on an asset owned by "admin" self.add_perm(self.admin_asset, self.someuser, 'change_') # Confirm that "someuser" has received the implied permissions expected_perms = [PERM_CHANGE_ASSET, PERM_VIEW_ASSET] self.assertListEqual( sorted(self.admin_asset.get_perms(self.someuser)), expected_perms ) # Create another asset to receive the copied permissions new_asset = self.create_asset( name='destination asset', owner=self.admin, owner_password=self.admin_password ) # Add some extraneous permissions to the destination asset; these # should be removed by the copy operation self.add_perm(new_asset, self.anotheruser, 'view_') self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset)) # Perform the permissions copy via the API endpoint self.client.login( username=self.admin.username, password=self.admin_password ) if self.URL_NAMESPACE is None: dest_asset_perm_url = reverse( 'asset-permissions', kwargs={'uid': new_asset.uid} ) else: dest_asset_perm_url = reverse( 'api_v2:asset-permission-assignment-clone', kwargs={'parent_lookup_asset': new_asset.uid} ) # TODO: check that `clone_from` can also be a URL. # You know, Roy Fielding and all that. self.client.patch( dest_asset_perm_url, data={'clone_from': self.admin_asset.uid} ) # Check the result; since the source and destination have the same # owner, the permissions should be identical self.assertDictEqual( self.admin_asset.get_users_with_perms(attach_perms=True), new_asset.get_users_with_perms(attach_perms=True) ) def test_cannot_copy_permissions_between_non_owned_assets(self): # Give "someuser" view permissions on an asset owned by "admin" self.add_perm(self.admin_asset, self.someuser, 'view_') self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset)) # Create another asset to receive the copied permissions new_asset = self.create_asset( name='destination asset', owner=self.admin, owner_password=self.admin_password ) # Give "someuser" edit permissions on the new asset owned by "admin" self.add_perm(new_asset, self.someuser, 'change_') self.assertTrue(self.someuser.has_perm(PERM_CHANGE_ASSET, new_asset)) new_asset_perms_before_copy_attempt = new_asset.get_users_with_perms( attach_perms=True ) # Perform the permissions copy via the API endpoint self.client.login( username=self.someuser.username, password=self.someuser_password ) if self.URL_NAMESPACE is None: dest_asset_perm_url = reverse( 'asset-permissions', kwargs={'uid': new_asset.uid} ) else: dest_asset_perm_url = reverse( 'api_v2:asset-permission-assignment-clone', kwargs={'parent_lookup_asset': new_asset.uid} ) response = self.client.patch( dest_asset_perm_url, data={'clone_from': self.admin_asset.uid} ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # Check the result; nothing should have changed self.assertDictEqual( new_asset_perms_before_copy_attempt, new_asset.get_users_with_perms(attach_perms=True) ) def test_user_cannot_copy_permissions_from_non_viewable_asset(self): # Make sure "someuser" cannot view the asset owned by "admin" self.assertFalse( self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset) ) # Create another asset to receive the copied permissions new_asset = self.create_asset( name='destination asset', owner=self.admin, owner_password=self.admin_password ) # Take note of the destination asset's permissions to make sure they # are *not* changed later dest_asset_original_perms = new_asset.get_users_with_perms( attach_perms=True ) # Perform the permissions copy via the API endpoint self.client.login( username=self.someuser.username, password=self.someuser_password ) if self.URL_NAMESPACE is None: dest_asset_perm_url = reverse( 'asset-permissions', kwargs={'uid': new_asset.uid} ) else: dest_asset_perm_url = reverse( 'api_v2:asset-permission-assignment-clone', kwargs={'parent_lookup_asset': new_asset.uid} ) response = self.client.patch( dest_asset_perm_url, data={'clone_from': self.admin_asset.uid} ) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # Make sure no permissions were changed on the destination asset self.assertDictEqual( dest_asset_original_perms, new_asset.get_users_with_perms(attach_perms=True) ) def test_user_cannot_copy_permissions_to_non_editable_asset(self): # Give "someuser" view permissions on an asset owned by "admin" self.add_perm(self.admin_asset, self.someuser, 'view_') self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset)) # Create another asset to receive the copied permissions new_asset = self.create_asset( name='destination asset', owner=self.admin, owner_password=self.admin_password ) # Give "someuser" view permissions on the new asset owned by "admin" self.add_perm(new_asset, self.someuser, 'view_') self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, new_asset)) # Take note of the destination asset's permissions to make sure they # are *not* changed later dest_asset_original_perms = new_asset.get_users_with_perms( attach_perms=True ) # Perform the permissions copy via the API endpoint self.client.login( username=self.someuser.username, password=self.someuser_password ) if self.URL_NAMESPACE is None: dest_asset_perm_url = reverse( 'asset-permissions', kwargs={'uid': new_asset.uid} ) else: dest_asset_perm_url = reverse( 'api_v2:asset-permission-assignment-clone', kwargs={'parent_lookup_asset': new_asset.uid} ) response = self.client.patch( dest_asset_perm_url, data={'clone_from': self.admin_asset.uid} ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # Make sure no permissions were changed on the destination asset self.assertDictEqual( dest_asset_original_perms, new_asset.get_users_with_perms(attach_perms=True) ) ############# Collection tests ############### def test_own_collection_in_collection_list(self): self.assert_viewable(self.admin_collection, self.admin, self.admin_password) def test_viewable_collection_in_collection_list(self): # Give "someuser" view permissions on a collection owned by "admin". self.add_perm(self.admin_collection, self.someuser, 'view_') # Test that "someuser" can now view the collection. self.assert_viewable(self.admin_collection, self.someuser, self.someuser_password) def test_non_viewable_collection_not_in_collection_list(self): # Wow, that's quite a function name... # Ensure that "someuser" doesn't have permission to view the survey # collection owned by "admin". perm_name = self._get_perm_name('view_', self.admin_collection) self.assertFalse(self.someuser.has_perm(perm_name, self.admin_collection)) # Verify they can't view the collection through the API. self.assert_viewable(self.admin_collection, self.someuser, self.someuser_password, viewable=False) def test_inherited_viewable_collections_in_collection_list(self): # Give "someuser" view permissions on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Test that "someuser" can now view the child collection. self.assert_viewable(self.child_collection, self.someuser, self.someuser_password) def test_viewable_collection_inheritance_conflict(self): grandchild_collection = self.create_collection('grandchild_collection', self.admin, self.admin_password) self.add_to_collection(grandchild_collection, self.child_collection, self.admin, self.admin_password) # Give "someuser" view permission on 'child_collection'. self.add_perm(self.child_collection, self.someuser, 'view_') # Give "someuser" view permission on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Revoke the view permissions of "someuser" on 'parent_collection'. self.remove_perm(self.admin_collection, self.admin, self.admin_password, self.someuser, self.someuser_password, 'view_') # Confirm that "someuser" can view 'grandchild_collection'. self.assert_viewable(grandchild_collection, self.someuser, self.someuser_password) def test_non_viewable_collection_inheritance_conflict(self): grandchild_collection = self.create_collection('grandchild_collection', self.admin, self.admin_password) self.add_to_collection(grandchild_collection, self.child_collection, self.admin, self.admin_password) # Give "someuser" view permission on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Revoke the view permissions of "someuser" on the child collection. self.remove_perm(self.child_collection, self.admin, self.admin_password, self.someuser, self.someuser_password, 'view_') # Confirm that "someuser" can't view 'grandchild_collection'. self.assert_viewable(grandchild_collection, self.someuser, self.someuser_password, viewable=False) def test_viewable_collection_not_deletable(self): # Give "someuser" view permissions on a collection owned by "admin". self.add_perm(self.admin_collection, self.someuser, 'view_') # Confirm that "someuser" is not allowed to delete the collection. delete_perm = self._get_perm_name('delete_', self.admin_collection) self.assertFalse(self.someuser.has_perm(delete_perm, self.admin_collection)) # Test that "someuser" can't delete the collection. self.client.login(username=self.someuser.username, password=self.someuser_password) url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.admin_collection.uid}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_inherited_viewable_collection_not_deletable(self): # Give "someuser" view permissions on a collection owned by "admin". self.add_perm(self.admin_collection, self.someuser, 'view_') # Confirm that "someuser" is not allowed to delete the child collection. delete_perm = self._get_perm_name('delete_', self.child_collection) self.assertFalse(self.someuser.has_perm(delete_perm, self.child_collection)) # Test that "someuser" can't delete the child collection. self.client.login(username=self.someuser.username, password=self.someuser_password) url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.child_collection.uid}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) class ApiAssignedPermissionsTestCase(KpiTestCase): """ An obnoxiously large amount of code to test that the endpoint for listing assigned permissions complies with the following rules: * Superusers see it all (and there is *no* pagination) * Anonymous users see nothing * Regular users see everything that concerns them, namely all their own permissions and all the owners' permissions for all objects to which they have been assigned any permission See also kpi.utils.object_permission.get_user_permission_assignments_queryset """ # TODO: does this duplicate stuff in # test_api_asset_permission_assignment.py / should it be moved there? URL_NAMESPACE = ROUTER_URL_NAMESPACE def setUp(self): super().setUp() self.anon = get_anonymous_user() self.super = User.objects.get(username='admin') self.super_password = 'pass' self.someuser = User.objects.get(username='someuser') self.someuser_password = 'someuser' self.anotheruser = User.objects.get(username='anotheruser') self.anotheruser_password = 'anotheruser' self.collection = Asset.objects.create( asset_type=ASSET_TYPE_COLLECTION, owner=self.someuser ) self.asset = Asset.objects.create(owner=self.someuser) def test_anon_only_sees_owner_and_anon_permissions(self): self.asset.assign_perm(self.anon, PERM_VIEW_ASSET) self.assertTrue(self.anon.has_perm(PERM_VIEW_ASSET, self.asset)) url = self.get_asset_perm_assignment_list_url(self.asset) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) user_urls = [] for username in [self.asset.owner.username, self.anon.username]: user_urls.append( self.absolute_reverse( self._get_endpoint('user-detail'), kwargs={'username': username}, ) ) self.assertSetEqual( set((a['user'] for a in response.data)), set(user_urls) ) def test_user_sees_relevant_permissions_on_assigned_objects(self): # A user with explicitly-assigned permissions should see their # own permissions and the owner's permissions, but not permissions # assigned to other users self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset)) irrelevant_user = User.objects.create(username='mindyourown') self.asset.assign_perm(irrelevant_user, PERM_VIEW_ASSET) self.client.login(username=self.anotheruser.username, password=self.anotheruser_password) url = self.get_asset_perm_assignment_list_url(self.asset) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) returned_urls = [r['url'] for r in response.data] all_obj_perms = self.asset.permissions.all() relevant_obj_perms = all_obj_perms.filter( user__in=(self.asset.owner, self.anotheruser), permission__codename__in=self.asset.get_assignable_permissions( with_partial=False ), ) self.assertListEqual( sorted(returned_urls), sorted( self.get_urls_for_asset_perm_assignment_objs( relevant_obj_perms, asset=self.asset ) ), ) def test_user_cannot_see_permissions_on_unassigned_objects(self): self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset)) self.client.login(username=self.anotheruser.username, password=self.anotheruser_password) url = self.get_asset_perm_assignment_list_url(self.collection) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_superuser_sees_all_permissions(self): self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset)) self.client.login(username=self.super.username, password=self.super_password) url = self.get_asset_perm_assignment_list_url(self.asset) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) returned_urls = [r['url'] for r in response.data] all_obj_perms = self.asset.permissions.all() self.assertListEqual( sorted(returned_urls), sorted( self.get_urls_for_asset_perm_assignment_objs( all_obj_perms, asset=self.asset ) ), )
kobotoolbox/kpi
kpi/tests/api/v2/test_api_permissions.py
Python
agpl-3.0
34,731
class CreateExports < ActiveRecord::Migration[4.2] def change create_table :exports do |t| t.references :organization, index: true t.references :user, index: true t.text :file t.integer :file_format, default: 0 t.integer :kind, default: 0 t.integer :progress, default: 0 t.integer :rows t.jsonb :options, default: {} t.timestamps null: false end end end
bikeindex/bike_index
db/migrate/20180918220604_create_exports.rb
Ruby
agpl-3.0
421
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package netkuliTesting; /** * * @author Phildor92 <phillip.evans09@hotmail.com> */ public class NetkulixGUI extends javax.swing.JFrame { /** * Creates new form NetkulixGUI */ public NetkulixGUI() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jInternalFrame1 = new javax.swing.JInternalFrame(); jLabel2 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jInternalFrame1.setBorder(javax.swing.BorderFactory.createTitledBorder("Main.VERSION")); jInternalFrame1.setVisible(true); jLabel2.setText("Sanity Testing"); jButton2.setText("Start!"); jScrollPane1.setToolTipText("Fill in comments"); jTextArea1.setColumns(19); jTextArea1.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N jTextArea1.setLineWrap(true); jTextArea1.setRows(5); jTextArea1.setText("Comments (e.g. Mac DUT, mobile device, etc...)"); jTextArea1.setToolTipText(""); jScrollPane1.setViewportView(jTextArea1); jTextField1.setText("SW version"); jTextField1.setToolTipText("Fill in the AUT version"); jButton1.setText("Start!"); jLabel1.setText("TestRail testing"); jRadioButton1.setText("Mac"); jRadioButton2.setText("Windows"); jRadioButton3.setText("Android/iOS"); javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane()); jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout); jInternalFrame1Layout.setHorizontalGroup( jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addContainerGap() .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(6, 6, 6) .addComponent(jButton2)) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(6, 6, 6) .addComponent(jButton1)) .addComponent(jSeparator1) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton1) .addComponent(jRadioButton2) .addComponent(jRadioButton3)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jInternalFrame1Layout.setVerticalGroup( jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addContainerGap(39, Short.MAX_VALUE) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jLabel2)) .addGap(18, 18, 18) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButton3))) .addGap(8, 8, 8) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1) .addComponent(jLabel1)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jInternalFrame1) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> final String VERSION = "NetkuliGUI 0.2";//version 0.2-16.08.30-A /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NetkulixGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JInternalFrame jInternalFrame1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
RealN-RnD/Test-Automation-C
src/netkuliTesting/NetkulixGUI.java
Java
agpl-3.0
9,645
/* * NASA Worldview * * This code was originally developed at NASA/Goddard Space Flight Center for * the Earth Science Data and Information System (ESDIS) project. * * Copyright (C) 2013 - 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. */ var wv = wv || {}; wv.proj = (function(self) { self.parse = function(state, errors, config) { // Permalink version 1.0 - 1.1 if ( state["switch"] ) { state.p = state["switch"]; delete state["switch"]; } var projId = state.p; if ( projId ) { if ( !config.projections[projId] ) { delete state.p; errors.push({message: "Unsupported projection: " + projId}); } } }; return self; })(wv.proj || {});
cchang3/worldview-design
src/animation-module/code/web/js/proj/wv.proj.js
JavaScript
agpl-3.0
885
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ package org.silverpeas.web.notificationserver.channel.silvermail.requesthandlers; import org.silverpeas.core.util.logging.SilverLogger; import org.silverpeas.core.web.mvc.controller.ComponentSessionController; import org.silverpeas.web.notificationserver.channel.silvermail.SILVERMAILRequestHandler; import org.silverpeas.web.notificationserver.channel.silvermail.SILVERMAILSessionController; import javax.inject.Named; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; @Singleton @Named("ReadMessage") public class ReadMessage implements SILVERMAILRequestHandler { @Override public String handleRequest(ComponentSessionController componentSC, HttpServletRequest request) { try { String sId = request.getParameter("ID"); long id = Long.parseLong(sId); ((SILVERMAILSessionController) componentSC).setCurrentMessageId(id); } catch (NumberFormatException e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } return "/SILVERMAIL/jsp/readMessage.jsp"; } }
SilverDav/Silverpeas-Core
core-war/src/main/java/org/silverpeas/web/notificationserver/channel/silvermail/requesthandlers/ReadMessage.java
Java
agpl-3.0
2,242
/******************************************************************************* * gvGeoportal is sponsored by the General Directorate for Information * Technologies (DGTI) of the Regional Ministry of Finance and Public * Administration of the Generalitat Valenciana (Valencian Community, * Spain), managed by gvSIG Association and led by DISID Corporation. * * Copyright (C) 2016 DGTI - Generalitat Valenciana * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package es.gva.dgti.gvgeoportal.security; import org.gvnix.addon.gva.security.providers.safe.GvNIXSafeLoginController; import org.springframework.stereotype.Controller; @GvNIXSafeLoginController @Controller public class SafeLoginController { }
gvSIGAssociation/gvsig-web
src/main/java/es/gva/dgti/gvgeoportal/security/SafeLoginController.java
Java
agpl-3.0
1,419
require 'spec_helper' describe Email do describe "create!" do it "should set the default app if none is given" do email = FactoryGirl.create(:email, app_id: nil) email.app.should be_default_app end context "One email is created" do before :each do FactoryGirl.create(:email, from: "matthew@foo.com", to: "foo@bar.com", data: "From: contact@openaustraliafoundation.org.au\nTo: Matthew Landauer\nSubject: This is a subject\nMessage-ID: <5161ba1c90b10_7837557029c754c8@kedumba.mail>\n\nHello!" ) end it "should set the message-id based on the email content" do Email.first.message_id.should == "5161ba1c90b10_7837557029c754c8@kedumba.mail" end it "should set a hash of the full email content" do Email.first.data_hash.should == "d096b1b1dfbcabf6bd4ef4d4b0ad88f562eedee9" end it "should have an identical hash to another email with identical content" do first_email = Email.first email = FactoryGirl.create(:email, from: "geoff@foo.com", to: "people@bar.com", data: first_email.data) email.data_hash.should == first_email.data_hash end it "should have a different hash to another email with different content" do first_email = Email.first email = FactoryGirl.create(:email, from: "geoff@foo.com", to: "people@bar.com", data: "Something else") email.data_hash.should_not == first_email.data_hash end it "should set the subject of the email based on the data" do Email.first.subject.should == "This is a subject" end end end describe "#from" do it "should return a string for the from email address" do email = FactoryGirl.create(:email, from_address: Address.create!(text: "matthew@foo.com")) email.from.should == "matthew@foo.com" end it "should allow the from_address to be set by a string" do email = FactoryGirl.create(:email, from: "matthew@foo.com") email.from.should == "matthew@foo.com" end end describe "#from_address" do it "should return an Address object" do email = FactoryGirl.create(:email, from: "matthew@foo.org") a1 = Address.find_by_text("matthew@foo.org") a1.should_not be_nil email.from_address.should == a1 end end describe "#to" do it "should return an array for all the email addresses" do email = FactoryGirl.create(:email, to: ["mlandauer@foo.org", "matthew@bar.com"]) email.to.should == ["mlandauer@foo.org", "matthew@bar.com"] end it "should be able to give just a single recipient" do email = Email.new(to: "mlandauer@foo.org") email.to.should == ["mlandauer@foo.org"] end it "should set created_at for deliveries too" do email = FactoryGirl.create(:email, to: "mlandauer@foo.org") email.deliveries.first.created_at.should_not be_nil end end describe "#to_addresses" do it "should return an array of Address objects" do email = FactoryGirl.create(:email, to: ["mlandauer@foo.org", "matthew@bar.com"]) a1 = Address.find_by_text("mlandauer@foo.org") a2 = Address.find_by_text("matthew@bar.com") a1.should_not be_nil a2.should_not be_nil email.to_addresses.should == [a1, a2] end end describe "#data" do context "one email" do before :each do FactoryGirl.create(:email, id: 10, data: "This is a main data section") end let(:email) { Email.find(10) } it "should be able to read in the data again" do email.data.should == "This is a main data section" end it "should be able to read in the data again even after being saved again" do email.save! email.data.should == "This is a main data section" end end it "should only keep the full data of a certain number of the emails around" do EmailDataCache.stub!(:max_no_emails_to_store_data).and_return(2) 4.times { FactoryGirl.create(:email, data: "This is a main section") } Dir.glob(File.join(EmailDataCache.data_filesystem_directory, "*")).count.should == 2 end end context "an email with a text part and an html part" do let(:mail) do Mail.new do text_part do body 'This is plain text' end html_part do content_type 'text/html; charset=UTF-8' body '<h1>This is HTML</h1>' end end end let(:email) do Email.new(data: mail.encoded) end describe "#html_part" do it { email.html_part.should == "<h1>This is HTML</h1>" } end describe "#text_part" do it { email.text_part.should == "This is plain text" } end end context "an email which just consistents of a single text part" do let(:mail) do Mail.new do body 'This is plain text' end end let(:email) do Email.new(data: mail.encoded) end describe "#html_part" do it { email.html_part.should be_nil } end describe "#text_part" do it { email.text_part.should == "This is plain text" } end end context "an email which just consistents of a single html part" do let(:mail) do Mail.new do content_type 'text/html; charset=UTF-8' body '<p>This is some html</p>' end end let(:email) do Email.new(data: mail.encoded) end describe "#html_part" do it { email.html_part.should == "<p>This is some html</p>" } end describe "#text_part" do it { email.text_part.should be_nil } end end context "an email which consistents of a part that is itself multipart" do let(:html_part) do Mail::Part.new do content_type 'text/html; charset=UTF-8' body '<p>This is some html</p>' end end let(:text_part) do Mail::Part.new do body 'This is plain text' end end let(:mail) do mail = Mail.new mail.part :content_type => "multipart/alternative" do |p| p.html_part = html_part p.text_part = text_part end mail end let(:email) do Email.new(data: mail.encoded) end describe "#html_part" do it { email.html_part.should == "<p>This is some html</p>" } end describe "#text_part" do it { email.text_part.should == 'This is plain text' } end end end
WebsterFolksLabs/cuttlefish
spec/models/email_spec.rb
Ruby
agpl-3.0
6,425
/* Copyright (C) 2006-2016 Patrick G. Durand * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * You may obtain a copy of the License at * * https://www.gnu.org/licenses/agpl-3.0.txt * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. */ package bzh.plealog.bioinfo.ui.feature; import java.awt.BorderLayout; import java.text.SimpleDateFormat; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import bzh.plealog.bioinfo.api.data.feature.FeatureTable; /** * This component is used to display the status information of a FeatureTable. * * @author Patrick G. Durand */ public class FeatureStatusViewer extends JPanel { private static final long serialVersionUID = 9153946953865147941L; private JTextField _date; private JTextField _source; private JTextField _status; private JTextField _message; private static final SimpleDateFormat DATE_FOMATTER1 = new SimpleDateFormat("dd-MMM-yyyy", Locale.UK); private static final SimpleDateFormat DATE_FOMATTER2 = new SimpleDateFormat("yyyyMMdd"); public FeatureStatusViewer(){ JLabel lbl; JPanel pnl1, pnl2, pnl3, pnl4, pnl5; pnl1 = new JPanel(new BorderLayout()); lbl = new JLabel("Retrieval date:"); _date = createTextField(); pnl1.add(lbl, BorderLayout.WEST); pnl1.add(_date, BorderLayout.CENTER); lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); pnl1.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0)); pnl2 = new JPanel(new BorderLayout()); lbl = new JLabel("Feature source:"); _source = createTextField(); pnl2.add(lbl, BorderLayout.WEST); pnl2.add(_source, BorderLayout.CENTER); lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); pnl2.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0)); pnl3 = new JPanel(new BorderLayout()); lbl = new JLabel("Message:"); _message = createTextField(); pnl3.add(lbl, BorderLayout.WEST); pnl3.add(_message, BorderLayout.CENTER); lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); pnl3.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0)); pnl4 = new JPanel(new BorderLayout()); lbl = new JLabel("Feature status:"); _status = createTextField(); pnl4.add(lbl, BorderLayout.WEST); pnl4.add(_status, BorderLayout.CENTER); lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); pnl4.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0)); pnl5 = new JPanel(); pnl5.setLayout(new BoxLayout(pnl5, BoxLayout.Y_AXIS)); pnl5.add(pnl1); pnl5.add(pnl2); pnl5.add(pnl4); pnl5.add(pnl3); this.setLayout(new BorderLayout()); this.add(pnl5, BorderLayout.NORTH); } /** * Utility method to create a JTextField. */ private JTextField createTextField(){ JTextField tf; tf = new JTextField(); tf.setEditable(false); tf.setBorder(null); tf.setOpaque(false); //tf.setForeground(DDResources.getSystemTextColor()); return tf; } /** * Reset the viewer. */ public void clear(){ setData(null); } /** * Utility method to conevert date formats. */ private String transformDate(String d){ String date="-"; try { date = DATE_FOMATTER1.format(DATE_FOMATTER2.parse(d)); } catch (Exception e) { } return date; } /** * Sets a new FeatureTable. * * @param fTable the feature table to display in this component. */ public void setData(FeatureTable fTable){ String val; if (fTable==null){ _date.setText(""); _source.setText(""); _status.setText(""); _message.setText(""); } else{ val = fTable.getDate(); _date.setText(val!=null?transformDate(val):"?"); val = fTable.getSource(); _source.setText(val!=null?val:"?"); _status.setText(fTable.getStatus()!=FeatureTable.ERROR_STATUS ? FeatureTable.OK_STATUS_S : FeatureTable.ERROR_STATUS_S); val = fTable.getMessage(); _message.setText((val!=null && !val.equals("-"))?val:"None"); } } }
pgdurand/Bioinformatics-UI-API
src/bzh/plealog/bioinfo/ui/feature/FeatureStatusViewer.java
Java
agpl-3.0
4,589
package com.tesora.dve.sql; /* * #%L * Tesora Inc. * Database Virtualization Engine * %% * Copyright (C) 2011 - 2014 Tesora Inc. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.sql.Timestamp; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import com.tesora.dve.errmap.MySQLErrors; import com.tesora.dve.resultset.ResultRow; import com.tesora.dve.server.bootstrap.BootstrapHost; import com.tesora.dve.sql.util.DBHelperConnectionResource; import com.tesora.dve.sql.util.PEDDL; import com.tesora.dve.sql.util.ProjectDDL; import com.tesora.dve.sql.util.ProxyConnectionResource; import com.tesora.dve.sql.util.ResourceResponse; import com.tesora.dve.sql.util.StorageGroupDDL; import com.tesora.dve.standalone.PETest; public class FunctionsTest extends SchemaTest { private static final ProjectDDL checkDDL = new PEDDL("checkdb", new StorageGroupDDL("check", 2, "checkg"), "schema"); @BeforeClass public static void setup() throws Exception { PETest.projectSetup(checkDDL); PETest.bootHost = BootstrapHost.startServices(PETest.class); } protected ProxyConnectionResource conn; protected DBHelperConnectionResource dbh; @Before public void connect() throws Throwable { conn = new ProxyConnectionResource(); checkDDL.create(conn); dbh = new DBHelperConnectionResource(); } @After public void disconnect() throws Throwable { if(conn != null) conn.disconnect(); conn = null; if(dbh != null) dbh.disconnect(); dbh = null; } @Test public void testLowerWithLike() throws Throwable { conn.execute("create table `a` (`id` int, `mask` varchar(50), primary key (`id`)) "); String select = "select 1 from a where id=1 and lower('MiXeD cAsE') like lower(mask)"; // query should return empty result set conn.assertResults(select, br()); // insert a row that does not satisfy the lower clause conn.execute("insert into a values (1,'some junk')"); // query should return empty result set conn.assertResults(select, br()); // update row so that it does satisfy the lower clause conn.execute("update a set mask='MIXED CASE'"); // query should return 1 row conn.assertResults(select, br(nr, Long.valueOf(1))); // make sure we didn't break the typical like parameter select = "select 1 from a where id=1 and mask like '%C%'"; conn.assertResults(select, br(nr, Long.valueOf(1))); } @Test public void testUnix_timestamp() throws Throwable { conn.execute("create table `tblUnixTS` (`id` int, `d` date, `dt` datetime, `ts` timestamp, primary key (`id`)) "); // these are the acceptable values that can be put into the unix_timestamp function String dateLiteral = "'1997-01-01'"; String datetimeLiteral = "'1998-02-02 00:00:01'"; String timestampLiteral = "'1999-03-03 23:59:59'"; long dateFormat1Long = 970101; long dateFormat2Long = 19970101; conn.execute("insert into tblUnixTS values (1,"+ dateLiteral + "," + datetimeLiteral + "," + timestampLiteral + ")"); // all the values are before the current time so no rows should be returned conn.assertResults("select 1 from tblUnixTS where unix_timestamp(d) > unix_timestamp()", br()); conn.assertResults("select 1 from tblUnixTS where unix_timestamp(dt) > unix_timestamp()", br()); conn.assertResults("select 1 from tblUnixTS where unix_timestamp(ts) > unix_timestamp()", br()); // this should return the row if we reverse the comparison operator conn.assertResults("select 1 from tblUnixTS where unix_timestamp(d) < unix_timestamp()", br(nr, Long.valueOf(1))); conn.assertResults("select 1 from tblUnixTS where unix_timestamp(dt) < unix_timestamp()", br(nr, Long.valueOf(1))); conn.assertResults("select 1 from tblUnixTS where unix_timestamp(ts) < unix_timestamp()", br(nr, Long.valueOf(1))); // make sure using a literal or a column definition as a parameter returns the same value compareUnixTimestampParamLiteralVSColumn( "select unix_timestamp(" + dateLiteral + ")", "select unix_timestamp(d) from tblUnixTS where id=1"); compareUnixTimestampParamLiteralVSColumn( "select unix_timestamp(" + datetimeLiteral + ")", "select unix_timestamp(dt) from tblUnixTS where id=1"); compareUnixTimestampParamLiteralVSColumn( "select unix_timestamp(" + timestampLiteral + ")", "select unix_timestamp(ts) from tblUnixTS where id=1"); compareUnixTimestampParamLiteralVSColumn( "select unix_timestamp(" + dateFormat1Long + ")", "select unix_timestamp(d) from tblUnixTS where id=1"); compareUnixTimestampParamLiteralVSColumn( "select unix_timestamp(" + dateFormat2Long + ")", "select unix_timestamp(d) from tblUnixTS where id=1"); } private void compareUnixTimestampParamLiteralVSColumn(String literalSql, String columnSql) throws Throwable { ResourceResponse resp = conn.fetch(literalSql); List<ResultRow> rows = resp.getResults(); assertEquals("Expected one row only", 1, rows.size()); Long literalLong = (Long) (rows.get(0).getResultColumn(1) .getColumnValue()); resp = conn.fetch(columnSql); rows = resp.getResults(); assertEquals("Expected one row only", 1, rows.size()); Long columnLong = (Long) (rows.get(0).getResultColumn(1) .getColumnValue()); assertEquals("Expected literal query (" + literalSql + ") to return same value as column query (" + columnSql + ")", literalLong, columnLong); } @Test public void testPE167() throws Throwable { conn.execute("create table ucp (`vid` integer unsigned not null, `length` integer, `width` integer, `height` integer);"); // test length as a column name String select = "SELECT length, width, height FROM ucp WHERE vid = 7710429"; // query should return empty result set conn.assertResults(select, br()); } @Test public void testPE168() throws Throwable { conn.execute("create table urs (`uid` integer unsigned not null, `created` timestamp);"); String select; String[] units = {"MICROSECOND", "SECOND", "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "QUARTER", "YEAR" }; for (String unit : units) { select = "SELECT uid FROM `urs` WHERE uid=420185 AND TIMESTAMPDIFF(" + unit + ", FROM_UNIXTIME(created), NOW()) <= 3"; // query should return empty result set conn.assertResults(select, br()); } // use a literal as a parameter select = "SELECT uid FROM `urs` WHERE uid=420185 AND TIMESTAMPDIFF(DAY, '2012-01-01', '2012-01-01')"; // query should return empty result set conn.assertResults(select, br()); try { select = "SELECT uid FROM `urs` WHERE uid=420185 AND TIMESTAMPDIFF(JUNK, '2012-01-01', '2012-01-01')"; conn.assertResults(select, br()); fail("JUNK is not a valid unit for timestampdiff"); } catch (Exception e) { // expected } } @Test public void test_PE222_utc_timestamp() throws Throwable { // From the doc: utc_timestamp returns the current UTC date and time // as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, // depending on whether the function is used in a string or numeric context. Timestamp ts; // try with and without parens ResourceResponse resp = conn.fetch("SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0"); List<ResultRow> rows = resp.getResults(); assertEquals("Expected one row only", 1, rows.size()); // If the types don't cast properly then we have a problem assertNotNull(ts = (Timestamp) (rows.get(0).getResultColumn(1).getColumnValue())); assertNotNull((rows.get(0).getResultColumn(2).getColumnValue())); // put function into an insert conn.execute("create table `tblUTCTS` (`id` int, `ts` timestamp, primary key (`id`)) "); conn.execute("insert into tblUTCTS values (1, utc_timestamp())"); // just make sure the ts2 is equal or after the above ts Timestamp ts2; resp = conn.fetch("select ts from tblUTCTS"); rows = resp.getResults(); assertEquals("Expected one row only", 1, rows.size()); assertNotNull(ts2 = (Timestamp) (rows.get(0).getResultColumn(1).getColumnValue())); assertTrue(ts.compareTo(ts2)<1); } @Test public void test_PE136_REGEXP() throws Throwable { StringBuilder buf = new StringBuilder(); buf.append("CREATE TABLE wpo ("); buf.append("oid bigint(20) unsigned NOT NULL auto_increment,"); buf.append("onm varchar(64) NOT NULL default '',"); buf.append("ov longtext NOT NULL,"); buf.append("al varchar(20) NOT NULL default 'yes',"); buf.append("PRIMARY KEY (oid),"); buf.append("UNIQUE KEY onm (onm)"); buf.append(") DEFAULT CHARACTER SET utf8 "); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("INSERT INTO `wpo` ("); buf.append("`onm`, `ov`, `al`) "); buf.append("VALUES ("); buf.append("'_site_transient_timeout_theme_roots', '1325536233', 'yes') "); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("INSERT INTO `wpo` ("); buf.append("`onm`, `ov`, `al`) "); buf.append("VALUES ("); buf.append("'rss_00000000000000000000000000000000', '0000000000', 'no') "); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("SELECT `onm`, `ov`, `al` "); buf.append("FROM wpo WHERE onm REGEXP '^rss_[0-9a-f]{32}(_ts)?$'"); conn.assertResults(buf.toString(), br(nr, "rss_00000000000000000000000000000000", "0000000000", "no")); buf = new StringBuilder(); buf.append("SELECT `onm`, `ov`, `al` "); buf.append("FROM wpo WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'"); conn.assertResults(buf.toString(), br(nr, "rss_00000000000000000000000000000000", "0000000000", "no")); buf = new StringBuilder(); buf.append("UPDATE wpo "); buf.append("SET `ov`='1111111111' "); buf.append("WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("SELECT `onm`, `ov`, `al` "); buf.append("FROM wpo WHERE onm RLIKE '^[0-9a-f]{32}(_ts)?$'"); conn.assertResults(buf.toString(), br()); buf = new StringBuilder(); buf.append("SELECT `onm`, `ov`, `al` "); buf.append("FROM wpo WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'"); conn.assertResults(buf.toString(), br(nr, "rss_00000000000000000000000000000000", "1111111111", "no")); buf = new StringBuilder(); buf.append("DELETE FROM wpo "); buf.append("WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("SELECT `onm`, `ov`, `al` "); buf.append("FROM wpo WHERE onm RLIKE '^rss_[0-9a-f]{32}(_ts)?$'"); conn.assertResults(buf.toString(), br()); } @Test public void test_NULLIF() throws Throwable { StringBuilder buf = new StringBuilder(); buf.append("CREATE TABLE wp_usermeta ("); buf.append("umid bigint(20) unsigned NOT NULL auto_increment,"); buf.append("uid bigint(20) unsigned NOT NULL default '0',"); buf.append("mk varchar(255) default NULL,"); buf.append("mv longtext,"); buf.append("PRIMARY KEY (umid),"); buf.append("KEY uid (uid),"); buf.append("KEY mk (mk)"); buf.append(") DEFAULT CHARACTER SET utf8 "); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("INSERT INTO `wp_usermeta` ("); buf.append("`uid`,`mk`,`mv`) "); buf.append("VALUES "); buf.append("('1','last_name',''),"); buf.append("('1','nickname','admin'),"); buf.append("('1','description',''),"); buf.append("('1','rich_editing','true'),"); buf.append("('1','comment_shortcuts','false'),"); buf.append("('1','admin_color','fresh'),"); buf.append("('1','use_ssl','0'),"); buf.append("('1','show_admin_bar_front','true'),"); buf.append("('1','wp_capabilities','a:1:{s:10:\"subscriber\";s:1:\"1\";}'),"); buf.append("('1','wp_user_level','0'),"); buf.append("('1','dismissed_wp_pointers','wp330_toolbar,wp330_media_uploader,wp330_saving_widgets'),"); buf.append("('1','show_welcome_panel','1'),"); buf.append("('1','wp_dashboard_quick_press_last_post_id','3')"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("SELECT "); buf.append("COUNT(NULLIF(`mv` LIKE '%administrator%', FALSE)),"); buf.append("COUNT(NULLIF(`mv` LIKE '%editor%', FALSE)),"); buf.append("COUNT(NULLIF(`mv` LIKE '%author%', FALSE)),"); buf.append("COUNT(NULLIF(`mv` LIKE '%contributor%', FALSE)),"); buf.append("COUNT(NULLIF(`mv` LIKE '%subscriber%', FALSE)),"); buf.append("COUNT(*) "); buf.append("FROM wp_usermeta "); buf.append("WHERE mk = 'wp_capabilities'"); conn.assertResults(buf.toString(), br(nr, Long.valueOf(0), Long.valueOf(0), Long.valueOf(0), Long.valueOf(0), Long.valueOf(1), Long.valueOf(1))); } @Test public void test_DATE_SUB_or_ADD_and_YEAR_MONTH() throws Throwable { StringBuilder buf = new StringBuilder(); buf.append("CREATE TABLE wpp ("); buf.append("ID bigint(20) unsigned NOT NULL auto_increment,"); buf.append("pd datetime NOT NULL default '0000-00-00 00:00:00',"); buf.append("ps varchar(20) NOT NULL default 'publish',"); buf.append("pt varchar(20) NOT NULL default 'post',"); buf.append("PRIMARY KEY (ID)"); buf.append(") DEFAULT CHARACTER SET utf8 "); buf.append("BROADCAST DISTRIBUTE "); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("CREATE TABLE a_broadcast_table_to_join ("); buf.append("ID bigint(20) unsigned NOT NULL auto_increment,"); buf.append("pt varchar(20) NOT NULL default 'post',"); buf.append("PRIMARY KEY (ID)"); buf.append(") DEFAULT CHARACTER SET utf8 "); buf.append("BROADCAST DISTRIBUTE "); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("CREATE TABLE a_random_table_to_join ("); buf.append("ID bigint(20) unsigned NOT NULL auto_increment,"); buf.append("pt varchar(20) NOT NULL default 'post',"); buf.append("PRIMARY KEY (ID)"); buf.append(") DEFAULT CHARACTER SET utf8 "); buf.append("RANDOM DISTRIBUTE "); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("INSERT INTO `wpp` ("); buf.append("`pd`) "); buf.append("VALUES "); buf.append("('2012-01-02 18:30:33')"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("INSERT INTO `wpp` ("); buf.append("`pd`,`pt`) "); buf.append("VALUES "); buf.append("('2012-02-02 18:30:33','page')"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("INSERT INTO `wpp` ("); buf.append("`pd`,`ps`,`pt`) "); buf.append("VALUES "); buf.append("('2012-03-02 18:31:00','auto-draft','post')"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("SELECT ID "); buf.append("FROM wpp "); buf.append("WHERE ps = 'auto-draft' "); buf.append("AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > pd "); conn.assertResults(buf.toString(), br(nr, Long.valueOf(3))); buf = new StringBuilder(); buf.append("SELECT ID "); buf.append("FROM wpp "); buf.append("WHERE DATE_ADD( '2012-01-01 18:31:00', INTERVAL 2 DAY ) > pd "); conn.assertResults(buf.toString(), br(nr, Long.valueOf(1))); buf = new StringBuilder(); buf.append("SELECT DISTINCT YEAR( pd ) AS year, MONTH( pd) AS month "); buf.append("FROM wpp "); buf.append("WHERE pt = 'page' "); buf.append("ORDER BY pd desc"); conn.assertResults(buf.toString(), br(nr, Integer.valueOf(2012), Integer.valueOf(2))); // make sure the following don't throw exceptions buf = new StringBuilder(); buf.append("SELECT DISTINCT YEAR( p.pd ) AS year, MONTH( p.pd) AS month "); buf.append("FROM wpp p INNER JOIN a_broadcast_table_to_join j "); buf.append("ON p.ID = j.ID "); buf.append("ORDER BY pd desc"); conn.assertResults(buf.toString(), br()); buf = new StringBuilder(); buf.append("SELECT DISTINCT YEAR( p.pd ) AS year, MONTH( p.pd) AS month "); buf.append("FROM wpp p INNER JOIN a_random_table_to_join j "); buf.append("ON p.ID = j.ID "); buf.append("ORDER BY pd desc"); conn.assertResults(buf.toString(), br()); } @Test public void testPE775() throws Throwable { StringBuilder buf = new StringBuilder(); buf.append("CREATE TABLE `umt` ( "); buf.append("`uid` int(11) NOT NULL, "); buf.append("`token` varchar(100) NOT NULL, "); buf.append("`datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, "); buf.append("PRIMARY KEY (`token`), "); buf.append("KEY `uid` (`uid`) "); buf.append(") ENGINE=MyISAM DEFAULT CHARSET=utf8 /*#dve BROADCAST DISTRIBUTE */ "); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("INSERT INTO umt (uid,token,datetime) "); buf.append("VALUES "); buf.append("(2904,'c0ab2d0a53de4522223ae0c8d08e871294debbe29a72fba8c38b326ad7261507',now())"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("SELECT count(*) FROM umt"); conn.assertResults(buf.toString(), br(nr, Long.valueOf(1))); buf = new StringBuilder(); buf.append("SELECT datetime FROM umt"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("UPDATE umt SET datetime=now()"); conn.execute(buf.toString()); } @Test public void testPE951_LEFT() throws Throwable { StringBuilder buf = new StringBuilder(); buf.append("CREATE TABLE `pe951` ( `value` varchar(100) NOT NULL )"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("INSERT INTO pe951 VALUES ('123456789012345678901234567890'), ('This is a test string')"); conn.execute(buf.toString()); buf = new StringBuilder(); buf.append("SELECT value FROM pe951 ORDER BY value"); conn.assertResults(buf.toString(), br(nr, "123456789012345678901234567890", nr, "This is a test string")); buf = new StringBuilder(); buf.append("SELECT LEFT(value,10) FROM pe951 ORDER BY value"); conn.assertResults(buf.toString(), br(nr, "1234567890", nr, "This is a ")); } @Test public void testPE988_REPLACE() throws Throwable { final String test1 = "SELECT REPLACE('Hello, World!', 'Hello', 'Hi')"; conn.assertResults(test1, br(nr, "Hi, World!")); conn.execute("CREATE TABLE `pe988` ( `id` int(11) NOT NULL" + ", `name` varchar(256) NOT NULL )"); conn.execute("INSERT INTO `pe988` VALUES (1, 'float')"); conn.execute("INSERT INTO `pe988` VALUES (2, ' int')"); conn.execute("INSERT INTO `pe988` VALUES (3, 'text ')"); conn.execute("INSERT INTO `pe988` VALUES (4, ' char ')"); conn.execute("INSERT INTO `pe988` VALUES (5, 'long long')"); conn.execute("INSERT INTO `pe988` VALUES (6, ' tiny text')"); conn.execute("INSERT INTO `pe988` VALUES (7, 'unsigned int ')"); conn.execute("INSERT INTO `pe988` VALUES (8, ' long double ')"); conn.execute("INSERT INTO `pe988` VALUES (9, ' some long text with spaces and tabs ');"); final String test2 = "SELECT REPLACE(pe988.name, ' ', '-') FROM pe988 ORDER BY id"; conn.assertResults(test2, br( nr, "float", nr, "-int", nr, "text-", nr, "-char-", nr, "long-long", nr, "-tiny-text", nr, "unsigned-int-", nr, "-long-double-", nr, "--some--long--text---with--spaces--and tabs--")); } @Test public void testPE1156_GroupConcatMaxLen() throws Throwable { final String test = "SELECT GROUP_CONCAT('a', 'b', 'c', 'd', 'e', 'f', 'g')"; conn.assertResults(test, br(nr, "abcdefg")); conn.execute("SET SESSION group_concat_max_len = 5"); conn.assertResults(test, br(nr, "abcde")); } @Test public void testPE362_Char() throws Throwable { final String test1In = "SELECT CHAR(77,121,83,81,'76')"; final String test1Out = "MySQL"; /* By default, CHAR() returns a binary string. */ conn.assertResults(test1In, br(nr, test1Out.getBytes())); conn.assertResults( "SELECT CHAR(0x4E, NULL, 0x55, NULL, 0x4C, NULL, 0x4C USING utf8)", br(nr, "NULL")); } @Ignore @Test public void testPE347_Interval() throws Throwable { conn.assertResults("SELECT INTERVAL(55,10,20,30,40,50,60,70,80,90,100)", br(nr, 5)); conn.assertResults("SELECT INTERVAL(3,1,1+1,1+1+1+1)", br(nr, 2)); conn.assertResults("SELECT INTERVAL(0,1,2,3,4)", br(nr, 0)); conn.assertResults("SELECT INTERVAL(NULL,1,2,3,4)", br(nr, -1)); } @Ignore @Test public void testPE347_Elt() throws Throwable { conn.assertResults("SELECT ELT(2,\"ONE\",\"TWO\",\"THREE\")", br(nr, "TWO")); conn.assertResults("SELECT ELT(0,\"ONE\",\"TWO\",\"THREE\")", br(nr, null)); conn.assertResults("SELECT ELT(4,\"ONE\",\"TWO\",\"THREE\")", br(nr, null)); conn.assertResults("SELECT ELT(1,1,2,3)|0)", br(nr, 1)); conn.assertResults("SELECT ELT(1,1.1,1.2,1.3)+0)", br(nr, 1.1)); } @Test public void testPE347_Field() throws Throwable { conn.assertResults("SELECT FIELD(\"IBM\",\"NCA\",\"ICL\",\"SUN\",\"IBM\",\"DIGITAL\")", br(nr, 4l)); conn.assertResults("SELECT FIELD(\"TESORA\",\"NCA\",\"ICL\",\"SUN\",\"IBM\",\"DIGITAL\")", br(nr, 0l)); } @Test public void testPE1403_Rand() throws Throwable { new ExpectedSqlErrorTester() { @Override public void test() throws Throwable { conn.execute("SELECT RAND(1,2,3)"); } }.assertError(SchemaException.class, MySQLErrors.incorrectParamCountFormatter, "RAND"); assertResultDistribution("SELECT RAND()", 1, 1, 10, true); assertResultDistribution("SELECT RAND(0)", 1, 1, 10, false); assertResultDistribution("SELECT RAND(5)", 1, 1, 10, false); conn.execute("CREATE TABLE pe1403 (id INT NOT NULL)"); conn.execute("INSERT INTO pe1403 VALUES (1), (2), (3), (4), (5), (6)"); assertResultDistribution("SELECT id, RAND() FROM pe1403", 2, 6, 1, true); assertResultDistribution("SELECT id, RAND(0) FROM pe1403", 2, 6, 1, true); assertResultDistribution("SELECT id, RAND(5) FROM pe1403", 2, 6, 1, true); } private void assertResultDistribution(final String stmt, final int columnIndex, final int expectedNumRows, final int numTrials, final boolean assertRandom) throws Throwable { final Set<Object> results = new HashSet<Object>(numTrials); for (int i = 0; i < numTrials; ++i) { final ResourceResponse response = conn.execute(stmt); final List<ResultRow> rows = response.getResults(); assertEquals("Wrong number of rows in the result set.", expectedNumRows, rows.size()); for (final ResultRow row : rows) { results.add(row.getResultColumn(columnIndex).getColumnValue()); } } if (assertRandom) { assertTrue("Random results expected.", results.size() == (expectedNumRows * numTrials)); } else { assertTrue("Equal results expected.", results.size() == 1); } } @Test public void testPE311_XOR() throws Throwable { conn.assertResults("SELECT 1 XOR 1", br(nr, 0l)); conn.assertResults("SELECT 1 XOR 0", br(nr, 1l)); conn.assertResults("SELECT 1 XOR NULL", br(nr, null)); conn.assertResults("SELECT 1 XOR 1 XOR 1", br(nr, 1l)); conn.execute("CREATE TABLE `pe311` (`id` int, `value` varchar(10), PRIMARY KEY (`id`))"); conn.execute("INSERT INTO `pe311` VALUES (1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')"); conn.assertResults("SELECT id XOR id, value FROM pe311 WHERE ((id > 2) XOR (id < 4)) ORDER BY id ASC", br(nr, 0l, "one", nr, 0l, "two", nr, 0l, "four", nr, 0l, "five")); } @Test public void testPE761() throws Throwable { conn.execute("CREATE TABLE `pe761_A` (`value` int)"); conn.execute("INSERT INTO `pe761_A` VALUES (1), (2), (3), (4)"); conn.assertResults("SELECT ROUND(VAR_SAMP(`value`), 4) FROM `pe761_A`", br(nr, 1.6667)); conn.assertResults("SELECT ROUND(VARIANCE(`value`), 4) FROM `pe761_A`", br(nr, 1.2500)); conn.assertResults("SELECT ROUND(VAR_POP(`value`), 4) FROM `pe761_A`", br(nr, 1.2500)); conn.assertResults("SELECT ROUND(STDDEV_SAMP(`value`), 4) FROM `pe761_A`", br(nr, 1.2910)); conn.assertResults("SELECT ROUND(STDDEV(`value`), 4) FROM `pe761_A`", br(nr, 1.1180)); conn.assertResults("SELECT ROUND(STD(`value`), 4) FROM `pe761_A`", br(nr, 1.1180)); conn.assertResults("SELECT ROUND(STDDEV_POP(`value`), 4) FROM `pe761_A`", br(nr, 1.1180)); conn.execute("CREATE TABLE `pe761_B` (`id` int not null, `value` int)"); conn.execute("INSERT INTO `pe761_B` VALUES (1, 1), (1, 2), (1, 3)," + "(2, 4), (2, 5), (2, 6), (3, 7), (3, 8), (3, 9)"); conn.assertResults("SELECT ROUND(VAR_SAMP(`value`), 4) FROM `pe761_B` GROUP BY `id`", br(nr, 1.0, nr, 1.0, nr, 1.0)); conn.assertResults("SELECT ROUND(VARIANCE(`value`), 4) FROM `pe761_B` GROUP BY `id`", br(nr, 0.6667, nr, 0.6667, nr, 0.6667)); conn.assertResults("SELECT ROUND(VAR_POP(`value`), 4) FROM `pe761_B` GROUP BY `id`", br(nr, 0.6667, nr, 0.6667, nr, 0.6667)); conn.assertResults("SELECT ROUND(STDDEV_SAMP(`value`), 4) FROM `pe761_B` GROUP BY `id`", br(nr, 1.0, nr, 1.0, nr, 1.0)); conn.assertResults("SELECT ROUND(STDDEV(`value`), 4) FROM `pe761_B` GROUP BY `id`", br(nr, 0.8165, nr, 0.8165, nr, 0.8165)); conn.assertResults("SELECT ROUND(STD(`value`), 4) FROM `pe761_B` GROUP BY `id`", br(nr, 0.8165, nr, 0.8165, nr, 0.8165)); conn.assertResults("SELECT ROUND(STDDEV_POP(`value`), 4) FROM `pe761_B` GROUP BY `id`", br(nr, 0.8165, nr, 0.8165, nr, 0.8165)); } @Test public void testPower() throws Throwable { conn.assertResults("SELECT POW(3, 2)", br(nr, 9.0)); conn.assertResults("SELECT POWER(3, 3)", br(nr, 27.0)); } }
Tesora/tesora-dve-pub
tesora-dve-core/src/test/java/com/tesora/dve/sql/FunctionsTest.java
Java
agpl-3.0
26,017
<?php /** * Copyright (c) 2015 ScientiaMobile, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Refer to the COPYING.txt file distributed with this package. * * * @category WURFL * @copyright ScientiaMobile, Inc. * @license GNU Affero General Public License */ namespace Wurfl\Configuration; use Noodlehaus\Config as ConfigLoader; /** * XML Configuration */ class FileConfig extends Config { /** * Creates a new WURFL Configuration object from $configFilePath * * @param string $configFilePath Complete filename of configuration file * * @throws \InvalidArgumentException */ public function __construct($configFilePath) { if (!file_exists($configFilePath)) { throw new \InvalidArgumentException('The configuration file ' . $configFilePath . ' does not exist.'); } $this->configFilePath = $configFilePath; $this->configurationFileDir = dirname($this->configFilePath); $configLoader = new ConfigLoader($this->configFilePath); $this->initialize($configLoader->all()); } /** * WURFL XML Schema * * @var string */ const WURFL_CONF_SCHEMA = "<?xml version='1.0' encoding='utf-8' ?> <element name='wurfl-config' xmlns='http://relaxng.org/ns/structure/1.0'> <element name='wurfl'> <element name='main-file'><text/></element> <element name='patches'> <zeroOrMore> <element name='patch'><text/></element> </zeroOrMore> </element> </element> <optional> <element name='allow-reload'><text/></element> </optional> <optional> <element name='match-mode'><text/></element> </optional> <optional> <element name='logDir'><text/></element> </optional> <element name='persistence'> <element name='provider'><text/></element> <optional> <element name='params'><text/></element> </optional> </element> <element name='cache'> <element name='provider'><text/></element> <optional> <element name='params'><text/></element> </optional> </element> </element>"; }
mimmi20/Wurfl
src/Configuration/FileConfig.php
PHP
agpl-3.0
2,589
// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_EXCEPTIONS_HPP_ #define RDB_PROTOCOL_EXCEPTIONS_HPP_ #include <string> #include "utils.hpp" #include "rdb_protocol/bt.hpp" #include "rpc/serialize_macros.hpp" namespace query_language { /* Thrown if the client sends a malformed or nonsensical query (e.g. a protocol buffer that doesn't match our schema or STOP for an unknown token). */ class broken_client_exc_t : public std::exception { public: explicit broken_client_exc_t(const std::string &_what) : message(_what) { } ~broken_client_exc_t() throw () { } const char *what() const throw () { return message.c_str(); } std::string message; }; /* `bad_query_exc_t` is thrown if the user writes a query that accesses undefined variables or that has mismatched types. The difference between this and `broken_client_exc_t` is that `broken_client_exc_t` is the client's fault and `bad_query_exc_t` is the client's user's fault. */ class bad_query_exc_t : public std::exception { public: bad_query_exc_t(const std::string &s, const backtrace_t &bt) : message(s), backtrace(bt) { } ~bad_query_exc_t() throw () { } const char *what() const throw () { return message.c_str(); } std::string message; backtrace_t backtrace; }; class runtime_exc_t { public: runtime_exc_t() { } runtime_exc_t(const std::string &_what, const backtrace_t &bt) : message(_what), backtrace(bt) { } std::string what() const throw() { return message; } std::string as_str() const throw() { return strprintf("%s\nBacktrace:\n%s", message.c_str(), backtrace.print().c_str()); } std::string message; backtrace_t backtrace; RDB_MAKE_ME_SERIALIZABLE_2(message, backtrace); }; }// namespace query_language #endif /* RDB_PROTOCOL_EXCEPTIONS_HPP_ */
AtnNn/rethinkdb
src/rdb_protocol/exceptions.hpp
C++
agpl-3.0
1,921
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.security.authentication.password; import org.silverpeas.core.security.authentication.password.encryption.UnixSHA512Encryption; import org.silverpeas.core.util.ServiceProvider; import java.util.Set; /** * Factory of password encryption objects implementing a given algorithm. It wraps the concrete * implementation of the <code>PasswordEncryption</code> interface used for encrypting a password * according to a chosen algorithm. * <p> * This factory provides all of the available password encryption supported by Silverpeas, * nevertheless it returns only the main encryption used by default in Silverpeas (the one that is * considered as the more robust and secure) with the <code>getDefaultPasswordEncryption()</code> * method. Getting others encryption can be done in order to work with passwords encrypted with * old (and then deprecated) algorithms with the <code>getPasswordEncryption(digest)</code> * method. * @author mmoquillon */ public class PasswordEncryptionProvider { /** * Gets the password encryption that is used by default in Silverpeas to encrypt the user * passwords and to check them. * @return the current default password encryption. */ public static PasswordEncryption getDefaultPasswordEncryption() { return ServiceProvider.getService(UnixSHA512Encryption.class); } /** * Gets the encryption that has computed the specified digest. * <p> * As digests in password encryption are usually made up of an encryption algorithm identifier, * the factory can then find the algorithm that matches the specified digest. If the digest * doesn't contain any algorithm identifier, then the UnixDES is returned (yet it is the only one * supported by Silverpeas that doesn't generate an algorithm identifier in the digest). In the * case the identifier in the digest isn't known, then a exception is thrown. * @param digest the digest from which the password encryption has be found. * @return the password encryption that has computed the specified digest. * @throws IllegalArgumentException if the digest was not computed by any of the password * encryption supported in Silverpeas. */ public static PasswordEncryption getPasswordEncryption(String digest) throws IllegalArgumentException { Set<PasswordEncryption> availableEncrypts = ServiceProvider.getAllServices(PasswordEncryption.class); PasswordEncryption encryption = availableEncrypts.stream() .filter(encrypt -> encrypt.doUnderstandDigest(digest)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Digest '" + digest + "' not understand by any of the available encryption in Silverpeas")); return encryption; } private PasswordEncryptionProvider() { } }
SilverDav/Silverpeas-Core
core-library/src/main/java/org/silverpeas/core/security/authentication/password/PasswordEncryptionProvider.java
Java
agpl-3.0
3,947
__author__ = 'c.brett'
Spycho/aimmo
aimmo-game/simulation/test/__init__.py
Python
agpl-3.0
23
import Ember from 'ember'; import _validate from 'ember-simple-validate/utils/validate'; import Validator from 'ember-simple-validate/lib/validator'; var get = Ember.get; var set = Ember.set; var validValidator = function(validator) { return validator instanceof Validator; }; export default Ember.Mixin.create({ init: function() { this._super(); set(this, 'isValid', undefined); }, validate: function() { set(this, 'validationErrors', {}); if(!this.canValidate()) { set(this, 'isValid', true); } else { var self = this; var validators = get(this, 'validators'); set(this, 'isValid', _validate(this, validators)); Ember.keys(validators).forEach(function(key) { Ember.makeArray(validators[key]).forEach(function(validator) { self.addErrors(key, get(validator, 'errors')); }); }); } return this.get('isValid'); }, canValidate: function() { var validators = get(this, 'validators') || {}; var canValidate = true; var keys = Ember.keys(validators); if(keys && keys.length) { keys.forEach(function(key) { var validatorList = Ember.makeArray(validators[key]); validatorList.forEach(function(validator) { if(!validValidator(validator)) { canValidate = false; return false; } }); }); } else { canValidate = false; } return canValidate; }, addErrors: function(key, errors) { var self = this; Ember.makeArray(errors).forEach(function(error) { self.addError(key, error); }); }, addError: function(key, error) { var self = this; var keyParts = key.split('.'); var path = 'validationErrors'; keyParts.forEach(function(key, i) { path += '.' + key; if(!get(self, path)) { var blank = i === keyParts.length - 1 ? Ember.A() : {}; set(self, path, blank); } }); get(this, 'validationErrors.' + key).pushObject(error); } });
ChinookBook/ember-simple-validate
addon/mixins/simple-validation-mixin.js
JavaScript
agpl-3.0
2,032
# -*- coding: utf-8 -*- # setup.py # Copyright (C) 2013 LEAP # # 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/>. """ setup file for leap.mx """ import os from setuptools import setup, find_packages import versioneer versioneer.versionfile_source = 'src/leap/mx/_version.py' versioneer.versionfile_build = 'leap/mx/_version.py' versioneer.tag_prefix = '' # tags are like 1.2.0 versioneer.parentdir_prefix = 'leap.mx-' from pkg.utils.reqs import parse_requirements trove_classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: No Input/Output (Daemon)', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3' ' or later (AGPLv3+)', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Communications :: Email', 'Topic :: Security :: Cryptography', ] if os.environ.get("VIRTUAL_ENV", None): data_files = None else: # XXX use a script entrypoint for mx instead, it will # be automatically # placed by distutils, using whatever interpreter is # available. data_files = [("/usr/local/bin/", ["pkg/mx.tac"]), ("/etc/init.d/", ["pkg/leap_mx"])] setup( name='leap.mx', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), url="http://github.com/leapcode/leap_mx", license='AGPLv3+', author='The LEAP Encryption Access Project', author_email='info@leap.se', description=("An asynchronous, transparently-encrypting remailer " "for the LEAP platform"), long_description=( "An asynchronous, transparently-encrypting remailer " "using BigCouch/CouchDB and PGP/GnuPG, written in Twisted Python." ), namespace_packages=["leap"], package_dir={'': 'src'}, packages=find_packages('src'), #test_suite='leap.mx.tests', install_requires=parse_requirements(), classifiers=trove_classifiers, data_files=data_files )
kalikaneko/leap_mx
setup.py
Python
agpl-3.0
2,678
module FeatureFlags # TODO: remove unused feature flags after like December 2019 AVAILABLE_FRONTEND_FEATURES = ['subscriptions', 'assessments', 'custom_sidebar', 'canvas_render', 'snapshots', 'enable_all_buttons', 'video_recording', 'goals', 'app_connections', 'translation', 'geo_sidebar', 'modeling', 'edit_before_copying', 'core_reports', 'lessonpix', 'audio_recordings', 'fast_render', 'badge_progress', 'board_levels', 'premium_symbols', 'find_multiple_buttons', 'new_speak_menu', 'native_keyboard', 'inflections_overlay', 'app_store_purchases', 'emergency_boards', 'evaluations', 'swipe_pages', 'app_store_monthly_purchases', 'ios_head_tracking', 'vertical_ios_head_tracking', 'auto_inflections', 'remote_modeling', 'focus_word_highlighting', 'profiles', 'skin_tones'] ENABLED_FRONTEND_FEATURES = ['subscriptions', 'assessments', 'custom_sidebar', 'snapshots', 'video_recording', 'goals', 'modeling', 'geo_sidebar', 'edit_before_copying', 'core_reports', 'lessonpix', 'translation', 'fast_render', 'audio_recordings', 'app_connections', 'enable_all_buttons', 'badge_progress', 'premium_symbols', 'board_levels', 'native_keyboard', 'app_store_purchases', 'find_multiple_buttons', 'new_speak_menu', 'swipe_pages', 'inflections_overlay', 'ios_head_tracking', 'emergency_boards', 'evaluations', 'vertical_ios_head_tracking', 'remote_modeling', 'auto_inflections', 'focus_word_highlighting'] DISABLED_CANARY_FEATURES = [] FEATURE_DATES = { 'word_suggestion_images' => 'Jan 21, 2017', 'hidden_buttons' => 'Feb 2, 2017', 'browser_no_autosync' => 'Feb 22, 2017', 'folder_icons' => 'Mar 7, 2017', 'symbol_background' => 'May 10, 2017', 'new_index' => 'Feb 17, 2018', 'click_buttons' => 'May 1, 2019', 'token_refresh' => 'July 4, 2019', 'battery_sounds' => 'February 25, 2020', 'auto_capitalize' => 'May 1, 2021', 'utterance_interruptions' => 'May 15, 2021', 'utterance_core_access' => 'May 1, 2021', 'recent_cleared_phrases' => 'Sep 1, 2021', 'skin_tones' => 'Feb 14, 2022' } def self.frontend_flags_for(user) flags = {} AVAILABLE_FRONTEND_FEATURES.each do |feature| if ENABLED_FRONTEND_FEATURES.include?(feature) flags[feature] = true elsif user && user.settings && user.settings['feature_flags'] && user.settings['feature_flags'][feature] flags[feature] = true elsif user && user.settings && user.settings['feature_flags'] && user.settings['feature_flags']['canary'] && !DISABLED_CANARY_FEATURES.include?(feature) flags[feature] = true end end flags end def self.user_created_after?(user, feature) return false unless FEATURE_DATES[feature] date = Date.parse(FEATURE_DATES[feature]) rescue Date.today created = (user.created_at || Time.now).to_date return !!(created >= date) end def self.feature_enabled_for?(feature, user) flags = frontend_flags_for(user) !!flags[feature] end end
CoughDrop/coughdrop
lib/feature_flags.rb
Ruby
agpl-3.0
3,182
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * 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 Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $dictionary['Administration'] = array('table' => 'config_eurivex', 'comment' => 'System table containing system-wide definitions' ,'fields' => array ( 'category' => array ( 'name' => 'category', 'vname' => 'LBL_LIST_SYMBOL', 'type' => 'varchar', 'len' => '32', 'comment' => 'Settings are grouped under this category; arbitraily defined based on requirements' ), 'name' => array ( 'name' => 'name', 'vname' => 'LBL_LIST_NAME', 'type' => 'varchar', 'len' => '32', 'comment' => 'The name given to the setting' ), 'value' => array ( 'name' => 'value', 'vname' => 'LBL_LIST_RATE', 'type' => 'text', 'comment' => 'The value given to the setting' ), ), 'indices'=>array( array('name'=>'idx_config_cat', 'type'=>'index', 'fields'=>array('category')),) ); $dictionary['UpgradeHistory'] = array( 'table' => 'upgrade_history', 'comment' => 'Tracks Sugar upgrades made over time; used by Upgrade Wizard and Module Loader', 'fields' => array ( 'id' => array ( 'name' => 'id', 'type' => 'id', 'required' => true, 'reportable' => false, 'comment' => 'Unique identifier' ), 'filename' => array ( 'name' => 'filename', 'type' => 'varchar', 'len' => '255', 'comment' => 'Cached filename containing the upgrade scripts and content' ), 'md5sum' => array ( 'name' => 'md5sum', 'type' => 'varchar', 'len' => '32', 'comment' => 'The MD5 checksum of the upgrade file' ), 'type' => array ( 'name' => 'type', 'type' => 'varchar', 'len' => '30', 'comment' => 'The upgrade type (module, patch, theme, etc)' ), 'status' => array ( 'name' => 'status', 'type' => 'varchar', 'len' => '50', 'comment' => 'The status of the upgrade (ex: "installed")', ), 'version' => array ( 'name' => 'version', 'type' => 'varchar', 'len' => '64', 'comment' => 'Version as contained in manifest file' ), 'name' => array ( 'name' => 'name', 'type' => 'varchar', 'len' => '255', ), 'description' => array ( 'name' => 'description', 'type' => 'text', ), 'id_name' => array ( 'name' => 'id_name', 'type' => 'varchar', 'len' => '255', 'comment' => 'The unique id of the module' ), 'manifest' => array ( 'name' => 'manifest', 'type' => 'longtext', 'comment' => 'A serialized copy of the manifest file.' ), 'date_entered' => array ( 'name' => 'date_entered', 'type' => 'datetime', 'required'=>true, 'comment' => 'Date of upgrade or module load' ), 'enabled' => array( 'name' => 'enabled', 'type' => 'bool', 'len' => '1', 'default' => '1', ), ), 'indices' => array( array('name'=>'upgrade_history_pk', 'type'=>'primary', 'fields'=>array('id')), array('name'=>'upgrade_history_md5_uk', 'type'=>'unique', 'fields'=>array('md5sum')), ), ); ?>
hirakc/eur_crm
modules/Administration/vardefs.php
PHP
agpl-3.0
5,819
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. return [ 'discussion-votes' => [ 'update' => [ 'error' => 'נכשל בעדכון הצבעה', ], ], 'discussions' => [ 'allow_kudosu' => 'אפשר kudosu', 'beatmap_information' => 'דף מפות', 'delete' => 'מחק', 'deleted' => 'נמחק על ידי :editor :delete_time.', 'deny_kudosu' => 'דחה kudosu', 'edit' => 'ערוך', 'edited' => 'נערך לאחרונה על ידי :editor :update_time.', 'guest' => '', 'kudosu_denied' => 'נדחה מקבלת kudosu.', 'message_placeholder_deleted_beatmap' => 'רמת הקושי הזאת נמחקה לכן לא ניתן לדון בה.', 'message_placeholder_locked' => 'דיון למפה זו בוטל.', 'message_placeholder_silenced' => "לא ניתן לדון בזמן שמושתק.", 'message_type_select' => 'בחר סוג תגובה', 'reply_notice' => 'הקש על Enter כדי להגיב.', 'reply_placeholder' => 'הקלד את תגובתך כאן', 'require-login' => 'אנא התחבר על מנת לפרסם הודעה או להגיב', 'resolved' => 'נפתר', 'restore' => 'שחזר', 'show_deleted' => 'הצג שנמחק', 'title' => 'דיונים', 'collapse' => [ 'all-collapse' => 'סגור הכל', 'all-expand' => 'הרחב הכל', ], 'empty' => [ 'empty' => 'עדיין אין דיונים!', 'hidden' => 'אין דיון שמתאים לסינון שנבחר.', ], 'lock' => [ 'button' => [ 'lock' => 'נעל דיון', 'unlock' => 'פתח דיון', ], 'prompt' => [ 'lock' => 'סיבת הנעילה', 'unlock' => 'האם אתה בטוח שברצונך לפתוח?', ], ], 'message_hint' => [ 'in_general' => 'פוסט זה יעבור לדיוני beatmapset כללים. כדי לעשות mod ל- beatmap זה, התחל הודעה עם חותמת זמן (למשל 00:12:345).', 'in_timeline' => 'כדי לבצע mod לחותמות זמן מרובות, פרסם הודעה מספר פעמים (הודעה אחת לחותמת זמן).', ], 'message_placeholder' => [ 'general' => 'הקלד כאן כדי לפרסם הודעה ל- כללי (:version)', 'generalAll' => 'הקלד כאן כדי לפרסם הודעה ל- כללי (כל רמות הקושי)', 'review' => 'הקלד כאן כדי לפרסם ביקורת', 'timeline' => 'הקלד כאן כדי לפרסם הודעה ל- "ציר זמן" (:version)', ], 'message_type' => [ 'disqualify' => 'פסול', 'hype' => 'הייפ!', 'mapper_note' => 'הערה', 'nomination_reset' => 'איפוס מועמדות', 'praise' => 'שבח', 'problem' => 'בעיה', 'review' => 'ביקורת', 'suggestion' => 'הצעה', ], 'mode' => [ 'events' => 'היסטוריה', 'general' => 'כללי :scope', 'reviews' => 'ביקורות', 'timeline' => 'ציר זמן', 'scopes' => [ 'general' => 'רמת הקושי הזאת', 'generalAll' => 'כל רמות הקושי', ], ], 'new' => [ 'pin' => 'נעץ', 'timestamp' => 'חותמת זמן', 'timestamp_missing' => 'העתק במצב עריכה והדבק בהודעה שלך כדי להוסיף חותמת זמן!', 'title' => 'דיון חדש', 'unpin' => 'בטל נעיצה', ], 'review' => [ 'new' => 'ביקורת חדשה', 'embed' => [ 'delete' => 'מחק', 'missing' => '[ביקורת נמחקה]', 'unlink' => 'בטל קישור', 'unsaved' => 'לא שמור', 'timestamp' => [ 'all-diff' => 'פוסים ב "כל דרגות הקושי" לא יכול להיות תמידיים.', 'diff' => 'אם :type יתחיל בזמן מסוים, הוא יהיה נראה מתחת ציר הזמן.', ], ], 'insert-block' => [ 'paragraph' => 'הוסף פסקה', 'praise' => 'הוסף שיבוח', 'problem' => 'הוסף תקלה', 'suggestion' => 'הוסף הצעה', ], ], 'show' => [ 'title' => ':title ממופה על ידי :mapper', ], 'sort' => [ 'created_at' => 'זמן יצירה', 'timeline' => 'ציר זמן', 'updated_at' => 'עידכון אחרון', ], 'stats' => [ 'deleted' => 'נמחק', 'mapper_notes' => 'הערות', 'mine' => 'מוקש', 'pending' => 'ממתין', 'praises' => 'שבחים', 'resolved' => 'נפתר', 'total' => 'הכל', ], 'status-messages' => [ 'approved' => 'Beatmap זו אושרה ב :date!', 'graveyard' => "Beatmap זו לא עודכנה מאז :date וקרוב לוודאי שננטשה על ידי היוצר...", 'loved' => 'Beatmap זו הוספה ל "אהובות" ב- :date!', 'ranked' => 'Beatmap זו דורגה ב :date!', 'wip' => 'הערה: Beatmap זו מסומנת כ "עבודה בתהליך" על ידי היוצר.', ], 'votes' => [ 'none' => [ 'down' => 'עדיין אין מצביעים', 'up' => 'אין הצבעטת עדיין', ], 'latest' => [ 'down' => 'ההצבעות האחרונות', 'up' => 'ההצבעות האחרונות', ], ], ], 'hype' => [ 'button' => 'הייפ Beatmap!', 'button_done' => 'כבר Hyped!', 'confirm' => "אתה בטוח? זה ישתמש באחד מ- :n ההייפים הנותרים שלך ולא ניתן לבטל זאת.", 'explanation' => 'תן הייפ ל beatmap הזו כדי להפוך אותה לגלויה יותר להיות מועמדת ומדורגת!', 'explanation_guest' => 'התחבר ותן הייף ל beatmap זו כדי להפוך אותה לגלויה יותר להיות מועמדת ומדורגת!', 'new_time' => "תקבל הייפ אחר :new_time.", 'remaining' => 'יש לך :remaining הייפים נותרים.', 'required_text' => 'הייפ: :current/:required', 'section_title' => 'רכבת הייפ', 'title' => 'הייפ', ], 'feedback' => [ 'button' => 'השאר משוב', ], 'nominations' => [ 'delete' => 'מחק', 'delete_own_confirm' => 'אתה בטוח? Beatmap זו תימחק ואתה תועבר חזרה לפרופיל שלך.', 'delete_other_confirm' => 'אתה בטוח? Beatmap זו תימחק ואתה תועבר חזרה לפרופיל של המשתמש.', 'disqualification_prompt' => 'סיבת הפסילה?', 'disqualified_at' => 'נפסלה :time_ago (:reason).', 'disqualified_no_reason' => 'לא פורטה הסיבה', 'disqualify' => 'פסול', 'incorrect_state' => 'שגיאה בעת ביצוע פעולה זו, נסה לרענן את הדף.', 'love' => 'אוהב', 'love_choose' => '', 'love_confirm' => 'לאהוב מפה זו?', 'nominate' => 'למנות', 'nominate_confirm' => 'למנות מפה זו?', 'nominated_by' => 'מונתה על ידי :users', 'not_enough_hype' => "אין כאן מספיק התעניינות.", 'remove_from_loved' => 'הורד סטטוס ה-Loved', 'remove_from_loved_prompt' => 'סיבה הורדת סטטוס ה-Loved:', 'required_text' => 'מינויים: :current/:required', 'reset_message_deleted' => 'נמחק', 'title' => 'סטטוס המינוי', 'unresolved_issues' => 'ישנן עדיין בעיות שלא נפתרו שחייבות טיפול קודם.', 'rank_estimate' => [ '_' => 'מפה זאת תקבל סטטוס Ranked ב:date במידה ולא ימצאו שגיעות. המפה נמצא ב#:position ב:queue.', 'queue' => 'נבדקת לקבלת Ranking', 'soon' => 'בקרוב', ], 'reset_at' => [ 'nomination_reset' => 'תהליך המינוי התאפס :time_ago על ידי :user עם בעיה חדשה :discussion (:message).', 'disqualify' => 'נפסלה :time_ago על ידי :user עם בעיה חדשה :discussion (:message).', ], 'reset_confirm' => [ 'nomination_reset' => 'אתה בטוח? פרסום בעיה חדשה יאפס את תהליך המינוי.', 'disqualify' => 'אתה בטוח? זה יסיר את המפה מ- "מוקדמות" ויאפס את תהליך המינוי.', ], ], 'listing' => [ 'search' => [ 'prompt' => 'הקלד מילות מפתח...', 'login_required' => 'התחבר כדי לחפש.', 'options' => 'אפשרויות חיפוש נוספות', 'supporter_filter' => 'סינון לפי :filters דורש תג osu!supporter פעיל', 'not-found' => 'אין תוצאות', 'not-found-quote' => '... לא, לא נמצא כלום.', 'filters' => [ 'extra' => 'נוסף', 'general' => 'כללי', 'genre' => 'ז\'אנר', 'language' => 'שפה', 'mode' => 'מצב', 'nsfw' => '', 'played' => 'שוחקה', 'rank' => 'דרגה הושגה', 'status' => 'קטגוריות', ], 'sorting' => [ 'title' => 'כותרת', 'artist' => 'אמן', 'difficulty' => 'דרגת קושי', 'favourites' => 'מועדפות', 'updated' => 'עודכנה', 'ranked' => 'מדורגת', 'rating' => 'דירוג', 'plays' => 'שיחוקים', 'relevance' => 'רלוונטיות', 'nominations' => 'מינויים', ], 'supporter_filter_quote' => [ '_' => 'סינון לפי :filters דורש :link פעיל', 'link_text' => 'תג osu!supporter', ], ], ], 'general' => [ 'converts' => 'כלול מפות מומרות', 'featured_artists' => '', 'follows' => '', 'recommended' => 'דרגת קושי מומלצת', ], 'mode' => [ 'all' => 'הכל', 'any' => 'הכל', 'osu' => '', 'taiko' => '', 'fruits' => '', 'mania' => '', ], 'status' => [ 'any' => 'הכל', 'approved' => 'מאושרת', 'favourites' => 'מועדפים', 'graveyard' => 'קבורה', 'leaderboard' => 'יש לוח מובילים', 'loved' => 'אהובה', 'mine' => 'המפות שלי', 'pending' => 'בתהליך * WIP', 'qualified' => 'מוסמכת', 'ranked' => 'מדורג', ], 'genre' => [ 'any' => 'הכל', 'unspecified' => 'לא מוגדר', 'video-game' => 'משחק וידאו', 'anime' => 'אנימה', 'rock' => 'רוק', 'pop' => 'פופ', 'other' => 'אחר', 'novelty' => 'Novelty', 'hip-hop' => 'היפ הופ', 'electronic' => 'אלקטרוני', 'metal' => 'מטאל', 'classical' => 'קלאסי', 'folk' => 'פולק', 'jazz' => 'ג\'אז', ], 'mods' => [ '4K' => '', '5K' => '', '6K' => '', '7K' => '', '8K' => '', '9K' => '', 'AP' => '', 'DT' => '', 'EZ' => '', 'FI' => '', 'FL' => '', 'HD' => '', 'HR' => '', 'HT' => '', 'MR' => '', 'NC' => '', 'NF' => '', 'NM' => '', 'PF' => '', 'RX' => '', 'SD' => '', 'SO' => '', 'TD' => '', 'V2' => '', ], 'language' => [ 'any' => '', 'english' => 'אנגלית', 'chinese' => 'סינית', 'french' => 'צרפתית', 'german' => 'גרמנית', 'italian' => 'איטלקית', 'japanese' => 'יפנית', 'korean' => 'קוריאנית', 'spanish' => 'ספרדית', 'swedish' => 'שוודית', 'russian' => 'רוסית', 'polish' => 'פולנית', 'instrumental' => 'אינסטרומנטלי', 'other' => 'אחר', 'unspecified' => 'לא מוגדר', ], 'nsfw' => [ 'exclude' => '', 'include' => '', ], 'played' => [ 'any' => 'הכל', 'played' => 'שוחקה', 'unplayed' => 'לא שוחקה', ], 'extra' => [ 'video' => 'יש וידאו', 'storyboard' => 'יש Storyboard', ], 'rank' => [ 'any' => 'הכל', 'XH' => 'SS כסוף', 'X' => '', 'SH' => 'S כסוף', 'S' => '', 'A' => '', 'B' => '', 'C' => '', 'D' => '', ], 'panel' => [ 'playcount' => 'מספר משחקים: :count', 'favourites' => 'מועדפות: :count', ], 'variant' => [ 'mania' => [ '4k' => '4K', '7k' => '7K', 'all' => 'הכל', ], ], ];
LiquidPL/osu-web
resources/lang/he-IL/beatmaps.php
PHP
agpl-3.0
14,321
import _ from 'lodash'; import React from 'react'; import {PreviewModal} from '../previewModal'; SendItem.$inject = ['$q', 'api', 'desks', 'notify', 'authoringWorkspace', 'superdeskFlags', '$location', 'macros', '$rootScope', 'deployConfig', 'authoring', 'send', 'editorResolver', 'confirm', 'archiveService', 'preferencesService', 'multi', 'datetimeHelper', 'config', 'privileges', 'storage', 'modal', 'gettext', 'urls']; export function SendItem($q, api, desks, notify, authoringWorkspace, superdeskFlags, $location, macros, $rootScope, deployConfig, authoring, send, editorResolver, confirm, archiveService, preferencesService, multi, datetimeHelper, config, privileges, storage, modal, gettext, urls) { return { scope: { item: '=', view: '=', orig: '=', _beforeSend: '&beforeSend', _editable: '=editable', _publish: '&publish', _action: '=action', mode: '@', }, controller: function() { this.userActions = { send_to: 'send_to', publish: 'publish', duplicate_to: 'duplicate_to', externalsource_to: 'externalsource_to', }; }, controllerAs: 'vm', templateUrl: 'scripts/apps/authoring/views/send-item.html', link: function sendItemLink(scope, elem, attrs, ctrl) { scope.mode = scope.mode || 'authoring'; scope.desks = null; scope.stages = null; scope.macros = null; scope.userDesks = null; scope.allDesks = null; scope.task = null; scope.selectedDesk = null; scope.selectedStage = null; scope.selectedMacro = null; scope.beforeSend = scope._beforeSend || $q.when; scope.destination_last = {send_to: null, publish: null, duplicate_to: null}; scope.origItem = angular.extend({}, scope.item); scope.subscribersWithPreviewConfigured = []; // key for the storing last desk/stage in the user preferences for send action. var PREFERENCE_KEY = 'destination:active'; // key for the storing last user action (send to/publish) in the storage. var USER_ACTION_KEY = 'send_to_user_action'; scope.$watch('item', activateItem); scope.$watch(send.getConfig, activateConfig); scope.publish = function() { scope.loading = true; var result = scope._publish(); return $q .resolve(result) .then(null, (e) => $q.reject(false)) .finally(() => { scope.loading = false; }); }; function activateConfig(config, oldConfig) { if (scope.mode !== 'authoring' && config !== oldConfig) { scope.isActive = !!config; scope.item = scope.isActive ? {} : null; scope.multiItems = multi.count ? multi.getItems() : null; scope.config = config; activate(); } } function activateItem(item) { if (scope.mode === 'monitoring') { superdeskFlags.flags.fetching = !!item; } scope.isActive = !!item; activate(); } function activate() { if (scope.isActive) { api.query('subscribers') .then((res) => { const allSubscribers = res['_items']; scope.subscribersWithPreviewConfigured = allSubscribers .map( (subscriber) => { subscriber.destinations = subscriber.destinations.filter( (destination) => typeof destination.preview_endpoint_url === 'string' && destination.preview_endpoint_url.length > 0 ); return subscriber; } ) .filter((subscriber) => subscriber.destinations.length > 0); }); desks .initialize() .then(fetchDesks) .then(initialize) .then(setDesksAndStages); } } scope.preview = function() { if (scope.$parent.save_enabled() === true) { modal.alert({ headerText: gettext('Preview'), bodyText: gettext( 'In order to preview the item, save the changes first.' ), }); } else { modal.createCustomModal() .then(({openModal, closeModal}) => { openModal( <PreviewModal subscribersWithPreviewConfigured={scope.subscribersWithPreviewConfigured} documentId={scope.item._id} urls={urls} closeModal={closeModal} gettext={gettext} /> ); }); } }; scope.close = function() { if (scope.mode === 'monitoring') { superdeskFlags.flags.fetching = false; } if (scope.$parent.views) { scope.$parent.views.send = false; } else if (scope.item) { scope.item = null; } $location.search('fetch', null); if (scope.config) { scope.config.reject(); } }; scope.selectDesk = function(desk) { scope.selectedDesk = _.cloneDeep(desk); scope.selectedStage = null; fetchStages(); fetchMacros(); }; scope.selectStage = function(stage) { scope.selectedStage = stage; }; scope.selectMacro = function(macro) { if (scope.selectedMacro === macro) { scope.selectedMacro = null; } else { scope.selectedMacro = macro; } }; scope.send = function(open) { updateLastDestination(); return runSend(open); }; scope.$on('item:nextStage', (_e, data) => { if (scope.item && scope.item._id === data.itemId) { var oldStage = scope.selectedStage; scope.selectedStage = data.stage; scope.send().then((sent) => { if (!sent) { scope.selectedStage = oldStage; } }); } }); // events on which panel should close var closePanelEvents = ['item:spike', 'broadcast:preview']; angular.forEach(closePanelEvents, (event) => { scope.$on(event, shouldClosePanel); }); /** * @description Closes the opened 'duplicate/send To' panel if the same item getting * spiked or any item is opening for authoring. * @param {Object} event * @param {Object} data - contains the item(=itemId) that was spiked or {item: null} when * any item opened for authoring (utilising, 'broadcast:preview' with {item: null}) */ function shouldClosePanel(event, data) { if ( (scope.config != null && data != null && _.includes(scope.config.itemIds, data.item)) || (data == null || data.item == null) ) { scope.close(); } } /* * Returns true if Destination field and Send button needs to be displayed, false otherwise. * @returns {Boolean} */ scope.showSendButtonAndDestination = function() { if (scope.itemActions) { var preCondition = scope.mode === 'ingest' || scope.mode === 'personal' || scope.mode === 'monitoring' || scope.mode === 'authoring' && scope.isSendEnabled() && scope.itemActions.send || scope.mode === 'spike'; if (scope.currentUserAction === ctrl.userActions.publish) { return preCondition && scope.showSendAndPublish(); } return preCondition; } }; /* * Returns true if Send and Send and Continue button needs to be disabled, false otherwise. * @returns {Boolean} */ scope.disableSendButton = function() { return !scope.selectedDesk || scope.mode !== 'ingest' && scope.selectedStage && scope.mode !== 'spike' && (_.get(scope, 'item.task.stage') === scope.selectedStage._id || _.includes(_.map(scope.multiItems, 'task.stage'), scope.selectedStage._id)); }; /* * Returns true if user is not a member of selected desk, false otherwise. * @returns {Boolean} */ scope.disableFetchAndOpenButton = function() { if (scope.selectedDesk) { var _isNonMember = _.isEmpty(_.find(desks.userDesks, {_id: scope.selectedDesk._id})); return _isNonMember; } }; /** * Returns true if Publish Schedule needs to be displayed, false otherwise. */ scope.showPublishSchedule = function() { return scope.item && archiveService.getType(scope.item) !== 'ingest' && scope.item.type !== 'composite' && !scope.item.embargo_date && !scope.item.embargo_time && ['published', 'killed', 'corrected', 'recalled'].indexOf(scope.item.state) === -1 && canPublishOnDesk(); }; /** * Returns true if timezone needs to be displayed, false otherwise. */ scope.showTimezone = function() { return (scope.item.publish_schedule || scope.item.embargo) && (scope.showPublishSchedule() || scope.showEmbargo()); }; /** * Returns true if Embargo needs to be displayed, false otherwise. */ scope.showEmbargo = function() { // If user doesn't have embargo privilege then don't display embargo fields if (!privileges.privileges.embargo) { return false; } if (config.ui && config.ui.publishEmbargo === false) { return false; } var prePublishCondition = scope.item && archiveService.getType(scope.item) !== 'ingest' && scope.item.type !== 'composite' && !scope.item.publish_schedule_date && !scope.item.publish_schedule_time; if (prePublishCondition && authoring.isPublished(scope.item)) { if (['published', 'corrected'].indexOf(scope.item.state) >= 0) { return scope.origItem.embargo; } // for published states other than 'published', 'corrected' return false; } return prePublishCondition; }; /** * Returns true if Embargo needs to be displayed, false otherwise. */ scope.isEmbargoEditable = function() { var publishedCondition = authoring.isPublished(scope.item) && scope.item.schedule_settings && scope.item.schedule_settings.utc_embargo && datetimeHelper.greaterThanUTC(scope.item.schedule_settings.utc_embargo); return scope.item && scope.item._editable && (!authoring.isPublished(scope.item) || publishedCondition); }; /** * Send the content to different desk/stage * @param {Boolean} open - True to open the item. * @return {Object} promise */ function runSend(open) { scope.loading = true; scope.item.sendTo = true; var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; if (scope.mode === 'authoring') { return sendAuthoring(deskId, stageId, scope.selectedMacro); } else if (scope.mode === 'archive') { return sendContent(deskId, stageId, scope.selectedMacro, open); } else if (scope.config) { scope.config.promise.finally(() => { scope.loading = false; }); return scope.config.resolve({ desk: deskId, stage: stageId, macro: scope.selectedMacro ? scope.selectedMacro.name : null, open: open, }); } else if (scope.mode === 'ingest') { return sendIngest(deskId, stageId, scope.selectedMacro, open); } } /** * Enable Disable the Send and Publish button. * Send And Publish is enabled using `superdesk.config.js`. */ scope.showSendAndPublish = () => !config.ui || angular.isUndefined(config.ui.sendAndPublish) || config.ui.sendAndPublish; /** * Check if the Send and Publish is allowed or not. * Following conditions are to met for Send and Publish action * - Item is not Published i.e. not state Published, Corrected, Killed or Scheduled * - Selected destination (desk/stage) should be different from item current location (desk/stage) * - Mode should be authoring * - Publish Action is allowed on that item. * @return {Boolean} */ scope.canSendAndPublish = function() { if (scope.mode !== 'authoring' || !scope.item) { return false; } // Selected destination desk should be different from item current location desk var isDestinationChanged = scope.selectedDesk && scope.item.task.desk !== scope.selectedDesk._id; return scope.showSendAndPublish() && !authoring.isPublished(scope.item) && isDestinationChanged && scope.mode === 'authoring' && scope.itemActions.publish; }; /** * Returns true if 'send' button should be displayed. Otherwise, returns false. * @return {boolean} */ scope.isSendEnabled = () => scope.item && !authoring.isPublished(scope.item); /* * Send the current item to different desk or stage and publish the item from new location. */ scope.sendAndPublish = function() { return runSendAndPublish(); }; /* * Returns true if 'send' action is allowed, otherwise false * @returns {Boolean} */ scope.canSendItem = function() { var itemType = [], typesList; if (scope.multiItems) { angular.forEach(scope.multiItems, (item) => { itemType[item._type] = 1; }); typesList = Object.keys(itemType); itemType = typesList.length === 1 ? typesList[0] : null; } return scope.mode === 'authoring' || itemType === 'archive' || scope.mode === 'spike' || (scope.mode === 'monitoring' && _.get(scope, 'config.action') === scope.vm.userActions.send_to); }; /** * Check if it is allowed to publish on current desk * @returns {Boolean} */ function canPublishOnDesk() { return !(isAuthoringDesk() && config.features.noPublishOnAuthoringDesk); } /** * If the action is correct and kill then the publish privilege needs to be checked. */ scope.canPublishItem = function() { if (!scope.itemActions || !canPublishOnDesk()) { return false; } if (scope._action === 'edit') { return scope.item ? !scope.item.flags.marked_for_not_publication && scope.itemActions.publish : scope.itemActions.publish; } else if (scope._action === 'correct') { return privileges.privileges.publish && scope.itemActions.correct; } else if (scope._action === 'kill') { return privileges.privileges.publish && scope.itemActions.kill; } return false; }; /** * Set the User Action. */ scope.setUserAction = function(action) { if (scope.currentUserAction === action) { return; } scope.currentUserAction = action; storage.setItem(USER_ACTION_KEY, action); setDesksAndStages(); }; /** * Checks if a given item is valid to publish * * @param {Object} item story to be validated * @return {Object} promise */ const validatePublish = (item) => api.save('validate', {act: 'publish', type: item.type, validate: item}); /** * Sends and publishes the current item in scope * First checks if the item is dirty and pops up save dialog if needed * Then checks if the story is valid to publish before sending * Then sends the story to the destination * Then publishes it * * @param {Object} item story to be validated * @return {Object} promise */ const runSendAndPublish = () => { var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; // send releases lock, increment version. return scope.beforeSend({action: 'Send and Publish'}) .then(() => validatePublish(scope.item) .then((validationResult) => { if (_.get(validationResult, 'errors.length')) { for (var i = 0; i < validationResult.errors.length; i++) { notify.error('\'' + _.trim(validationResult.errors[i]) + '\''); } return $q.reject(); } return sendAuthoring(deskId, stageId, scope.selectedMacro, true) .then((item) => { scope.loading = true; // open the item for locking and publish return authoring.open(scope.item._id, false); }) .then((item) => { // update the original item to avoid 412 error. scope.orig._etag = scope.item._etag = item._etag; scope.orig._locked = scope.item._locked = item._locked; scope.orig.task = scope.item.task = item.task; // change the desk location. $rootScope.$broadcast('desk_stage:change'); // if locked then publish if (item._locked) { return scope.publish(); } return $q.reject(); }) .then((result) => { if (result) { authoringWorkspace.close(false); } }) .catch((error) => { notify.error(gettext('Failed to send and publish.')); }); }) .finally(() => { scope.loading = false; }) ); }; /** * Run the macro and returns to the modified item. * @param {Object} item * @param {String} macro * @return {Object} promise */ function runMacro(item, macro) { if (macro) { return macros.call(macro, item, true).then((res) => angular.extend(item, res)); } return $q.when(item); } /** * Send to different location from authoring. * @param {String} deskId - selected desk Id * @param {String} stageId - selected stage Id * @param {String} macro - macro to apply * @return {Object} promise */ function sendAuthoring(deskId, stageId, macro) { var msg; scope.loading = true; return runMacro(scope.item, macro) .then((item) => api.find('tasks', scope.item._id) .then((task) => { scope.task = task; msg = 'Send'; return scope.beforeSend({action: msg}); }) .then((result) => { if (result && result._etag) { scope.task._etag = result._etag; } return api.save('move', {}, {task: {desk: deskId, stage: stageId}}, scope.item); }) .then((value) => { notify.success(gettext('Item sent.')); if (scope.currentUserAction === ctrl.userActions.send_to) { // Remember last destination desk and stage for send_to. var lastDestination = scope.destination_last[scope.currentUserAction]; if (!lastDestination || (lastDestination.desk !== deskId || lastDestination.stage !== stageId)) { updateLastDestination(); } } authoringWorkspace.close(true); return true; }, (err) => { if (err) { if (angular.isDefined(err.data._message)) { notify.error(err.data._message); } else if (angular.isDefined(err.data._issues['validator exception'])) { notify.error(err.data._issues['validator exception']); } } })) .finally(() => { scope.loading = false; }); } /** * Update the preferences to store last destinations * @param {String} key */ function updateLastDestination() { var updates = {}; var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; updates[PREFERENCE_KEY] = {desk: deskId, stage: stageId}; preferencesService.update(updates, PREFERENCE_KEY); } /** * Send content to different desk and stage * @param {String} deskId * @param {String} stageId * @param {String} macro * @param {Boolean} open - If true open the item. */ function sendContent(deskId, stageId, macro, open) { var finalItem; scope.loading = true; return api.save('duplicate', {}, {desk: scope.item.task.desk}, scope.item) .then((item) => api.find('archive', item._id)) .then((item) => runMacro(item, macro)) .then((item) => { finalItem = item; return api.find('tasks', item._id); }) .then((_task) => { scope.task = _task; api.save('tasks', scope.task, { task: _.extend(scope.task.task, {desk: deskId, stage: stageId}), }); }) .then(() => { notify.success(gettext('Item sent.')); scope.close(); if (open) { $location.url('/authoring/' + finalItem._id); } else { $rootScope.$broadcast('item:fetch'); } }) .finally(() => { scope.loading = false; }); } /** * Fetch content from ingest to a different desk and stage * @param {String} deskId * @param {String} stageId * @param {String} macro * @param {Boolean} open - If true open the item. */ function sendIngest(deskId, stageId, macro, open) { scope.loading = true; return send.oneAs(scope.item, { desk: deskId, stage: stageId, macro: macro ? macro.name : macro, }).then((finalItem) => { notify.success(gettext('Item fetched.')); if (open) { authoringWorkspace.edit(finalItem); } else { $rootScope.$broadcast('item:fetch'); } }) .finally(() => { scope.loading = false; }); } /** * Fetch desk and last selected desk and stage for send_to and publish action * @return {Object} promise */ function fetchDesks() { return desks.initialize() .then(() => { // get all desks scope.allDesks = desks.desks._items; // get user desks return desks.fetchCurrentUserDesks(); }) .then((deskList) => { scope.userDesks = deskList; return preferencesService.get(PREFERENCE_KEY); }) .then((result) => { if (result) { scope.destination_last.send_to = { desk: result.desk, stage: result.stage, }; scope.destination_last.duplicate_to = { desk: result.desk, stage: result.stage, }; } }); } /** * Set the last selected desk based on the user action. * To be called after currentUserAction is set */ function setDesksAndStages() { if (!scope.currentUserAction) { return; } // set the desks for desk filter if (scope.currentUserAction === ctrl.userActions.publish) { scope.desks = scope.userDesks; } else { scope.desks = scope.allDesks; } if (scope.mode === 'ingest') { scope.selectDesk(desks.getCurrentDesk()); } else { // set the last selected desk or current desk var itemDesk = desks.getItemDesk(scope.item); var lastDestination = scope.destination_last[scope.currentUserAction]; if (itemDesk) { if (lastDestination && !_.isNil(lastDestination.desk)) { scope.selectDesk(desks.deskLookup[lastDestination.desk]); } else { scope.selectDesk(itemDesk); } } else if (lastDestination && !_.isNil(lastDestination.desk)) { scope.selectDesk(desks.deskLookup[lastDestination.desk]); } else { scope.selectDesk(desks.getCurrentDesk()); } } } /** * Set stages and last selected stage. */ function fetchStages() { if (!scope.selectedDesk) { return; } scope.stages = desks.deskStages[scope.selectedDesk._id]; var stage = null; if (scope.currentUserAction === ctrl.userActions.send_to || scope.currentUserAction === ctrl.userActions.duplicate_to) { var lastDestination = scope.destination_last[scope.currentUserAction]; if (lastDestination) { stage = _.find(scope.stages, {_id: lastDestination.stage}); } else if (scope.item.task && scope.item.task.stage) { stage = _.find(scope.stages, {_id: scope.item.task.stage}); } } if (!stage) { stage = _.find(scope.stages, {_id: scope.selectedDesk.incoming_stage}); } scope.selectedStage = stage; } /** * Fetch macros for the selected desk. */ function fetchMacros() { if (!scope.selectedDesk) { return; } macros.getByDesk(scope.selectedDesk.name) .then((_macros) => { scope.macros = _macros; }); } /** * Initialize Item Actios and User Actions. */ function initialize() { initializeItemActions(); initializeUserAction(); } /** * Initialize User Action */ function initializeUserAction() { // default user action scope.currentUserAction = storage.getItem(USER_ACTION_KEY) || ctrl.userActions.send_to; if (scope.orig || scope.item) { if (scope.config && scope.config.action === 'externalsourceTo') { scope.currentUserAction = ctrl.userActions.externalsource_to; } // if the last action is send to but item is published open publish tab. if (scope.config && scope.config.action === 'duplicateTo') { scope.currentUserAction = ctrl.userActions.duplicate_to; } if (scope.currentUserAction === ctrl.userActions.send_to && scope.canPublishItem() && !scope.isSendEnabled()) { scope.currentUserAction = ctrl.userActions.publish; } else if (scope.currentUserAction === ctrl.userActions.publish && !scope.canPublishItem() && scope.showSendButtonAndDestination()) { scope.currentUserAction = ctrl.userActions.send_to; } else if (scope.currentUserAction === ctrl.userActions.publish && isAuthoringDesk() && noPublishOnAuthoringDesk()) { scope.currentUserAction = ctrl.userActions.send_to; } } } /** * The itemActions defined in parent scope (Authoring Directive) is made accessible via this method. * scope.$parent isn't used as send-item directive is used in multiple places and has different * hierarchy. */ function initializeItemActions() { if (scope.orig || scope.item) { scope.itemActions = authoring.itemActions(scope.orig || scope.item); } } /** * Test if desk of current item is authoring type. * * @return {Boolean} */ function isAuthoringDesk() { if (!_.get(scope, 'item.task.desk')) { return false; } const desk = desks.getItemDesk(scope.item); return desk && desk.desk_type === 'authoring'; } /** * Test if noPublishOnAuthoringDesk config is active. * * @return {Boolean} */ function noPublishOnAuthoringDesk() { return config.features.noPublishOnAuthoringDesk; } // update actions on item save scope.$watch('orig._current_version', initializeItemActions); }, }; }
jerome-poisson/superdesk-client-core
scripts/apps/authoring/authoring/directives/SendItem.js
JavaScript
agpl-3.0
35,674
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl> * * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OCA\Files_Versions\Listener; use OCA\Files\Event\LoadSidebar; use OCA\Files_Versions\AppInfo\Application; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; use OCP\Util; class LoadSidebarListener implements IEventListener { public function handle(Event $event): void { if (!($event instanceof LoadSidebar)) { return; } // TODO: make sure to only include the sidebar script when // we properly split it between files list and sidebar Util::addScript(Application::APP_ID, 'files_versions'); } }
andreas-p/nextcloud-server
apps/files_versions/lib/Listener/LoadSidebarListener.php
PHP
agpl-3.0
1,562
/** The FlamingLayer Class **/ /** * @constructor * @augments Layer * @description The superclass for all flamingolayers * @param id The id of the layer * @param options The options to be given to the layer * @param flamingoObject The flamingo object of the layer * */ Ext.define("viewer.viewercontroller.flamingo.FlamingoLayer",{ enabledEvents: null, type: null, constructor :function (config){ if (config.id){ this.id = config.viewerController.mapComponent.makeFlamingoAcceptableId(config.id); config.id = this.id; } this.enabledEvents=new Object(); this.map = this.viewerController ? this.viewerController.mapComponent.getMap() : null; return this; }, /** * Get's the frameworklayer: the viewer specific layer. */ getFrameworkLayer : function(){ if (this.map==null){ return null; } return this.map.getFrameworkMap(); }, toXML : function(){ Ext.Error.raise({msg: "FlamingoLayer.toXML(): .toXML() must be made!"}); }, getTagName : function(){ Ext.Error.raise({msg: "FlamingoLayer.getTagName: .getTagName() must be made!"}); }, setOption : function(optionKey,optionValue){ this.options[optionKey]=optionValue; }, getId : function(){ return this.id; }, getFrameworkId: function(){ return this.map.getId()+"_"+this.getId(); }, setAlpha : function (alpha){ // Fixup wrong Flash alpha, it thinks 0 is transparent and 100 is opaque if(this.map) { this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"setAlpha",alpha) } }, getAlpha : function (){ return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getAlpha"); }, /** * Get the last getMap request array * @see viewer.viewerController.controller.Layer#getLastMapRequest */ getLastMapRequest: function(){ var request=this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getLastGetMapRequest"); if (request==null){ return null; } return [request]; }, /** * Returns the type of the layer. */ getType: function(){ return this.type; }, /** * reloads the framework map */ reload: function(){ if (this.map !=null && this.map.getFrameworkMap()){ return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"update"); } }, /** * Overwrites the addListener function. Add's the event to allowexternalinterface of flamingo * so flamingo is allowed to broadcast the event. */ addListener : function(event,handler,scope){ //enable flamingo event broadcasting var flamEvent=this.viewerController.mapComponent.eventList[event]; if (flamEvent!=undefined){ //if not enabled yet, add it if (this.enabledEvents[flamEvent]==undefined){ this.map.getFrameworkMap().callMethod(this.viewerController.mapComponent.getId(),"addAllowExternalInterface",this.getFrameworkId()+"."+flamEvent); this.enabledEvents[flamEvent]=true; } } /* fix for infinite loop: * If this is called from a layer that extends the FlamingoArcLayer the superclass is * that FlamingoArcLayer and this function is called again when this.superclass.function is called **/ if (this.superclass.$className == "viewer.viewercontroller.flamingo.FlamingoArcLayer"){ this.superclass.superclass.addListener.call(this,event,handler,scope); }else{ this.superclass.addListener.call(this,event,handler,scope); } //viewer.viewercontroller.controller.Layer.superclass.addListener.call(this,event,handler,scope); }, setVisible : function (visible){ this.visible = visible; if (this.options!=null){ this.options["visible"] = visible; } if (this.map !=null){ this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "setVisible", visible); } }, /** * Get the visibility */ getVisible : function (){ if (this.map !=null){ this.visible = this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "getVisible"); } if (this.options!=null) this.options["visible"] = this.visible; return this.visible; }, /** * Overwrite destroy, clear Listeners and forward to super.destroy */ destroy: function(){ /* fix for infinite loop: * If this is called from a layer that extends the FlamingoArcLayer the superclass is * that FlamingoArcLayer and this function is called again when this.superclass.function is called **/ if (this.superclass.$className == "viewer.viewercontroller.flamingo.FlamingoArcLayer"){ this.superclass.superclass.destroy.call(this); }else{ this.superclass.destroy.call(this); } } });
mvdstruijk/flamingo
viewer/src/main/webapp/viewer-html/common/viewercontroller/flamingo/FlamingoLayer.js
JavaScript
agpl-3.0
5,324
<?php namespace ShiftBundle\Controller\Admin; use Laminas\Mail\Message; use Laminas\View\Model\ViewModel; use ShiftBundle\Entity\RegistrationShift; use ShiftBundle\Entity\Shift\Registered; /** * RegistrationSubscriptionController * * @author Pieter Maene <pieter.maene@litus.cc> */ class RegistrationSubscriptionController extends \CommonBundle\Component\Controller\ActionController\AdminController { public function manageAction() { $shift = $this->getRegistrationShiftEntity(); if ($shift === null) { return new ViewModel(); } $registered = $shift->getRegistered(); $form = $this->getForm('shift_registrationSubscription_add'); if ($this->getRequest()->isPost()) { $form->setData($this->getRequest()->getPost()); if ($form->isValid()) { $subscriber = $form->hydrateObject($shift); if ($subscriber === null) { $this->flashMessenger()->error( 'Error', 'Unable to add the given person to the registration shift!' ); $this->redirect()->toRoute( 'shift_admin_registration_shift_subscription', array( 'action' => 'manage', 'id' => $shift->getId(), ) ); return new ViewModel(); } $this->getEntityManager()->persist($subscriber); $this->getEntityManager()->flush(); $this->redirect()->toRoute( 'shift_admin_registration_shift_subscription', array( 'action' => 'manage', 'id' => $shift->getId(), ) ); return new ViewModel(); } } return new ViewModel( array( 'form' => $form, 'shift' => $shift, 'registered' => $registered, ) ); } public function deleteAction() { $this->initAjax(); $subscription = $this->getSubscriptionEntity(); if ($subscription === null) { return new ViewModel(); } $repository = $this->getEntityManager() ->getRepository('ShiftBundle\Entity\RegistrationShift'); $shift = $repository->findOneByRegistered($subscription->getId()); $shift->removeRegistered($subscription->getPerson()); $mailAddress = $this->getEntityManager() ->getRepository('CommonBundle\Entity\General\Config') ->getConfigValue('shift.mail'); $mailName = $this->getEntityManager() ->getRepository('CommonBundle\Entity\General\Config') ->getConfigValue('shift.mail_name'); $language = $subscription->getPerson()->getLanguage(); if ($language === null) { $language = $this->getEntityManager()->getRepository('CommonBundle\Entity\General\Language') ->findOneByAbbrev('en'); } $mailData = unserialize( $this->getEntityManager() ->getRepository('CommonBundle\Entity\General\Config') ->getConfigValue('shift.subscription_deleted_mail') ); $message = $mailData[$language->getAbbrev()]['content']; $subject = $mailData[$language->getAbbrev()]['subject']; $shiftString = $shift->getName() . ' from ' . $shift->getStartDate()->format('d/m/Y h:i') . ' to ' . $shift->getEndDate()->format('d/m/Y h:i'); $mail = new Message(); $mail->setEncoding('UTF-8') ->setBody(str_replace('{{ shift }}', $shiftString, $message)) ->setFrom($mailAddress, $mailName) ->addTo($subscription->getPerson()->getEmail(), $subscription->getPerson()->getFullName()) ->setSubject($subject); if (getenv('APPLICATION_ENV') != 'development') { $this->getMailTransport()->send($mail); } $this->getEntityManager()->remove($subscription); $this->getEntityManager()->flush(); return new ViewModel( array( 'result' => array( 'status' => 'success', ), ) ); } /** * @return Registered|null */ private function getSubscriptionEntity() { $subscription = $this->getEntityManager() ->getRepository('ShiftBundle\Entity\Shift\Registered') ->findOneById($this->getParam('id', 0)); if ($subscription === null) { $this->flashMessenger()->error( 'Error', 'No subscription with the given ID was found!' ); $this->redirect()->toRoute( 'shift_admin_registration_shift', array( 'action' => 'manage', 'shift' => $this->getEntityById('ShiftBundle\Entity\RegistrationShift', 'shift'), ) ); return; } return $subscription; } /** * @return RegistrationShift|null */ private function getRegistrationShiftEntity() { $shift = $this->getEntityById('ShiftBundle\Entity\RegistrationShift', 'shift'); if (!($shift instanceof RegistrationShift)) { $this->flashMessenger()->error( 'Error', 'No registration shift was found!' ); $this->redirect()->toRoute( 'shift_admin_registration_shift', array( 'action' => 'manage', ) ); return; } return $shift; } }
LitusProject/Litus
module/ShiftBundle/Controller/Admin/RegistrationSubscriptionController.php
PHP
agpl-3.0
5,908
namespace '/storages' do get do @storages = Storage.all return_resource object: @storages end post do @storage = Storage.create!(params[:storage]) return_resource object: @storage end before %r{\A/(?<id>\d+)/?.*} do @storage = Storage.find(params[:id]) end namespace '/:id' do delete do return_resource object: @storage.delete end patch do @storage.assign_attributes(params[:storage]).save! return_resource object: @storage end get do return_resource object: @storage end end end
virtapi/virtapi
controllers/storage_controller.rb
Ruby
agpl-3.0
569
<?php # # Copyright (c) 2000-2003 University of Utah and the Flux Group. # # {{{EMULAB-LICENSE # # This file is part of the Emulab network testbed software. # # This file is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # This file is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public # License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this file. If not, see <http://www.gnu.org/licenses/>. # # }}} # require("defs.php3"); # # A shameless plug for the web crawlers. # PAGEHEADER("Network Emulation using the Utah Network Testbed"); echo "<br> Emulab.Net provides a great network emulation environment! <br> Please see our <a href=\"$TBDOCBASE\">Home Page</a> for more information.<br><br>\n"; echo "<a href='pix/side-crop-big.jpg'> <img src='pix/side-crop-med.jpg' align=center></a>\n"; PAGEFOOTER(); ?>
nmc-probe/emulab-nome
www/netemu.php3
PHP
agpl-3.0
1,261
from django import template register = template.Library() @register.simple_tag def keyvalue(dict, key): return dict[key]
routetopa/tet
tet/browser/templatetags/keyvalue.py
Python
agpl-3.0
127
<?php namespace Zco\Bundle\GroupesBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints as Assert; final class GroupType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('nom', TextType::class, [ 'label' => 'Nom du groupe', 'constraints' => [new Assert\NotBlank()], ]); $builder->add('logo', TextType::class, [ 'label' => 'URL du logo masculin', 'required' => false, ]); $builder->add('logo_feminin', TextType::class, [ 'label' => 'URL du logo féminin', 'required' => false, ]); $builder->add('sanction', CheckboxType::class, [ 'label' => 'Sanction', 'required' => false, ]); $builder->add('team', CheckboxType::class, [ 'label' => 'Équipe', 'required' => false, ]); $builder->add('secondaire', CheckboxType::class, [ 'label' => 'Groupe secondaire', 'required' => false, ]); } }
zcorrecteurs/zcorrecteurs.fr
src/Zco/Bundle/GroupesBundle/Form/GroupType.php
PHP
agpl-3.0
1,347
/* * TeleStax, Open Source Cloud Communications * Copyright 2012, Telestax Inc and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.protocols.ss7.cap.api.service.circuitSwitchedCall.primitive; import java.io.Serializable; /** * <code> CollectedInfo ::= CHOICE { collectedDigits [0] CollectedDigits } </code> * * * * @author sergey vetyutnev * */ public interface CollectedInfo extends Serializable { CollectedDigits getCollectedDigits(); }
RestComm/jss7
cap/cap-api/src/main/java/org/restcomm/protocols/ss7/cap/api/service/circuitSwitchedCall/primitive/CollectedInfo.java
Java
agpl-3.0
1,352
# This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import re def camelcase_to_snakecase(string_to_convert): """ Convert CamelCase string to snake_case Original solution in http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string_to_convert) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
suutari/shoop
shuup/admin/utils/str_utils.py
Python
agpl-3.0
605
package com.tesora.dve.errmap; /* * #%L * Tesora Inc. * Database Virtualization Engine * %% * Copyright (C) 2011 - 2014 Tesora Inc. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ public class OneParamErrorCode<First> extends ErrorCode { public OneParamErrorCode(String name, boolean logError) { super(name, logError); } }
Tesora/tesora-dve-pub
tesora-dve-common/src/main/java/com/tesora/dve/errmap/OneParamErrorCode.java
Java
agpl-3.0
910
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kra.iacuc; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.common.framework.module.CoeusModule; import org.kuali.coeus.common.framework.person.KcPerson; import org.kuali.coeus.common.notification.impl.NotificationHelper; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.authorization.KraAuthorizationConstants; import org.kuali.kra.iacuc.actions.IacucActionHelper; import org.kuali.kra.iacuc.customdata.IacucProtocolCustomDataHelper; import org.kuali.kra.iacuc.noteattachment.IacucNotesAttachmentsHelper; import org.kuali.kra.iacuc.notification.IacucProtocolNotificationContext; import org.kuali.kra.iacuc.onlinereview.IacucOnlineReviewsActionHelper; import org.kuali.kra.iacuc.onlinereview.IacucProtocolOnlineReviewService; import org.kuali.kra.iacuc.permission.IacucPermissionsHelper; import org.kuali.kra.iacuc.personnel.IacucPersonnelHelper; import org.kuali.kra.iacuc.procedures.IacucProtocolProcedureService; import org.kuali.kra.iacuc.procedures.IacucProtocolProceduresHelper; import org.kuali.kra.iacuc.protocol.IacucProtocolHelper; import org.kuali.kra.iacuc.protocol.reference.IacucProtocolReferenceBean; import org.kuali.kra.iacuc.questionnaire.IacucQuestionnaireHelper; import org.kuali.kra.iacuc.specialreview.IacucProtocolSpecialReviewHelper; import org.kuali.kra.iacuc.species.IacucProtocolSpeciesHelper; import org.kuali.kra.iacuc.species.exception.IacucProtocolExceptionHelper; import org.kuali.kra.iacuc.threers.IacucAlternateSearchHelper; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.protocol.ProtocolFormBase; import org.kuali.kra.protocol.actions.ActionHelperBase; import org.kuali.kra.protocol.actions.ProtocolStatusBase; import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionBase; import org.kuali.kra.protocol.customdata.ProtocolCustomDataHelperBase; import org.kuali.kra.protocol.onlinereview.OnlineReviewsActionHelperBase; import org.kuali.kra.protocol.onlinereview.ProtocolOnlineReviewService; import org.kuali.kra.protocol.protocol.ProtocolHelperBase; import org.kuali.kra.protocol.protocol.reference.ProtocolReferenceBeanBase; import org.kuali.kra.protocol.questionnaire.QuestionnaireHelperBase; import org.kuali.kra.protocol.specialreview.ProtocolSpecialReviewHelperBase; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kns.datadictionary.HeaderNavigation; import org.kuali.rice.kns.util.ActionFormUtilMap; import org.kuali.rice.kns.web.ui.HeaderField; import org.kuali.rice.krad.util.GlobalVariables; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; public class IacucProtocolForm extends ProtocolFormBase { private static final long serialVersionUID = -535557943052220820L; private IacucProtocolSpeciesHelper iacucProtocolSpeciesHelper; private IacucAlternateSearchHelper iacucAlternateSearchHelper; private IacucProtocolExceptionHelper iacucProtocolExceptionHelper; private IacucProtocolProceduresHelper iacucProtocolProceduresHelper; private boolean defaultOpenCopyTab = false; private boolean reinitializeModifySubmissionFields = true; public IacucProtocolForm() throws Exception { super(); initializeIacucProtocolSpecies(); initializeIacucAlternateSearchHelper(); initializeIacucProtocolException(); initializeIacucProtocolProcedures(); } public void initializeIacucProtocolSpecies() throws Exception { setIacucProtocolSpeciesHelper(new IacucProtocolSpeciesHelper(this)); } public void initializeIacucProtocolProcedures() throws Exception { setIacucProtocolProceduresHelper(new IacucProtocolProceduresHelper(this)); } public void initializeIacucProtocolException() throws Exception { setIacucProtocolExceptionHelper(new IacucProtocolExceptionHelper(this)); } protected void initializeIacucAlternateSearchHelper() throws Exception { setIacucAlternateSearchHelper(new IacucAlternateSearchHelper(this)); } @Override public String getActionName() { return "iacucProtocol"; } @Override protected String getDefaultDocumentTypeName() { return "IacucProtocolDocument"; } /** * Gets a {@link IacucProtocolDocument ProtocolDocument}. * @return {@link IacucProtocolDocument ProtocolDocument} */ public IacucProtocolDocument getIacucProtocolDocument() { return (IacucProtocolDocument) super.getProtocolDocument(); } @Override protected String getLockRegion() { return KraAuthorizationConstants.LOCK_DESCRIPTOR_IACUC_PROTOCOL; } public IacucProtocolHelper getProtocolHelper() { return (IacucProtocolHelper)super.getProtocolHelper(); } @Override protected ProtocolHelperBase createNewProtocolHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucProtocolHelper((IacucProtocolForm) protocolForm); } public IacucPermissionsHelper getPermissionsHelper(ProtocolFormBase protocolForm) { return (IacucPermissionsHelper)super.getPermissionsHelper(); } @Override protected IacucPermissionsHelper createNewPermissionsHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucPermissionsHelper((IacucProtocolForm) protocolForm); } public IacucPersonnelHelper getPersonnelHelper(ProtocolFormBase protocolForm) { return (IacucPersonnelHelper)super.getPersonnelHelper(); } @Override protected IacucPersonnelHelper createNewPersonnelHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucPersonnelHelper((IacucProtocolForm)protocolForm); } public IacucNotesAttachmentsHelper getNotesAttachmentHelper(ProtocolFormBase form) { return (IacucNotesAttachmentsHelper)super.getNotesAttachmentsHelper(); } @Override protected IacucNotesAttachmentsHelper createNewNotesAttachmentsHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucNotesAttachmentsHelper((IacucProtocolForm)protocolForm); } protected QuestionnaireHelperBase createNewQuestionnaireHelper(ProtocolFormBase form) { return new IacucQuestionnaireHelper(form); } @Override public String getModuleCode() { return CoeusModule.IACUC_PROTOCOL_MODULE_CODE; } public IacucProtocolSpeciesHelper getIacucProtocolSpeciesHelper() { return iacucProtocolSpeciesHelper; } public void setIacucProtocolSpeciesHelper(IacucProtocolSpeciesHelper iacucProtocolSpeciesHelper) { this.iacucProtocolSpeciesHelper = iacucProtocolSpeciesHelper; } public IacucAlternateSearchHelper getIacucAlternateSearchHelper() { return iacucAlternateSearchHelper; } public void setIacucAlternateSearchHelper(IacucAlternateSearchHelper iacucAlternateSearchHelper) { this.iacucAlternateSearchHelper = iacucAlternateSearchHelper; } @Override protected ProtocolReferenceBeanBase createNewProtocolReferenceBeanInstance() { return new IacucProtocolReferenceBean(); } public IacucProtocolExceptionHelper getIacucProtocolExceptionHelper() { return iacucProtocolExceptionHelper; } public void setIacucProtocolExceptionHelper(IacucProtocolExceptionHelper iacucProtocolExceptionHelper) { this.iacucProtocolExceptionHelper = iacucProtocolExceptionHelper; } @Override public void populate(HttpServletRequest request) { super.populate(request); // Temporary hack for KRACOEUS-489 if (getActionFormUtilMap() instanceof ActionFormUtilMap) { ((ActionFormUtilMap) getActionFormUtilMap()).clear(); } getIacucProtocolDocument().getIacucProtocol().setIacucProtocolStudyGroupBeans(getIacucProtocolProcedureService().getRevisedStudyGroupBeans(getIacucProtocolDocument().getIacucProtocol(), getIacucProtocolProceduresHelper().getAllProcedures())); } @Override public void populateHeaderFields(WorkflowDocument workflowDocument) { super.populateHeaderFields(workflowDocument); IacucProtocolDocument pd = getIacucProtocolDocument(); HeaderField documentNumber = getDocInfo().get(0); documentNumber.setDdAttributeEntryName("DataDictionary.IacucProtocolDocument.attributes.documentNumber"); ProtocolStatusBase protocolStatus = (pd == null) ? null : pd.getIacucProtocol().getProtocolStatus(); HeaderField docStatus = new HeaderField("DataDictionary.AttributeReference.attributes.workflowDocumentStatus", protocolStatus == null? "" : protocolStatus.getDescription()); getDocInfo().set(1, docStatus); String lastUpdatedDateStr = null; if(pd != null && pd.getUpdateTimestamp() != null) { lastUpdatedDateStr = getFormattedDateTime(pd.getUpdateTimestamp()); } if(getDocInfo().size() > 2) { KcPerson initiator = getKcPersonService().getKcPersonByPersonId(pd.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId()); String modifiedInitiatorFieldStr = initiator == null ? "" : initiator.getUserName(); if(StringUtils.isNotBlank(lastUpdatedDateStr)) { modifiedInitiatorFieldStr += (" : " + lastUpdatedDateStr); } getDocInfo().set(2, new HeaderField("DataDictionary.IacucProtocol.attributes.initiatorLastUpdated", modifiedInitiatorFieldStr)); } String protocolSubmissionStatusStr = null; if(pd != null && pd.getIacucProtocol() != null && pd.getIacucProtocol().getProtocolSubmission() != null) { pd.getIacucProtocol().getProtocolSubmission().refreshReferenceObject("submissionStatus"); protocolSubmissionStatusStr = pd.getIacucProtocol().getProtocolSubmission().getSubmissionStatus().getDescription(); } HeaderField protocolSubmissionStatus = new HeaderField("DataDictionary.IacucProtocol.attributes.protocolSubmissionStatus", protocolSubmissionStatusStr); getDocInfo().set(3, protocolSubmissionStatus); getDocInfo().add(new HeaderField("DataDictionary.IacucProtocol.attributes.protocolNumber", (pd == null) ? null : pd.getIacucProtocol().getProtocolNumber())); String expirationDateStr = null; if(pd != null && pd.getProtocol().getExpirationDate() != null) { expirationDateStr = getFormattedDate(pd.getIacucProtocol().getExpirationDate()); } HeaderField expirationDate = new HeaderField("DataDictionary.IacucProtocol.attributes.expirationDate", expirationDateStr); getDocInfo().add(expirationDate); } @Override public HeaderNavigation[] getHeaderNavigationTabs() { HeaderNavigation[] navigation = super.getHeaderNavigationTabs(); ProtocolOnlineReviewService onlineReviewService = getProtocolOnlineReviewService(); List<HeaderNavigation> resultList = new ArrayList<HeaderNavigation>(); boolean onlineReviewTabEnabled = false; if (getProtocolDocument() != null && getProtocolDocument().getProtocol() != null) { String principalId = GlobalVariables.getUserSession().getPrincipalId(); ProtocolSubmissionBase submission = getProtocolDocument().getProtocol().getProtocolSubmission(); boolean isUserOnlineReviewer = onlineReviewService.isProtocolReviewer(principalId, false, submission); boolean isUserIacucAdmin = getSystemAuthorizationService().hasRole(GlobalVariables.getUserSession().getPrincipalId(), "KC-UNT", "IACUC Administrator"); onlineReviewTabEnabled = (isUserOnlineReviewer || isUserIacucAdmin) && onlineReviewService.isProtocolInStateToBeReviewed((IacucProtocol)getProtocolDocument().getProtocol()); } //We have to copy the HeaderNavigation elements into a new collection as the //List returned by DD is it's cached copy of the header navigation list. for (HeaderNavigation nav : navigation) { if (StringUtils.equals(nav.getHeaderTabNavigateTo(),ONLINE_REVIEW_NAV_TO)) { nav.setDisabled(!onlineReviewTabEnabled); if (onlineReviewTabEnabled || ((!onlineReviewTabEnabled) && (!HIDE_ONLINE_REVIEW_WHEN_DISABLED))) { resultList.add(nav); } } else { resultList.add(nav); } } HeaderNavigation[] result = new HeaderNavigation[resultList.size()]; resultList.toArray(result); return result; } protected ProtocolOnlineReviewService getProtocolOnlineReviewService() { return KcServiceLocator.getService(IacucProtocolOnlineReviewService.class); } @Override protected QuestionnaireHelperBase createNewQuestionnaireHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucQuestionnaireHelper((IacucProtocolForm) protocolForm); } @Override protected ActionHelperBase createNewActionHelperInstanceHook(ProtocolFormBase protocolForm, boolean initializeActions) throws Exception{ IacucActionHelper iacucActionHelper = new IacucActionHelper((IacucProtocolForm) protocolForm); if(initializeActions) { iacucActionHelper.initializeProtocolActions(); } return iacucActionHelper; } @Override protected ProtocolSpecialReviewHelperBase createNewSpecialReviewHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucProtocolSpecialReviewHelper((IacucProtocolForm) protocolForm); } @Override protected ProtocolCustomDataHelperBase createNewCustomDataHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucProtocolCustomDataHelper((IacucProtocolForm) protocolForm); } @Override protected OnlineReviewsActionHelperBase createNewOnlineReviewsActionHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucOnlineReviewsActionHelper((IacucProtocolForm) protocolForm); } public IacucProtocolProceduresHelper getIacucProtocolProceduresHelper() { return iacucProtocolProceduresHelper; } public void setIacucProtocolProceduresHelper(IacucProtocolProceduresHelper iacucProtocolProceduresHelper) { this.iacucProtocolProceduresHelper = iacucProtocolProceduresHelper; } @Override protected NotificationHelper<IacucProtocolNotificationContext> getNotificationHelperHook() { return new NotificationHelper<IacucProtocolNotificationContext>(); } protected IacucProtocolProcedureService getIacucProtocolProcedureService() { return (IacucProtocolProcedureService) KcServiceLocator.getService("iacucProtocolProcedureService"); } public boolean isReinitializeModifySubmissionFields() { return reinitializeModifySubmissionFields; } public void setReinitializeModifySubmissionFields(boolean reinitializeModifySubmissionFields) { this.reinitializeModifySubmissionFields = reinitializeModifySubmissionFields; } public boolean isDefaultOpenCopyTab() { return defaultOpenCopyTab; } public void setDefaultOpenCopyTab(boolean defaultOpenCopyTab) { this.defaultOpenCopyTab = defaultOpenCopyTab; } @Override protected List<String> getTerminalNodeNamesHook() { List<String> retVal = new ArrayList<String>(); retVal.add(Constants.IACUC_PROTOCOL_IACUCREVIEW_ROUTE_NODE_NAME); return retVal; } public String getShortUrl() { return getBaseShortUrl() + "/kc-common/iacuc-protocols/" + getIacucProtocolDocument().getProtocol().getProtocolNumber(); } }
mukadder/kc
coeus-impl/src/main/java/org/kuali/kra/iacuc/IacucProtocolForm.java
Java
agpl-3.0
16,703