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 com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.UserMap; import com.earth2me.essentials.craftbukkit.BanLookup; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.StringUtil; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.bukkit.BanList; import java.util.UUID; import me.StevenLawson.essentials.EssentialsHandler; import org.bukkit.BanEntry; import org.bukkit.Location; import org.bukkit.Server; public class Commandseen extends EssentialsCommand { public Commandseen() { super("seen"); } @Override protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { seen(server, sender, args, true, true, true); } @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { seen(server, user.getSource(), args, user.isAuthorized("essentials.seen.banreason"), user.isAuthorized("essentials.seen.extra"), user.isAuthorized("essentials.seen.ipsearch")); } protected void seen(final Server server, final CommandSource sender, final String[] args, final boolean showBan, final boolean extra, final boolean ipLookup) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } User player = ess.getOfflineUser(args[0]); if (player == null) { if (ipLookup && FormatUtil.validIP(args[0])) { seenIP(server, sender, args[0]); return; } else if (ess.getServer().getBanList(BanList.Type.IP).isBanned(args[0])) { sender.sendMessage(tl("isIpBanned", args[0])); return; } else if (BanLookup.isBanned(ess, args[0])) { sender.sendMessage(tl("whoisBanned", showBan ? BanLookup.getBanEntry(ess, args[0]).getReason() : tl("true"))); return; } else { try { player = getPlayer(server, sender, args, 0); } catch (NoSuchFieldException e) { throw new PlayerNotFoundException(); } } } if (player.getBase().isOnline() && canInteractWith(sender, player)) { seenOnline(server, sender, player, showBan, extra); } else { seenOffline(server, sender, player, showBan, extra); } } private void seenOnline(final Server server, final CommandSource sender, final User user, final boolean showBan, final boolean extra) throws Exception { user.setDisplayNick(); sender.sendMessage(tl("seenOnline", user.getDisplayName(), DateUtil.formatDateDiff(user.getLastLogin()))); if (ess.getSettings().isDebug()) { ess.getLogger().info("UUID: " + user.getBase().getUniqueId().toString()); } List<String> history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); if (history != null && history.size() > 1) { sender.sendMessage(tl("seenAccounts", StringUtil.joinListSkip(", ", user.getName(), history))); } if (user.isAfk()) { sender.sendMessage(tl("whoisAFK", tl("true"))); } if (user.isJailed()) { sender.sendMessage(tl("whoisJail", (user.getJailTimeout() > 0 ? DateUtil.formatDateDiff(user.getJailTimeout()) : tl("true")))); } if (user.isMuted()) { sender.sendMessage(tl("whoisMuted", (user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : tl("true")))); } final String location = user.getGeoLocation(); if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) { sender.sendMessage(tl("whoisGeoLocation", location)); } if (extra) { if (!sender.isPlayer() || EssentialsHandler.isSuperAdmin(sender.getPlayer())) { sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString())); } } } private void seenOffline(final Server server, final CommandSource sender, User user, final boolean showBan, final boolean extra) throws Exception { user.setDisplayNick(); if (user.getLastLogout() > 0) { sender.sendMessage(tl("seenOffline", user.getName(), DateUtil.formatDateDiff(user.getLastLogout()))); } else { sender.sendMessage(tl("userUnknown", user.getName())); } if (ess.getSettings().isDebug()) { ess.getLogger().info("UUID: " + user.getBase().getUniqueId().toString()); } List<String> history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); if (history != null && history.size() > 1) { sender.sendMessage(tl("seenAccounts", StringUtil.joinListSkip(", ", user.getName(), history))); } if (BanLookup.isBanned(ess, user)) { final BanEntry banEntry = BanLookup.getBanEntry(ess, user.getName()); final String reason = showBan ? banEntry.getReason() : tl("true"); sender.sendMessage(tl("whoisBanned", reason)); if (banEntry.getExpiration() != null) { Date expiry = banEntry.getExpiration(); String expireString = tl("now"); if (expiry.after(new Date())) { expireString = DateUtil.formatDateDiff(expiry.getTime()); } sender.sendMessage(tl("whoisTempBanned", expireString)); } } final String location = user.getGeoLocation(); if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) { sender.sendMessage(tl("whoisGeoLocation", location)); } if (extra) { if (!user.getLastLoginAddress().isEmpty()) { sender.sendMessage(tl("whoisIPAddress", user.getLastLoginAddress())); } final Location loc = user.getLogoutLocation(); if (loc != null) { sender.sendMessage(tl("whoisLocation", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); } } } private void seenIP(final Server server, final CommandSource sender, final String ipAddress) throws Exception { final UserMap userMap = ess.getUserMap(); if (ess.getServer().getBanList(BanList.Type.IP).isBanned(ipAddress)) { sender.sendMessage(tl("isIpBanned", ipAddress)); } sender.sendMessage(tl("runningPlayerMatch", ipAddress)); ess.runTaskAsynchronously(new Runnable() { @Override public void run() { final List<String> matches = new ArrayList<String>(); for (final UUID u : userMap.getAllUniqueUsers()) { final User user = ess.getUserMap().getUser(u); if (user == null) { continue; } final String uIPAddress = user.getLastLoginAddress(); if (!uIPAddress.isEmpty() && uIPAddress.equalsIgnoreCase(ipAddress)) { matches.add(user.getName()); } } if (matches.size() > 0) { sender.sendMessage(tl("matchingIPAddress")); sender.sendMessage(StringUtil.joinList(matches)); } else { sender.sendMessage(tl("noMatchingPlayers")); } } }); } }
RubyFreedomDevelopmentTeam/TF-Essentials
Essentials/src/com/earth2me/essentials/commands/Commandseen.java
Java
gpl-3.0
8,040
package com.github.bordertech.wcomponents.util; import com.github.bordertech.wcomponents.WebUtilities; import org.junit.Assert; import org.junit.Test; import org.owasp.validator.html.Policy; import org.owasp.validator.html.PolicyException; import org.owasp.validator.html.ScanException; /** * Tests for {@link HtmlSanitizerUtil}. * * @author Mark Reeves * @since 1.2.0 */ public class HtmlSanitizerUtil_Test { /** * A simple, valid HTML String for testing. */ private static final String SIMPLE_HTML = "<p>content</p>"; /** * A HTML string with an unsupported attribute. */ private static final String TAINTED_ATTRIBUTE = "<p foo=\"tainted\">content</p>"; /** * A HTML string with a good attribute with an unsupported value (when strict). */ private static final String TAINTED_STYLE = "<p style=\"z-index: 1;\">content</p>"; /** * A HTML string with an unsupported attribute when strict. */ private static final String STRICT_TAINTED_ATTRIBUTE = "<p class=\"tainted\">content</p>"; @Test public void testSanitizerNoChange() throws ScanException, PolicyException { Assert.assertEquals(SIMPLE_HTML, HtmlSanitizerUtil.sanitize(SIMPLE_HTML)); } @Test public void testSanitizerTaintedAttribute() throws ScanException, PolicyException { Assert.assertEquals(SIMPLE_HTML, HtmlSanitizerUtil.sanitize(TAINTED_ATTRIBUTE)); } @Test public void testSanitizerTaintedStyle() throws ScanException, PolicyException { Assert.assertEquals("<p style=\"\">content</p>", HtmlSanitizerUtil.sanitize(TAINTED_STYLE)); } // We only allow two styles. @Test public void testSanitizerGoodStyle() throws ScanException, PolicyException { String input = "<p style=\"text-decoration: line-through;padding-left: 20.0px;\">content</p>"; Assert.assertEquals(input, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerStyleBadDecoration() throws ScanException, PolicyException { String input = "<p style=\"text-decoration: all;\">content</p>"; String expected = "<p style=\"\">content</p>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerStyleBadPadding() throws ScanException, PolicyException { String input = "<p style=\"padding-left: any;\">content</p>"; String expected = "<p style=\"\">content</p>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } // I am not going to test every attribute and element in the config XML. @Test public void testSanitizerGoodAttribute() throws ScanException, PolicyException { String input = "<p title=\"Hello\">content</p>"; Assert.assertEquals(input, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerGoodAttributeBadValue() throws ScanException, PolicyException { String input = "<p title=\"???\">content</p>"; String expected = "<p>content</p>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerRemovedElement() throws ScanException, PolicyException { String input = "<div>Hello<form>goodbye</form></div>"; String expected = "<div>Hello</div>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerFilteredElement() throws ScanException, PolicyException { String input = "<body>Hello <p>goodbye</p></body>"; String expected = "Hello <p>goodbye</p>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerTrucatedElement() throws ScanException, PolicyException { String input = "<tt title=\"hello\">Hello</tt>"; String expected = "<tt>Hello</tt>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerGoodLink() throws ScanException, PolicyException { String input = "<a href=\"http://example.com\">Link</a>"; Assert.assertEquals(input, HtmlSanitizerUtil.sanitize(input)); } // added tel protocol support @Test public void testSanitizerGoodTelLink() throws ScanException, PolicyException { String input = "<a href=\"tel:123456\">Link</a>"; Assert.assertEquals(input, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerGoodLocalLink() throws ScanException, PolicyException { String input = "<a href=\"path/file.html\">Link</a>"; Assert.assertEquals(input, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerGoodServerLocalLink() throws ScanException, PolicyException { String input = "<a href=\"/path/file.html\">Link</a>"; Assert.assertEquals(input, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerFilteredLink() throws ScanException, PolicyException { String input = "<a name=\"anchor\">Hello</a>"; String expected = "<a>Hello</a>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerFilteredLinkBadHref() throws ScanException, PolicyException { String input = "<a href=\"page here\">Hello</a>"; String expected = "Hello"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerEmptyInput() throws ScanException, PolicyException { Assert.assertEquals("", HtmlSanitizerUtil.sanitize("")); } @Test public void testSanitizerEmptyishInput() throws ScanException, PolicyException { String input = " "; Assert.assertEquals(input, HtmlSanitizerUtil.sanitize(input)); } @Test public void testSanitizerNullInput() throws ScanException, PolicyException { Assert.assertNull(HtmlSanitizerUtil.sanitize(null)); } @Test public void testSanitizerAddCloseTags() throws ScanException, PolicyException { String input = "<ul><li>unclosed li<li>second unclosed li</ul>"; String expected = "<ul><li>unclosed li</li><li>second unclosed li</li></ul>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input)); } // Test of lax sanitiser rules. @Test public void testStrictSanitizerElement() throws ScanException, PolicyException { String input = "<input name=\"foo\" type=\"text\" value=\"bar\"/>"; Assert.assertEquals("", HtmlSanitizerUtil.sanitize(input, false)); } @Test public void testLaxScanElement() throws ScanException, PolicyException { String input = "<input name=\"foo\" type=\"text\" value=\"bar\" />"; Assert.assertEquals(input, HtmlSanitizerUtil.sanitize(input, true)); } @Test public void testLaxScanAddCloseTags() throws ScanException, PolicyException { String input = "<ul><li>unclosed li<li>second unclosed li</ul>"; String expected = "<ul><li>unclosed li</li><li>second unclosed li</li></ul>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input, true)); } @Test public void testLaxScanFilteredLinkBadHref() throws ScanException, PolicyException { String input = "<a href=\"page here\">Hello</a>"; String expected = "Hello"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input, true)); } @Test public void testLaxScanFilteredElement() throws ScanException, PolicyException { String input = "<div>Hello<form>goodbye</form></div>"; String expected = "<div>Hellogoodbye</div>"; Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(input, true)); } @Test public void testLaxScanTaintedAttribute() throws ScanException, PolicyException { Assert.assertEquals(SIMPLE_HTML, HtmlSanitizerUtil.sanitize(TAINTED_ATTRIBUTE, true)); } @Test public void testLaxScanTaintedStyle() throws ScanException, PolicyException { Assert.assertEquals(TAINTED_STYLE, HtmlSanitizerUtil.sanitize(TAINTED_STYLE, true)); } @Test public void testStrictScanLaxAttribute() throws ScanException, PolicyException { Assert.assertEquals(SIMPLE_HTML, HtmlSanitizerUtil.sanitize(STRICT_TAINTED_ATTRIBUTE, false)); } @Test public void testLaxScanLaxAttribute() throws ScanException, PolicyException { Assert.assertEquals(STRICT_TAINTED_ATTRIBUTE, HtmlSanitizerUtil.sanitize(STRICT_TAINTED_ATTRIBUTE, true)); } @Test public void testCreatePolicy() throws PolicyException { String resourceName = ConfigurationProperties.getAntisamyStrictConfigurationFile(); Assert.assertNotNull(HtmlSanitizerUtil.createPolicy(resourceName)); } @Test public void testCreatePolicyNullString() throws PolicyException { try { HtmlSanitizerUtil.createPolicy(null); Assert.assertTrue(false); } catch (SystemException ex) { Assert.assertTrue(true); } } @Test public void testCreatePolicyBadString() throws PolicyException { String resourceName = "Bad_Value"; try { HtmlSanitizerUtil.createPolicy(resourceName); Assert.assertTrue(false); } catch (SystemException ex) { Assert.assertTrue(true); } } @Test public void testSanitizeWithPolicy() throws ScanException, PolicyException { String resourceName = ConfigurationProperties.getAntisamyStrictConfigurationFile(); Policy testPolicy = HtmlSanitizerUtil.createPolicy(resourceName); String expected = HtmlSanitizerUtil.sanitize(TAINTED_ATTRIBUTE); Assert.assertEquals(expected, HtmlSanitizerUtil.sanitize(TAINTED_ATTRIBUTE, testPolicy)); } @Test public void testSanitizeWithNullPolicy() throws ScanException, PolicyException { try { HtmlSanitizerUtil.sanitize(TAINTED_ATTRIBUTE, (Policy) null); Assert.assertTrue(false); } catch (SystemException ex) { Assert.assertTrue(true); } } @Test public void testSanitizeOpenBracketEscaped() { String testString = WebUtilities.OPEN_BRACKET_ESCAPE; Assert.assertEquals(testString, HtmlSanitizerUtil.sanitize(testString)); } @Test public void testSanitizeCloseBracketEscaped() { String testString = WebUtilities.CLOSE_BRACKET_ESCAPE; Assert.assertEquals(testString, HtmlSanitizerUtil.sanitize(testString)); } @Test public void testSanitizeOpenBracket() { String testString = "{"; Assert.assertEquals(WebUtilities.OPEN_BRACKET_ESCAPE, HtmlSanitizerUtil.sanitize(testString)); } @Test public void testSanitizeCloseBracket() { String testString = "}"; Assert.assertEquals(WebUtilities.CLOSE_BRACKET_ESCAPE, HtmlSanitizerUtil.sanitize(testString)); } }
BorderTech/wcomponents
wcomponents-core/src/test/java/com/github/bordertech/wcomponents/util/HtmlSanitizerUtil_Test.java
Java
gpl-3.0
10,041
class RemoveKatelloFlagFromContainers < ActiveRecord::Migration[4.2] def up remove_column :containers, :katello end def down add_column :containers, :katello, :boolean end end
theforeman/foreman-docker
db/migrate/20150303175646_remove_katello_flag_from_containers.rb
Ruby
gpl-3.0
193
<?php /** OGotcha, a combat report converter for Ogame * Copyright (C) 2014 Klaas Van Parys * * 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/>. * * This program is based on the Kokx's CR Converter © 2009 kokx: https://github.com/kokx/kokx-converter */ $settings[ 'shipColorAttacker' ] = '#FC850C'; $settings[ 'shipColorDefender' ] = '#1C84BE'; $settings[ 'numberColor' ] = '#3183E7';
Warsaalk/OGotcha
app/modules/kokx/renderer/vii/settings.php
PHP
gpl-3.0
1,038
/* * Copyright (C) 2008-2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.spartacusrex.spartacuside.keyboard; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import org.dyne.zshaolin.R; import java.util.ArrayList; import java.util.List; public class CandidateView extends View { private static final int OUT_OF_BOUNDS = -1; private TerminalKeyboard mService; private List<String> mSuggestions; private int mSelectedIndex; private int mTouchX = OUT_OF_BOUNDS; private Drawable mSelectionHighlight; private boolean mTypedWordValid; private Rect mBgPadding; private static final int MAX_SUGGESTIONS = 32; private static final int SCROLL_PIXELS = 20; private int[] mWordWidth = new int[MAX_SUGGESTIONS]; private int[] mWordX = new int[MAX_SUGGESTIONS]; private static final int X_GAP = 10; private static final List<String> EMPTY_LIST = new ArrayList<String>(); private int mColorNormal; private int mColorRecommended; private int mColorOther; private int mVerticalPadding; private Paint mPaint; private boolean mScrolled; private int mTargetScrollX; private int mTotalWidth; private GestureDetector mGestureDetector; /** * Construct a CandidateView for showing suggested words for completion. * @param context * @param attrs */ public CandidateView(Context context) { super(context); mSelectionHighlight = context.getResources().getDrawable( android.R.drawable.list_selector_background); mSelectionHighlight.setState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused, android.R.attr.state_window_focused, android.R.attr.state_pressed }); Resources r = context.getResources(); setBackgroundColor(r.getColor(R.color.candidate_background)); mColorNormal = r.getColor(R.color.candidate_normal); mColorRecommended = r.getColor(R.color.candidate_recommended); mColorOther = r.getColor(R.color.candidate_other); mVerticalPadding = r.getDimensionPixelSize(R.dimen.candidate_vertical_padding); mPaint = new Paint(); mPaint.setColor(mColorNormal); mPaint.setAntiAlias(true); mPaint.setTextSize(r.getDimensionPixelSize(R.dimen.candidate_font_height)); mPaint.setStrokeWidth(0); mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { mScrolled = true; int sx = getScrollX(); sx += distanceX; if (sx < 0) { sx = 0; } if (sx + getWidth() > mTotalWidth) { sx -= distanceX; } mTargetScrollX = sx; scrollTo(sx, getScrollY()); invalidate(); return true; } }); setHorizontalFadingEdgeEnabled(true); setWillNotDraw(false); setHorizontalScrollBarEnabled(false); setVerticalScrollBarEnabled(false); } /** * A connection back to the service to communicate with the text field * @param listener */ public void setService(TerminalKeyboard listener) { mService = listener; } @Override public int computeHorizontalScrollRange() { return mTotalWidth; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = resolveSize(50, widthMeasureSpec); // Get the desired height of the icon menu view (last row of items does // not have a divider below) Rect padding = new Rect(); mSelectionHighlight.getPadding(padding); final int desiredHeight = ((int)mPaint.getTextSize()) + mVerticalPadding + padding.top + padding.bottom; // Maximum possible width and desired height setMeasuredDimension(measuredWidth, resolveSize(desiredHeight, heightMeasureSpec)); } /** * If the canvas is null, then only touch calculations are performed to pick the target * candidate. */ @Override protected void onDraw(Canvas canvas) { if (canvas != null) { super.onDraw(canvas); } mTotalWidth = 0; if (mSuggestions == null) return; if (mBgPadding == null) { mBgPadding = new Rect(0, 0, 0, 0); if (getBackground() != null) { getBackground().getPadding(mBgPadding); } } int x = 0; final int count = mSuggestions.size(); final int height = getHeight(); final Rect bgPadding = mBgPadding; final Paint paint = mPaint; final int touchX = mTouchX; final int scrollX = getScrollX(); final boolean scrolled = mScrolled; final boolean typedWordValid = mTypedWordValid; final int y = (int) (((height - mPaint.getTextSize()) / 2) - mPaint.ascent()); for (int i = 0; i < count; i++) { String suggestion = mSuggestions.get(i); float textWidth = paint.measureText(suggestion); final int wordWidth = (int) textWidth + X_GAP * 2; mWordX[i] = x; mWordWidth[i] = wordWidth; paint.setColor(mColorNormal); if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) { if (canvas != null) { canvas.translate(x, 0); mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height); mSelectionHighlight.draw(canvas); canvas.translate(-x, 0); } mSelectedIndex = i; } if (canvas != null) { if ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid)) { paint.setFakeBoldText(true); paint.setColor(mColorRecommended); } else if (i != 0) { paint.setColor(mColorOther); } canvas.drawText(suggestion, x + X_GAP, y, paint); paint.setColor(mColorOther); canvas.drawLine(x + wordWidth + 0.5f, bgPadding.top, x + wordWidth + 0.5f, height + 1, paint); paint.setFakeBoldText(false); } x += wordWidth; } mTotalWidth = x; if (mTargetScrollX != getScrollX()) { scrollToTarget(); } } private void scrollToTarget() { int sx = getScrollX(); if (mTargetScrollX > sx) { sx += SCROLL_PIXELS; if (sx >= mTargetScrollX) { sx = mTargetScrollX; requestLayout(); } } else { sx -= SCROLL_PIXELS; if (sx <= mTargetScrollX) { sx = mTargetScrollX; requestLayout(); } } scrollTo(sx, getScrollY()); invalidate(); } public void setSuggestions(List<String> suggestions, boolean completions, boolean typedWordValid) { clear(); if (suggestions != null) { mSuggestions = new ArrayList<String>(suggestions); } mTypedWordValid = typedWordValid; scrollTo(0, 0); mTargetScrollX = 0; // Compute the total width onDraw(null); invalidate(); requestLayout(); } public void clear() { mSuggestions = EMPTY_LIST; mTouchX = OUT_OF_BOUNDS; mSelectedIndex = -1; invalidate(); } @Override public boolean onTouchEvent(MotionEvent me) { if (mGestureDetector.onTouchEvent(me)) { return true; } int action = me.getAction(); int x = (int) me.getX(); int y = (int) me.getY(); mTouchX = x; switch (action) { case MotionEvent.ACTION_DOWN: mScrolled = false; invalidate(); break; case MotionEvent.ACTION_MOVE: if (y <= 0) { // Fling up!? if (mSelectedIndex >= 0) { mService.pickSuggestionManually(mSelectedIndex); mSelectedIndex = -1; } } invalidate(); break; case MotionEvent.ACTION_UP: if (!mScrolled) { if (mSelectedIndex >= 0) { mService.pickSuggestionManually(mSelectedIndex); } } mSelectedIndex = -1; removeHighlight(); requestLayout(); break; } return true; } /** * For flick through from keyboard, call this method with the x coordinate of the flick * gesture. * @param x */ public void takeSuggestionAt(float x) { mTouchX = (int) x; // To detect candidate onDraw(null); if (mSelectedIndex >= 0) { mService.pickSuggestionManually(mSelectedIndex); } invalidate(); } private void removeHighlight() { mTouchX = OUT_OF_BOUNDS; invalidate(); } }
dyne/ZShaolin
termapk/src/com/spartacusrex/spartacuside/keyboard/CandidateView.java
Java
gpl-3.0
10,396
from scipy import stats N=stats.norm print N.mean() # 0 print N.var() # 1 xi = N.isf(0.95) print xi # -1.64485 N.cdf(xi) # Vérification : 0.05 # Graphiques de la fonction de densité et la cumulative. P=plot(N.cdf,x,-10,10) Q=plot(N.pdf,x,-10,10,color="red") show(P+Q)
LaurentClaessens/mazhe
tex/frido/code_sage2.py
Python
gpl-3.0
306
package fr.xephi.authme.process.join; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.events.ProtectInventoryEvent; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.process.login.AsynchronousLogin; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.PluginHookService; import fr.xephi.authme.service.SessionService; import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.settings.WelcomeMessageConfiguration; import fr.xephi.authme.settings.commandconfig.CommandManager; import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.util.InternetProtocolUtils; import fr.xephi.authme.util.PlayerUtils; import org.bukkit.GameMode; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import javax.inject.Inject; import static fr.xephi.authme.service.BukkitService.TICKS_PER_SECOND; import static fr.xephi.authme.settings.properties.RestrictionSettings.PROTECT_INVENTORY_BEFORE_LOGIN; /** * Asynchronous process for when a player joins. */ public class AsynchronousJoin implements AsynchronousProcess { @Inject private Server server; @Inject private DataSource database; @Inject private CommonService service; @Inject private LimboService limboService; @Inject private PluginHookService pluginHookService; @Inject private BukkitService bukkitService; @Inject private AsynchronousLogin asynchronousLogin; @Inject private CommandManager commandManager; @Inject private ValidationService validationService; @Inject private WelcomeMessageConfiguration welcomeMessageConfiguration; @Inject private SessionService sessionService; AsynchronousJoin() { } /** * Processes the given player that has just joined. * * @param player the player to process */ public void processJoin(final Player player) { final String name = player.getName().toLowerCase(); final String ip = PlayerUtils.getPlayerIp(player); if (service.getProperty(RestrictionSettings.UNRESTRICTED_NAMES).contains(name)) { return; } if (service.getProperty(RestrictionSettings.FORCE_SURVIVAL_MODE) && !service.hasPermission(player, PlayerStatePermission.BYPASS_FORCE_SURVIVAL)) { bukkitService.runTask(() -> player.setGameMode(GameMode.SURVIVAL)); } if (service.getProperty(HooksSettings.DISABLE_SOCIAL_SPY)) { pluginHookService.setEssentialsSocialSpyStatus(player, false); } if (!validationService.fulfillsNameRestrictions(player)) { handlePlayerWithUnmetNameRestriction(player, ip); return; } if (!validatePlayerCountForIp(player, ip)) { return; } final boolean isAuthAvailable = database.isAuthAvailable(name); if (isAuthAvailable) { // Protect inventory if (service.getProperty(PROTECT_INVENTORY_BEFORE_LOGIN)) { ProtectInventoryEvent ev = bukkitService.createAndCallEvent( isAsync -> new ProtectInventoryEvent(player, isAsync)); if (ev.isCancelled()) { player.updateInventory(); ConsoleLogger.fine("ProtectInventoryEvent has been cancelled for " + player.getName() + "..."); } } // Session logic if (sessionService.canResumeSession(player)) { service.send(player, MessageKey.SESSION_RECONNECTION); // Run commands bukkitService.scheduleSyncTaskFromOptionallyAsyncTask( () -> commandManager.runCommandsOnSessionLogin(player)); bukkitService.runTaskOptionallyAsync(() -> asynchronousLogin.forceLogin(player)); return; } } else if (!service.getProperty(RegistrationSettings.FORCE)) { bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(() -> { welcomeMessageConfiguration.sendWelcomeMessage(player); }); // Skip if registration is optional return; } processJoinSync(player, isAuthAvailable); } private void handlePlayerWithUnmetNameRestriction(Player player, String ip) { bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(() -> { player.kickPlayer(service.retrieveSingleMessage(player, MessageKey.NOT_OWNER_ERROR)); if (service.getProperty(RestrictionSettings.BAN_UNKNOWN_IP)) { server.banIP(ip); } }); } /** * Performs various operations in sync mode for an unauthenticated player (such as blindness effect and * limbo player creation). * * @param player the player to process * @param isAuthAvailable true if the player is registered, false otherwise */ private void processJoinSync(Player player, boolean isAuthAvailable) { final int registrationTimeout = service.getProperty(RestrictionSettings.TIMEOUT) * TICKS_PER_SECOND; bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(() -> { limboService.createLimboPlayer(player, isAuthAvailable); player.setNoDamageTicks(registrationTimeout); if (pluginHookService.isEssentialsAvailable() && service.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)) { player.performCommand("motd"); } if (service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) { // Allow infinite blindness effect int blindTimeOut = (registrationTimeout <= 0) ? 99999 : registrationTimeout; player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, blindTimeOut, 2)); } commandManager.runCommandsOnJoin(player); }); } /** * Checks whether the maximum number of accounts has been exceeded for the given IP address (according to * settings and permissions). If this is the case, the player is kicked. * * @param player the player to verify * @param ip the ip address of the player * * @return true if the verification is OK (no infraction), false if player has been kicked */ private boolean validatePlayerCountForIp(final Player player, String ip) { if (service.getProperty(RestrictionSettings.MAX_JOIN_PER_IP) > 0 && !service.hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS) && !InternetProtocolUtils.isLoopbackAddress(ip) && countOnlinePlayersByIp(ip) > service.getProperty(RestrictionSettings.MAX_JOIN_PER_IP)) { bukkitService.scheduleSyncTaskFromOptionallyAsyncTask( () -> player.kickPlayer(service.retrieveSingleMessage(player, MessageKey.SAME_IP_ONLINE))); return false; } return true; } private int countOnlinePlayersByIp(String ip) { int count = 0; for (Player player : bukkitService.getOnlinePlayers()) { if (ip.equalsIgnoreCase(PlayerUtils.getPlayerIp(player))) { ++count; } } return count; } }
Xephi/AuthMeReloaded
src/main/java/fr/xephi/authme/process/join/AsynchronousJoin.java
Java
gpl-3.0
7,728
/* * Copyright 2010 Research Studios Austria Forschungsgesellschaft mBH * * This file is part of easyrec. * * easyrec 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. * * easyrec 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 easyrec. If not, see <http://www.gnu.org/licenses/>. */ package org.easyrec.store.dao.core.impl; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.easyrec.model.core.ItemVO; import org.easyrec.store.dao.IDMappingDAO; import org.easyrec.store.dao.core.ProfileDAO; import org.easyrec.store.dao.core.types.ItemTypeDAO; import org.easyrec.store.dao.core.types.impl.ItemTypeDAOMysqlImpl; import org.easyrec.store.dao.impl.AbstractBaseProfileDAOMysqlImpl; import org.easyrec.store.dao.impl.IDMappingDAOMysqlImpl; import org.easyrec.utils.spring.store.dao.DaoUtils; import org.easyrec.utils.spring.store.dao.annotation.DAO; import org.easyrec.utils.spring.store.service.sqlscript.SqlScriptService; import org.springframework.jdbc.core.PreparedStatementCreatorFactory; import org.springframework.jdbc.core.RowMapper; import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; /** * @author szavrel * @author Fabian Salcher */ @DAO public class ProfileDAOMysqlImpl extends AbstractBaseProfileDAOMysqlImpl<Integer, Integer, Integer> implements ProfileDAO { // constants private final static String TABLE_CREATING_SQL_SCRIPT_NAME = "classpath:sql/core/Profile.sql"; private final String GET_PROFILE_QUERY = new StringBuilder("SELECT ").append(DEFAULT_PROFILE_DATA_COLUMN_NAME) .append(" FROM ").append(DEFAULT_TABLE_NAME).append(" WHERE ").append(DEFAULT_TENANT_ID_COLUMN_NAME) .append("=? AND ").append(DEFAULT_ITEM_ID_COLUMN_NAME).append("=? AND ") .append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME).append("=?").toString(); private final String GET_ACTIVE_PROFILE_QUERY = new StringBuilder("SELECT ").append(DEFAULT_PROFILE_DATA_COLUMN_NAME) .append(" FROM ").append(DEFAULT_TABLE_NAME).append(" WHERE ").append(DEFAULT_TENANT_ID_COLUMN_NAME) .append("=? AND ").append(DEFAULT_ITEM_ID_COLUMN_NAME).append("=? AND ") .append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME).append("=? AND ").append(DEFAULT_ACTIVE_COLUMN_NAME).append("=?").toString(); private final String STORE_PROFILE_QUERY = new StringBuilder("INSERT INTO ").append(DEFAULT_TABLE_NAME) .append(" SET ").append(DEFAULT_TENANT_ID_COLUMN_NAME).append(" =?, ").append(DEFAULT_ITEM_ID_COLUMN_NAME) .append(" =?, ").append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME).append(" =?, ") .append(DEFAULT_PROFILE_DATA_COLUMN_NAME).append(" =? ON DUPLICATE KEY UPDATE ") .append(DEFAULT_PROFILE_DATA_COLUMN_NAME).append(" =?").toString(); private final String GET_DIM_VALUE_QUERY = new StringBuilder("SELECT ExtractValue(") .append(DEFAULT_PROFILE_DATA_COLUMN_NAME).append(",?) FROM ").append(DEFAULT_TABLE_NAME).append(" WHERE ") .append(DEFAULT_TENANT_ID_COLUMN_NAME).append("=? AND ").append(DEFAULT_ITEM_ID_COLUMN_NAME) .append("=? AND ").append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME).append("=?").toString(); private final String SQL_ACTIVATE_PROFILE = new StringBuilder().append(" UPDATE ").append(DEFAULT_TABLE_NAME) .append(" SET ").append(DEFAULT_ACTIVE_COLUMN_NAME).append("=1 ").append(" WHERE ") .append(DEFAULT_TENANT_ID_COLUMN_NAME).append("=? AND ").append(DEFAULT_ITEM_ID_COLUMN_NAME) .append("=? AND ").append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME).append("=?").toString(); private final String SQL_DEACTIVATE_PROFILE = new StringBuilder().append(" UPDATE ").append(DEFAULT_TABLE_NAME) .append(" SET ").append(DEFAULT_ACTIVE_COLUMN_NAME).append("=0 ").append(" WHERE ") .append(DEFAULT_TENANT_ID_COLUMN_NAME).append("=? AND ").append(DEFAULT_ITEM_ID_COLUMN_NAME) .append("=? AND ").append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME).append("=?").toString(); private final int[] ARGTYPES_PROFILE_KEY = new int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR}; private final int[] ARGTYPES_PROFILE_ID = new int[]{Types.INTEGER}; // logging private final Log logger = LogFactory.getLog(this.getClass()); private ItemVORowMapper itemRowMapper = new ItemVORowMapper(); private IDMappingDAO idMappingDAO; private ItemTypeDAO itemTypeDAO; // constructor public ProfileDAOMysqlImpl(DataSource dataSource, SqlScriptService sqlScriptService) { super(sqlScriptService); setDataSource(dataSource); // ToDo: They shouldn't be here such mapping stuff should be done in the ProfileService itemTypeDAO = new ItemTypeDAOMysqlImpl(dataSource, sqlScriptService); idMappingDAO = new IDMappingDAOMysqlImpl(dataSource, sqlScriptService); // output connection information if (logger.isInfoEnabled()) { try { logger.info(DaoUtils.getDatabaseURLAndUserName(dataSource)); } catch (Exception e) { logger.error(e); } } } @Override public String getDefaultTableName() { return DEFAULT_TABLE_NAME; } @Override public String getTableCreatingSQLScriptName() { return TABLE_CREATING_SQL_SCRIPT_NAME; } public String getProfile(Integer tenantId, Integer itemId, Integer itemTypeId, Boolean active) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (itemId == null) { throw new IllegalArgumentException("itemId must not be 'null'!"); } if (itemTypeId == null) { throw new IllegalArgumentException("itemTypeId must not be 'null'"); } String itemType = itemTypeDAO.getTypeById(tenantId, itemTypeId); String mappedItemId = idMappingDAO.lookup(itemId); if (mappedItemId == null) throw new IllegalArgumentException("itemId has no string equivalent"); Object[] args; int[] argTypes; if (active == null) { args = new Object[]{tenantId, mappedItemId, itemType}; argTypes = new int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR}; return getJdbcTemplate().queryForObject(GET_PROFILE_QUERY, args, argTypes, String.class); } else { args = new Object[]{tenantId, mappedItemId, itemType, active}; argTypes = new int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.BOOLEAN}; return getJdbcTemplate().queryForObject(GET_ACTIVE_PROFILE_QUERY, args, argTypes, String.class); } } public String getProfile(Integer tenantId, Integer itemId, Integer itemTypeId) { return getProfile(tenantId, itemId, itemTypeId, null); } public int storeProfile(Integer tenantId, Integer itemId, Integer itemTypeId, String profileXML) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (itemId == null) { throw new IllegalArgumentException("itemId must not be 'null'!"); } if (itemTypeId == null) { throw new IllegalArgumentException("itemTypeId must not be 'null'"); } String itemType = itemTypeDAO.getTypeById(tenantId, itemTypeId); String mappedItemId = idMappingDAO.lookup(itemId); if (mappedItemId == null) throw new IllegalArgumentException("itemId has no string equivalent"); Object[] args = {tenantId, mappedItemId, itemType, profileXML, profileXML}; int[] argTypes = {Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.BLOB, Types.BLOB}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(STORE_PROFILE_QUERY, argTypes); int rowsAffected = getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); return rowsAffected; } public void activateProfile(Integer tenant, Integer item, Integer itemType) { String mappedItemId = idMappingDAO.lookup(item); if (mappedItemId == null) throw new IllegalArgumentException("itemId has no string equivalent"); Object[] args = {tenant, mappedItemId, itemTypeDAO.getTypeById(tenant, itemType)}; try { getJdbcTemplate().update(SQL_ACTIVATE_PROFILE, args, ARGTYPES_PROFILE_KEY); } catch (Exception e) { logger.debug(e); } } public void deactivateProfile(Integer tenant, Integer item, Integer itemType) { String mappedItemId = idMappingDAO.lookup(item); if (mappedItemId == null) throw new IllegalArgumentException("itemId has no string equivalent"); Object[] args = {tenant, mappedItemId, itemTypeDAO.getTypeById(tenant, itemType)}; try { getJdbcTemplate().update(SQL_DEACTIVATE_PROFILE, args, ARGTYPES_PROFILE_KEY); } catch (Exception e) { logger.debug(e); } } public Set<String> getMultiDimensionValue(Integer tenantId, Integer itemId, Integer itemTypeId, String dimensionXPath) { Set<String> ret = new HashSet<String>(); if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (itemId == null) { throw new IllegalArgumentException("itemId must not be 'null'!"); } if (itemTypeId == null) { throw new IllegalArgumentException("itemTypeId must not be 'null'"); } Object[] args; int[] argTypes; args = new Object[]{dimensionXPath, tenantId, idMappingDAO.lookup(itemId), itemTypeDAO.getTypeById(tenantId, itemTypeId)}; argTypes = new int[]{Types.VARCHAR, Types.INTEGER, Types.VARCHAR, Types.VARCHAR}; String result = getJdbcTemplate().queryForObject(GET_DIM_VALUE_QUERY, args, argTypes, String.class); StringTokenizer st = new StringTokenizer(result, " "); while (st.hasMoreTokens()) { ret.add(st.nextToken()); } return ret; } public String getSimpleDimensionValue(Integer tenantId, Integer itemId, Integer itemTypeId, String dimensionXPath) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (itemId == null) { throw new IllegalArgumentException("itemId must not be 'null'!"); } if (itemTypeId == null) { throw new IllegalArgumentException("itemTypeId must not be 'null'"); } Object[] args; int[] argTypes; args = new Object[]{dimensionXPath, tenantId, idMappingDAO.lookup(itemId), itemTypeDAO.getTypeById(tenantId, itemTypeId)}; argTypes = new int[]{Types.VARCHAR, Types.INTEGER, Types.VARCHAR, Types.VARCHAR}; return getJdbcTemplate().queryForObject(GET_DIM_VALUE_QUERY, args, argTypes, String.class); } public boolean updateXML(Integer tenantId, Integer itemId, Integer itemTypeId, String updateXPath, String newXML) { String query = new StringBuilder ("SELECT UpdateXML(") .append(DEFAULT_PROFILE_DATA_COLUMN_NAME) .append(", ?, ?) FROM ") .append(DEFAULT_TABLE_NAME) .append(" WHERE ") .append(DEFAULT_TENANT_ID_COLUMN_NAME) .append("=? AND ") .append(DEFAULT_ITEM_ID_COLUMN_NAME) .append("=? AND ") .append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME) .append("=?") .toString(); Object[] args; int[] argTypes; args = new Object[]{updateXPath, newXML, tenantId, idMappingDAO.lookup(itemId), itemTypeDAO.getTypeById(tenantId, itemTypeId)}; argTypes = new int[]{Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.VARCHAR, Types.VARCHAR}; String modifiedProfile = getJdbcTemplate().queryForObject(query, args, argTypes, String.class); int result = 0; if (modifiedProfile != null) result = storeProfile(tenantId, itemId, itemTypeId, modifiedProfile); return (result != 0); } public boolean deleteProfile(Integer tenantId, Integer itemId, Integer itemTypeId) { if (tenantId == null) { throw new IllegalArgumentException("tenantId must not be 'null'!"); } if (itemId == null) { throw new IllegalArgumentException("itemId must not be 'null'!"); } if (itemTypeId == null) { throw new IllegalArgumentException("itemTypeId must not be 'null'"); } String itemType = itemTypeDAO.getTypeById(tenantId, itemTypeId); String mappedItemId = idMappingDAO.lookup(itemId); if (mappedItemId == null) throw new IllegalArgumentException("itemId has no string equivalent"); Object[] args = {tenantId, mappedItemId, itemType, null, null}; int[] argTypes = {Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.BLOB, Types.BLOB}; PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(STORE_PROFILE_QUERY, argTypes); int rowsAffected = getJdbcTemplate().update(factory.newPreparedStatementCreator(args)); return (rowsAffected > 0); } public List<ItemVO<Integer, Integer>> getItemsByDimensionValue(Integer tenantId, Integer itemType, String dimensionXPath, String value) { List<Object> args = Lists.newArrayList(); List<Integer> argt = Lists.newArrayList(); StringBuilder sqlString = new StringBuilder("SELECT "); sqlString.append(DEFAULT_TENANT_ID_COLUMN_NAME).append(","); sqlString.append(DEFAULT_ITEM_ID_COLUMN_NAME).append(","); sqlString.append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME); sqlString.append(" FROM "); sqlString.append(DEFAULT_TABLE_NAME); sqlString.append(" WHERE "); if (tenantId != null) { sqlString.append(DEFAULT_TENANT_ID_COLUMN_NAME).append("=? AND "); args.add(tenantId); argt.add(Types.INTEGER); } if (itemType != null) { sqlString.append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME).append("=? AND "); args.add(itemTypeDAO.getTypeById(tenantId, itemType)); argt.add(Types.VARCHAR); } sqlString.append("ExtractValue(").append(DEFAULT_PROFILE_DATA_COLUMN_NAME); sqlString.append(",?)=?"); args.add(dimensionXPath); argt.add(Types.VARCHAR); args.add(value); argt.add(Types.VARCHAR); return getJdbcTemplate().query(sqlString.toString(), args.toArray(), Ints.toArray(argt), itemRowMapper); } public List<ItemVO<Integer, Integer>> getItemsByItemType(Integer tenantId, Integer itemType, int count) { if (itemType == null) { throw new IllegalArgumentException("itemType must not be 'null'"); } List<Object> args = Lists.newArrayList((Object) itemTypeDAO.getTypeById(tenantId, itemType)); List<Integer> argt = Lists.newArrayList(Types.VARCHAR); StringBuilder sqlString = new StringBuilder("SELECT "); sqlString.append(DEFAULT_TENANT_ID_COLUMN_NAME).append(","); sqlString.append(DEFAULT_ITEM_ID_COLUMN_NAME).append(","); sqlString.append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME); sqlString.append(" FROM "); sqlString.append(DEFAULT_TABLE_NAME); sqlString.append(" WHERE "); sqlString.append(DEFAULT_ITEM_TYPE_ID_COLUMN_NAME); sqlString.append("=?"); if (tenantId != null) { sqlString.append(" AND ").append(DEFAULT_TENANT_ID_COLUMN_NAME).append("=?"); args.add(tenantId); argt.add(Types.INTEGER); } if (count != 0) { sqlString.append(" LIMIT ?"); args.add(count); argt.add(Types.INTEGER); } return getJdbcTemplate().query(sqlString.toString(), args.toArray(), Ints.toArray(argt), itemRowMapper); } ////////////////////////////////////////////////////////////////////////////// // private inner classes private class ItemVORowMapper implements RowMapper<ItemVO<Integer, Integer>> { public ItemVO<Integer, Integer> mapRow(ResultSet rs, int rowNum) throws SQLException { int tenant = DaoUtils.getInteger(rs, DEFAULT_TENANT_ID_COLUMN_NAME); ItemVO<Integer, Integer> item = new ItemVO<Integer, Integer>( tenant, idMappingDAO.lookup(DaoUtils.getStringIfPresent(rs, DEFAULT_ITEM_ID_COLUMN_NAME)), itemTypeDAO.getIdOfType(tenant, DaoUtils.getStringIfPresent(rs, DEFAULT_ITEM_TYPE_ID_COLUMN_NAME))); return item; } } }
ferronrsmith/easyrec
easyrec-core/src/main/java/org/easyrec/store/dao/core/impl/ProfileDAOMysqlImpl.java
Java
gpl-3.0
17,841
package net.minecraft.client.particle; import net.minecraft.block.material.Material; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class ParticleBubble extends Particle { protected ParticleBubble(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); this.particleRed = 1.0F; this.particleGreen = 1.0F; this.particleBlue = 1.0F; this.setParticleTextureIndex(32); this.setSize(0.02F, 0.02F); this.particleScale *= this.rand.nextFloat() * 0.6F + 0.2F; this.motionX = xSpeedIn * 0.20000000298023224D + (Math.random() * 2.0D - 1.0D) * 0.019999999552965164D; this.motionY = ySpeedIn * 0.20000000298023224D + (Math.random() * 2.0D - 1.0D) * 0.019999999552965164D; this.motionZ = zSpeedIn * 0.20000000298023224D + (Math.random() * 2.0D - 1.0D) * 0.019999999552965164D; this.particleMaxAge = (int)(8.0D / (Math.random() * 0.8D + 0.2D)); } public void onUpdate() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; this.motionY += 0.002D; this.moveEntity(this.motionX, this.motionY, this.motionZ); this.motionX *= 0.8500000238418579D; this.motionY *= 0.8500000238418579D; this.motionZ *= 0.8500000238418579D; if (this.worldObj.getBlockState(new BlockPos(this.posX, this.posY, this.posZ)).getMaterial() != Material.WATER) { this.setExpired(); } if (this.particleMaxAge-- <= 0) { this.setExpired(); } } public static class Factory implements IParticleFactory { public Particle getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { return new ParticleBubble(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); } } }
MartyParty21/AwakenDreamsClient
mcp/src/minecraft/net/minecraft/client/particle/ParticleBubble.java
Java
gpl-3.0
2,145
/* * ScaleAdapter.java * * Norbiron Game * This is a case study for creating sprites for SamuEntropy/Brainboard. * * Copyright (C) 2016, Dr. Bátfai Norbert * * 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/>. * * Ez a program szabad szoftver; terjeszthető illetve módosítható a * Free Software Foundation által kiadott GNU General Public License * dokumentumában leírtak; akár a licenc 3-as, akár (tetszőleges) későbbi * változata szerint. * * Ez a program abban a reményben kerül közreadásra, hogy hasznos lesz, * de minden egyéb GARANCIA NÉLKÜL, az ELADHATÓSÁGRA vagy VALAMELY CÉLRA * VALÓ ALKALMAZHATÓSÁGRA való származtatott garanciát is beleértve. * További részleteket a GNU General Public License tartalmaz. * * A felhasználónak a programmal együtt meg kell kapnia a GNU General * Public License egy példányát; ha mégsem kapta meg, akkor * tekintse meg a <http://www.gnu.org/licenses/> oldalon. * * Version history: * * 0.0.1, 2013.szept.29. */ package batfai.samuentropy.brainboard8; /** * * @author nbatfai */ public class ScaleAdapter extends android.view.ScaleGestureDetector.SimpleOnScaleGestureListener { private NorbironSurfaceView surfaceView; public ScaleAdapter(NorbironSurfaceView surfaceView) { this.surfaceView = surfaceView; } @Override public boolean onScale(android.view.ScaleGestureDetector detector) { float scaleFactor = surfaceView.getScaleFactor() * detector.getScaleFactor(); surfaceView.setScaleFactor(Math.max(0.5f, Math.min(scaleFactor, 3.0f))); surfaceView.repaint(); return true; } }
artibarti/SamuEntropy
cs/BrainBoard/BrainBoard_v9/src/batfai/samuentropy/brainboard8/ScaleAdapter.java
Java
gpl-3.0
2,254
<?php /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ namespace Twilio\Tests\Integration\Taskrouter\V1\Workspace\Worker; use Twilio\Exceptions\DeserializeException; use Twilio\Exceptions\TwilioException; use Twilio\Http\Response; use Twilio\Tests\HolodeckTestCase; use Twilio\Tests\Request; class WorkersStatisticsTest extends HolodeckTestCase { public function testFetchRequest() { $this->holodeck->mock(new Response(500, '')); try { $this->twilio->taskrouter->v1->workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") ->workers ->statistics()->fetch(); } catch (DeserializeException $e) {} catch (TwilioException $e) {} $this->assertRequest(new Request( 'get', 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/Statistics' )); } public function testFetchResponse() { $this->holodeck->mock(new Response( 200, ' { "cumulative": { "reservations_created": 0, "reservations_accepted": 0, "reservations_rejected": 0, "reservations_timed_out": 0, "reservations_canceled": 0, "reservations_rescinded": 0, "activity_durations": [ { "max": 0, "min": 900, "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendly_name": "Offline", "avg": 1080, "total": 5400 }, { "max": 0, "min": 900, "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendly_name": "Busy", "avg": 1012, "total": 8100 }, { "max": 0, "min": 0, "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendly_name": "Idle", "avg": 0, "total": 0 }, { "max": 0, "min": 0, "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendly_name": "Reserved", "avg": 0, "total": 0 } ], "start_time": "2008-01-02T00:00:00Z", "end_time": "2008-01-02T00:00:00Z" }, "realtime": { "total_workers": 15, "activity_statistics": [ { "friendly_name": "Idle", "workers": 0, "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }, { "friendly_name": "Busy", "workers": 9, "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }, { "friendly_name": "Offline", "workers": 6, "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }, { "friendly_name": "Reserved", "workers": 0, "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ] }, "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/Statistics" } ' )); $actual = $this->twilio->taskrouter->v1->workspaces("WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") ->workers ->statistics()->fetch(); $this->assertNotNull($actual); } }
vmvargas/rogo-bot
vendor/twilio/sdk/Twilio/Tests/Integration/Taskrouter/V1/Workspace/Worker/WorkersStatisticsTest.php
PHP
gpl-3.0
4,630
/** * GaiaEHR (Electronic Health Records) * Copyright (C) 2012 Ernesto Rodriguez * * 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/>. */ Ext.define('App.model.administration.LabObservations', { extend: 'Ext.data.Model', table: { name: 'labs_panels', comment: 'Laboratory Observations' }, fields: [ {name: 'id', type: 'string', comment: 'LOINC'}, {name: 'code_text_short', type: 'string' }, {name: 'parent_id', type: 'int', dataType: 'bigint' }, {name: 'parent_loinc', type: 'string', dataType: 'text' }, {name: 'parent_name', type: 'string', dataType: 'text' }, {name: 'sequence', type: 'string', dataType: 'text' }, {name: 'loinc_number', type: 'string', dataType: 'text' }, {name: 'loinc_name', type: 'string', dataType: 'text' }, {name: 'default_unit', type: 'string' }, {name: 'range_start', type: 'string' }, {name: 'range_end', type: 'string' }, {name: 'required_in_panel', type: 'string', dataType: 'text' }, {name: 'description', type: 'string', dataType: 'text' }, {name: 'active', type: 'bool' } ] });
chithubco/doctorapp
app/model/administration/LabObservations.js
JavaScript
gpl-3.0
1,649
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Plugin version info * * @package tool * @subpackage uploaduser * @copyright 2011 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; $plugin->version = 2011092500; // The current plugin version (Date: YYYYMMDDXX) $plugin->requires = 2011092100; // Requires this Moodle version $plugin->component = 'tool_uploaduser'; // Full name of the plugin (used for diagnostics)
luke-tucker/moodle-old
admin/tool/uploaduser/version.php
PHP
gpl-3.0
1,173
package net.programmierecke.radiodroid2.recording; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Build; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.RecyclerView; import net.programmierecke.radiodroid2.BuildConfig; import net.programmierecke.radiodroid2.R; import java.io.File; import java.util.List; public class RecordingsAdapter extends RecyclerView.Adapter<RecordingsAdapter.RecordingItemViewHolder> { final static String TAG = "RecordingsAdapter"; class RecordingItemViewHolder extends RecyclerView.ViewHolder { final ViewGroup viewRoot; final TextView textViewTitle; final TextView textViewTime; private RecordingItemViewHolder(View itemView) { super(itemView); viewRoot = (ViewGroup) itemView; textViewTitle = itemView.findViewById(R.id.textViewTitle); textViewTime = itemView.findViewById(R.id.textViewTime); } } private Context context; private List<DataRecording> recordings; public RecordingsAdapter(@NonNull Context context) { this.context = context; } @NonNull @Override public RecordingsAdapter.RecordingItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View itemView = inflater.inflate(R.layout.list_item_recording, parent, false); return new RecordingItemViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull RecordingItemViewHolder holder, int position) { final DataRecording recording = recordings.get(position); holder.textViewTitle.setText(recording.Name); //holder.textViewTime.setText(recording.Time); holder.viewRoot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openRecording(recording); } }); } public void setRecordings(List<DataRecording> recordings) { if (this.recordings != null && recordings.size() == this.recordings.size()) { boolean same = true; for (int i = 0; i < recordings.size(); i++) { if (!recordings.get(i).equals(this.recordings.get(i))) { same = false; break; } } if (same) { return; } } this.recordings = recordings; notifyDataSetChanged(); } @Override public int getItemCount() { return recordings != null ? recordings.size() : 0; } void openRecording(DataRecording theData) { String path = RecordingsManager.getRecordDir() + "/" + theData.Name; if (BuildConfig.DEBUG) { Log.d(TAG, "play: " + path); } Intent i = new Intent(path); i.setAction(android.content.Intent.ACTION_VIEW); File file = new File(path); Uri fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file); i.setDataAndType(fileUri, "audio/*"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { ClipData clip = ClipData.newUri(context.getContentResolver(), "Record", fileUri); i.setClipData(clip); i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; context.grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); } } context.startActivity(i); } }
segler-alex/RadioDroid
app/src/main/java/net/programmierecke/radiodroid2/recording/RecordingsAdapter.java
Java
gpl-3.0
4,544
<?php namespace phpws; /** * Creates a session to hold module settings. * Prevents modules from having to load their config tables * per page. * * @author Matt McNaney <mcnaney at gmail dot com> * @version $Id$ */ class PHPWS_Settings { /** * Returns the value of a setting or false if not set */ public static function get($module, $setting = null) { if (empty($setting) && PHPWS_Settings::is_set($module)) { return $GLOBALS['PHPWS_Settings'][$module]; } elseif (PHPWS_Settings::is_set($module, $setting)) { return $GLOBALS['PHPWS_Settings'][$module][$setting]; } else { return null; } } /** * Checks to see if the value isset in the global variable. * is_set does not load all of the modules at once to allow * checking against default settings. If all were pulled at once, * newly added settings would get ignored. */ public static function is_set($module, $setting = null) { if (!isset($GLOBALS['PHPWS_Settings'][$module])) { $result = PHPWS_Settings::load($module); if (\phpws\PHPWS_Error::isError($result)) { \phpws\PHPWS_Error::log($result); return false; } } if (is_array($GLOBALS['PHPWS_Settings'][$module])) { if (empty($setting)) { return true; } elseif (isset($GLOBALS['PHPWS_Settings'][$module][$setting])) { return true; } else { return false; } } else { return false; } } public static function in_array($module, $setting, $value) { if (!PHPWS_Settings::is_set($module, $setting)) { return false; } return in_array($value, $GLOBALS['PHPWS_Settings'][$module][$setting]); } /** * Sets the module setting value */ public static function set($module, $setting, $value = null) { if (empty($setting)) { return; } if (is_array($setting)) { foreach ($setting as $key => $subval) { PHPWS_Settings::set($module, $key, $subval); } return true; } $GLOBALS['PHPWS_Settings'][$module][$setting] = $value; return true; } /* * Not in use and probably not usable. Removing notes on it but keeping it just * in case someone is using it. */ public static function append($module, $setting, $value) { if (is_array($setting)) { foreach ($setting as $key => $subval) { $result = PHPWS_Settings::append($module, $key, $subval); if (!$result) { return false; } } return true; } elseif (isset($GLOBALS['PHPWS_Settings'][$module][$setting]) && !is_array($GLOBALS['PHPWS_Settings'][$module][$setting])) { return false; } $GLOBALS['PHPWS_Settings'][$module][$setting][] = $value; return true; } /** * updates the settings table */ public static function save($module) { if (!PHPWS_Settings::is_set($module)) { return false; } $db = new PHPWS_DB('mod_settings'); $db->addWhere('module', $module); $db->addWhere('setting_name', array_keys($GLOBALS['PHPWS_Settings'][$module])); $db->delete(); $db->reset(); foreach ($GLOBALS['PHPWS_Settings'][$module] as $key => $value) { if (empty($key)) { continue; } $type = PHPWS_Settings::getType($value); $db->addValue('module', $module); $db->addValue('setting_name', $key); $db->addValue('setting_type', $type); switch ($type) { case 1: $db->addValue('small_num', (int) $value); break; case 2: $db->addValue('large_num', (int) $value); break; case 3: $db->addValue('small_char', $value); break; case 4: $db->addValue('large_char', $value); break; } $result = $db->insert(); if (\phpws\PHPWS_Error::isError($result)) { unset($GLOBALS['PHPWS_Settings'][$module]); PHPWS_Settings::load($module); return $result; } $db->reset(); } unset($GLOBALS['PHPWS_Settings'][$module]); PHPWS_Settings::load($module); } public static function loadConfig($module) { $filename = sprintf('%smod/%s/inc/settings.php', PHPWS_SOURCE_DIR, $module); if (is_file($filename)) { return $filename; } else { return null; } } public static function reset($module, $value) { $default = PHPWS_Settings::loadConfig($module); if (!$default) { return \phpws\PHPWS_Error::get(SETTINGS_MISSING_FILE, 'core', 'PHPWS_Settings::reset', $module); } include $default; if (isset($settings[$value])) { PHPWS_Settings::set($module, $value, $settings[$value]); $result = PHPWS_Settings::save($module); return true; } else { return false; } } /** * Loads the settings into the session * */ public static function load($module) { $default = PHPWS_Settings::loadConfig($module); if (!$default) { $GLOBALS['PHPWS_Settings'][$module] = 1; return \phpws\PHPWS_Error::get(SETTINGS_MISSING_FILE, 'core', 'PHPWS_Settings::load', $module); } include $default; PHPWS_Settings::set($module, $settings); $db = new PHPWS_DB('mod_settings'); $db->addWhere('module', $module); $result = $db->select(); if (empty($result)) { PHPWS_Settings::save($module); } else { foreach ($result as $key => $value) { switch ($value['setting_type']) { case 1: $setval = $value['small_num']; break; case 2: $setval = $value['large_num']; break; case 3: $setval = $value['small_char']; break; case 4: $setval = $value['large_char']; break; } PHPWS_Settings::set($module, $value['setting_name'], $setval); } } return true; } public static function getType($value) { switch (gettype($value)) { case 'NULL': return 3; break; case 'boolean': case 'integer': if ((int) $value < 32700) { return 1; } else { return 2; } break; case 'double': case 'string': if (strpos($value, '.') === false && is_numeric($value)) { return PHPWS_Settings::getType((int) $value); } if (strlen($value) < 100) { return 3; } else { return 4; } break; case 'object': case 'array': return 4; break; default: return 4; } } /** * Unregisters a module's settings */ public static function unregister($module) { $db = new PHPWS_DB('mod_settings'); $db->addWhere('module', $module); return $db->delete(); } /** * Clears the settings global */ public static function clear() { unset($GLOBALS['PHPWS_Settings']); } }
jlbooker/phpwebsite
src-phpws-legacy/src/PHPWS_Settings.php
PHP
gpl-3.0
8,205
// SuperTux // Copyright (C) 2006 Matthias Braun <matze@braunis.de> // Ingo Ruhnke <grumbel@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <config.h> #include <sstream> #include <stdlib.h> #include <string.h> #include <stdexcept> #include <SDL_image.h> #include <physfs.h> #include "lisp/list_iterator.hpp" #include "lisp/parser.hpp" #include "physfs/physfs_sdl.hpp" #include "supertux/screen.hpp" #include "util/file_system.hpp" #include "util/log.hpp" #include "util/utf8_iterator.hpp" #include "video/drawing_context.hpp" #include "video/drawing_request.hpp" #include "video/font.hpp" #include "video/renderer.hpp" namespace { bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold) { Uint8* pixels = (Uint8*)surface->pixels; for(int y = start_y; y < end_y; ++y) { const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3]; if (p > threshold) { return false; } } return true; } } // namespace Font::Font(GlyphWidth glyph_width_, const std::string& filename, int shadowsize_) : glyph_width(glyph_width_), glyph_surfaces(), shadow_surfaces(), char_height(), shadowsize(shadowsize_), border(0), rtl(false), glyphs(65536) { for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1; const std::string fontdir = FileSystem::dirname(filename); const std::string fontname = FileSystem::basename(filename); // scan for prefix-filename in addons search path char **rc = PHYSFS_enumerateFiles(fontdir.c_str()); for (char **i = rc; *i != NULL; i++) { std::string filename_(*i); if( filename_.rfind(fontname) != std::string::npos ) { loadFontFile(fontdir + filename_); } } PHYSFS_freeList(rc); } void Font::loadFontFile(const std::string &filename) { lisp::Parser parser; log_debug << "Loading font: " << filename << std::endl; const lisp::Lisp* root = parser.parse(filename); const lisp::Lisp* config_l = root->get_lisp("supertux-font"); if(!config_l) { std::ostringstream msg; msg << "Font file:" << filename << ": is not a supertux-font file"; throw std::runtime_error(msg.str()); } int def_char_width=0; if( !config_l->get("glyph-width",def_char_width) ) { log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl; } if( !config_l->get("glyph-height",char_height) ) { std::ostringstream msg; msg << "Font:" << filename << ": misses glyph-height"; throw std::runtime_error(msg.str()); } config_l->get("glyph-border", border); config_l->get("rtl", rtl); lisp::ListIterator iter(config_l); while(iter.next()) { const std::string& token = iter.item(); if( token == "surface" ) { const lisp::Lisp * glyphs_val = iter.lisp(); int local_char_width; bool monospaced; GlyphWidth local_glyph_width; std::string glyph_image; std::string shadow_image; std::vector<std::string> chars; if( ! glyphs_val->get("glyph-width", local_char_width) ) { local_char_width = def_char_width; } if( ! glyphs_val->get("monospace", monospaced ) ) { local_glyph_width = glyph_width; } else { if( monospaced ) local_glyph_width = FIXED; else local_glyph_width = VARIABLE; } if( ! glyphs_val->get("glyphs", glyph_image) ) { std::ostringstream msg; msg << "Font:" << filename << ": missing glyphs image"; throw std::runtime_error(msg.str()); } if( ! glyphs_val->get("shadows", shadow_image) ) { std::ostringstream msg; msg << "Font:" << filename << ": missing shadows image"; throw std::runtime_error(msg.str()); } if( ! glyphs_val->get("chars", chars) || chars.size() == 0) { std::ostringstream msg; msg << "Font:" << filename << ": missing chars definition"; throw std::runtime_error(msg.str()); } if( local_char_width==0 ) { std::ostringstream msg; msg << "Font:" << filename << ": misses glyph-width for some surface"; throw std::runtime_error(msg.str()); } loadFontSurface(glyph_image, shadow_image, chars, local_glyph_width, local_char_width); } } } void Font::loadFontSurface( const std::string &glyphimage, const std::string &shadowimage, const std::vector<std::string> &chars, GlyphWidth glyph_width_, int char_width ) { SurfacePtr glyph_surface = Surface::create("images/engine/fonts/" + glyphimage); SurfacePtr shadow_surface = Surface::create("images/engine/fonts/" + shadowimage); int surface_idx = glyph_surfaces.size(); glyph_surfaces.push_back(glyph_surface); shadow_surfaces.push_back(shadow_surface); int row=0, col=0; int wrap = glyph_surface->get_width() / char_width; SDL_Surface *surface = NULL; if( glyph_width_ == VARIABLE ) { //this does not work: // surface = ((SDL::Texture *)glyph_surface.get_texture())->get_texture(); surface = IMG_Load_RW(get_physfs_SDLRWops("images/engine/fonts/"+glyphimage), 1); if(surface == NULL) { std::ostringstream msg; msg << "Couldn't load image '" << glyphimage << "' :" << SDL_GetError(); throw std::runtime_error(msg.str()); } SDL_LockSurface(surface); } for( unsigned int i = 0; i < chars.size(); i++) { for(UTF8Iterator chr(chars[i]); !chr.done(); ++chr) { int y = row * (char_height + 2*border) + border; int x = col * (char_width + 2*border) + border; if( ++col == wrap ) { col=0; row++; } if( *chr == 0x0020 && glyphs[0x20].surface_idx != -1) continue; Glyph glyph; glyph.surface_idx = surface_idx; if( glyph_width_ == FIXED || isdigit(*chr) ) { glyph.rect = Rectf(x, y, x + char_width, y + char_height); glyph.offset = Vector(0, 0); glyph.advance = char_width; } else { if (y + char_height > surface->h) { log_warning << "error: font definition contains more letter then the images: " << glyphimage << std::endl; goto abort; } int left = x; while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64)) left += 1; int right = x + char_width - 1; while (right > left && vline_empty(surface, right, y, y + char_height, 64)) right -= 1; if (left <= right) { glyph.offset = Vector(x-left, 0); glyph.advance = right - left + 1 + 1; // FIXME: might be useful to make spacing configurable } else { // glyph is completly transparent glyph.offset = Vector(0, 0); glyph.advance = char_width + 1; // FIXME: might be useful to make spacing configurable } glyph.rect = Rectf(x, y, x + char_width, y + char_height); } glyphs[*chr] = glyph; } if( col>0 && col <= wrap ) { col = 0; row++; } } abort: if( surface != NULL ) { SDL_UnlockSurface(surface); SDL_FreeSurface(surface); } } Font::~Font() { } float Font::get_text_width(const std::string& text) const { float curr_width = 0; float last_width = 0; for(UTF8Iterator it(text); !it.done(); ++it) { if (*it == '\n') { last_width = std::max(last_width, curr_width); curr_width = 0; } else { if( glyphs.at(*it).surface_idx != -1 ) curr_width += glyphs[*it].advance; else curr_width += glyphs[0x20].advance; } } return std::max(curr_width, last_width); } float Font::get_text_height(const std::string& text) const { std::string::size_type text_height = char_height; for(std::string::const_iterator it = text.begin(); it != text.end(); ++it) { // since UTF8 multibyte characters are decoded with values // outside the ASCII range there is no risk of overlapping and // thus we don't need to decode the utf-8 string if (*it == '\n') text_height += char_height + 2; } return text_height; } float Font::get_height() const { return char_height; } std::string Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow) { // if text is already smaller, return full text if ((int)s.length() <= line_length) { if (overflow) *overflow = ""; return s; } // if we can find a whitespace character to break at, return text up to this character int i = line_length; while ((i > 0) && (s[i] != ' ')) i--; if (i > 0) { if (overflow) *overflow = s.substr(i+1); return s.substr(0, i); } // FIXME: wrap at line_length, taking care of multibyte characters if (overflow) *overflow = ""; return s; } std::string Font::wrap_to_width(const std::string& s_, float width, std::string* overflow) { std::string s = s_; // if text is already smaller, return full text if (get_text_width(s) <= width) { if (overflow) *overflow = ""; return s; } // if we can find a whitespace character to break at, return text up to this character for (int i = s.length()-1; i >= 0; i--) { std::string s2 = s.substr(0,i); if (s[i] != ' ') continue; if (get_text_width(s2) <= width) { if (overflow) *overflow = s.substr(i+1); return s.substr(0, i); } } // FIXME: hard-wrap at width, taking care of multibyte characters if (overflow) *overflow = ""; return s; } void Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_, FontAlignment alignment, DrawingEffect drawing_effect, Color color, float alpha) const { float x = pos_.x; float y = pos_.y; std::string::size_type last = 0; for(std::string::size_type i = 0;; ++i) { if (text[i] == '\n' || i == text.size()) { std::string temp = text.substr(last, i - last); // calculate X positions based on the alignment type Vector pos = Vector(x, y); if(alignment == ALIGN_CENTER) pos.x -= get_text_width(temp) / 2; else if(alignment == ALIGN_RIGHT) pos.x -= get_text_width(temp); // Cast font position to integer to get a clean drawing result and // no blurring as we would get with subpixel positions pos.x = static_cast<int>(pos.x); draw_text(renderer, temp, pos, drawing_effect, color, alpha); if (i == text.size()) break; y += char_height + 2; last = i + 1; } } } void Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos, DrawingEffect drawing_effect, Color color, float alpha) const { if(shadowsize > 0) draw_chars(renderer, false, rtl ? std::string(text.rbegin(), text.rend()) : text, pos + Vector(shadowsize, shadowsize), drawing_effect, Color(1,1,1), alpha); draw_chars(renderer, true, rtl ? std::string(text.rbegin(), text.rend()) : text, pos, drawing_effect, color, alpha); } void Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text, const Vector& pos, DrawingEffect drawing_effect, Color color, float alpha) const { Vector p = pos; for(UTF8Iterator it(text); !it.done(); ++it) { if(*it == '\n') { p.x = pos.x; p.y += char_height + 2; } else if(*it == ' ') { p.x += glyphs[0x20].advance; } else { Glyph glyph; if( glyphs.at(*it).surface_idx != -1 ) glyph = glyphs[*it]; else glyph = glyphs[0x20]; DrawingRequest request; request.pos = p + glyph.offset; request.drawing_effect = drawing_effect; request.color = color; request.alpha = alpha; SurfacePartRequest surfacepartrequest; surfacepartrequest.srcrect = glyph.rect; surfacepartrequest.dstsize = glyph.rect.get_size(); surfacepartrequest.surface = notshadow ? glyph_surfaces[glyph.surface_idx].get() : shadow_surfaces[glyph.surface_idx].get(); request.request_data = &surfacepartrequest; renderer->draw_surface_part(request); p.x += glyph.advance; } } } /* EOF */
GrumbelsTrashbin/supertux.auto_export
src/video/font.cpp
C++
gpl-3.0
12,765
/* * Copyright (c) 2018, Psiphon Inc. * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ // Package accesscontrol implements an access control authorization scheme // based on digital signatures. // // Authorizations for specified access types are issued by an entity that // digitally signs each authorization. The digital signature is verified // by service providers before granting the specified access type. Each // authorization includes an expiry date and a unique ID that may be used // to mitigate malicious reuse/sharing of authorizations. // // In a typical deployment, the signing keys will be present on issuing // entities which are distinct from service providers. Only verification // keys will be deployed to service providers. // // An authorization is represented in JSON, which is then base64-encoded // for transport: // // { // "Authorization" : { // "ID" : <derived unique ID>, // "AccessType" : <access type name; e.g., "my-access">, // "Expires" : <RFC3339-encoded UTC time value> // }, // "SigningKeyID" : <unique key ID>, // "Signature" : <Ed25519 digital signature> // } // package accesscontrol import ( "crypto/ed25519" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/json" "io" "time" "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors" "golang.org/x/crypto/hkdf" ) const ( keyIDLength = 32 authorizationIDKeyLength = 32 authorizationIDLength = 32 ) // SigningKey is the private key used to sign newly issued // authorizations for the specified access type. The key ID // is included in authorizations and identifies the // corresponding verification keys. // // AuthorizationIDKey is used to produce a unique // authentication ID that cannot be mapped back to its seed // value. type SigningKey struct { ID []byte AccessType string AuthorizationIDKey []byte PrivateKey []byte } // VerificationKey is the public key used to verify signed // authentications issued for the specified access type. The // authorization references the expected public key by ID. type VerificationKey struct { ID []byte AccessType string PublicKey []byte } // NewKeyPair generates a new authorization signing key pair. func NewKeyPair( accessType string) (*SigningKey, *VerificationKey, error) { ID := make([]byte, keyIDLength) _, err := rand.Read(ID) if err != nil { return nil, nil, errors.Trace(err) } authorizationIDKey := make([]byte, authorizationIDKeyLength) _, err = rand.Read(authorizationIDKey) if err != nil { return nil, nil, errors.Trace(err) } publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) if err != nil { return nil, nil, errors.Trace(err) } signingKey := &SigningKey{ ID: ID, AccessType: accessType, AuthorizationIDKey: authorizationIDKey, PrivateKey: privateKey, } verificationKey := &VerificationKey{ ID: ID, AccessType: accessType, PublicKey: publicKey, } return signingKey, verificationKey, nil } // Authorization describes an authorization, with a unique ID, // granting access to a specified access type, and expiring at // the specified time. // // An Authorization is embedded within a digitally signed // object. This wrapping object adds a signature and a signing // key ID. type Authorization struct { ID []byte AccessType string Expires time.Time } type signedAuthorization struct { Authorization json.RawMessage SigningKeyID []byte Signature []byte } // ValidateSigningKey checks that a signing key is correctly configured. func ValidateSigningKey(signingKey *SigningKey) error { if len(signingKey.ID) != keyIDLength || len(signingKey.AccessType) < 1 || len(signingKey.AuthorizationIDKey) != authorizationIDKeyLength || len(signingKey.PrivateKey) != ed25519.PrivateKeySize { return errors.TraceNew("invalid signing key") } return nil } // IssueAuthorization issues an authorization signed with the // specified signing key. // // seedAuthorizationID should be a value that uniquely identifies // the purchase, subscription, or transaction that backs the // authorization; a distinct unique authorization ID will be derived // from the seed without revealing the original value. The authorization // ID is to be used to mitigate malicious authorization reuse/sharing. // // The first return value is a base64-encoded, serialized JSON representation // of the signed authorization that can be passed to VerifyAuthorization. The // second return value is the unique ID of the signed authorization returned in // the first value. func IssueAuthorization( signingKey *SigningKey, seedAuthorizationID []byte, expires time.Time) (string, []byte, error) { err := ValidateSigningKey(signingKey) if err != nil { return "", nil, errors.Trace(err) } hkdf := hkdf.New(sha256.New, signingKey.AuthorizationIDKey, nil, seedAuthorizationID) ID := make([]byte, authorizationIDLength) _, err = io.ReadFull(hkdf, ID) if err != nil { return "", nil, errors.Trace(err) } auth := Authorization{ ID: ID, AccessType: signingKey.AccessType, Expires: expires.UTC(), } authJSON, err := json.Marshal(auth) if err != nil { return "", nil, errors.Trace(err) } signature := ed25519.Sign(signingKey.PrivateKey, authJSON) signedAuth := signedAuthorization{ Authorization: authJSON, SigningKeyID: signingKey.ID, Signature: signature, } signedAuthJSON, err := json.Marshal(signedAuth) if err != nil { return "", nil, errors.Trace(err) } encodedSignedAuth := base64.StdEncoding.EncodeToString(signedAuthJSON) return encodedSignedAuth, ID, nil } // VerificationKeyRing is a set of verification keys to be deployed // to a service provider for verifying access authorizations. type VerificationKeyRing struct { Keys []*VerificationKey } // ValidateVerificationKeyRing checks that a verification key ring is // correctly configured. func ValidateVerificationKeyRing(keyRing *VerificationKeyRing) error { for _, key := range keyRing.Keys { if len(key.ID) != keyIDLength || len(key.AccessType) < 1 || len(key.PublicKey) != ed25519.PublicKeySize { return errors.TraceNew("invalid verification key") } } return nil } // VerifyAuthorization verifies the signed authorization and, when // verified, returns the embedded Authorization struct with the // access control information. // // The key ID in the signed authorization is used to select the // appropriate verification key from the key ring. func VerifyAuthorization( keyRing *VerificationKeyRing, encodedSignedAuthorization string) (*Authorization, error) { err := ValidateVerificationKeyRing(keyRing) if err != nil { return nil, errors.Trace(err) } signedAuthorizationJSON, err := base64.StdEncoding.DecodeString( encodedSignedAuthorization) if err != nil { return nil, errors.Trace(err) } var signedAuth signedAuthorization err = json.Unmarshal(signedAuthorizationJSON, &signedAuth) if err != nil { return nil, errors.Trace(err) } if len(signedAuth.SigningKeyID) != keyIDLength { return nil, errors.TraceNew("invalid key ID length") } if len(signedAuth.Signature) != ed25519.SignatureSize { return nil, errors.TraceNew("invalid signature length") } var verificationKey *VerificationKey for _, key := range keyRing.Keys { if subtle.ConstantTimeCompare(signedAuth.SigningKeyID, key.ID) == 1 { verificationKey = key } } if verificationKey == nil { return nil, errors.TraceNew("invalid key ID") } if !ed25519.Verify( verificationKey.PublicKey, signedAuth.Authorization, signedAuth.Signature) { return nil, errors.TraceNew("invalid signature") } var auth Authorization err = json.Unmarshal(signedAuth.Authorization, &auth) if err != nil { return nil, errors.Trace(err) } if len(auth.ID) == 0 { return nil, errors.TraceNew("invalid authorization ID") } if auth.AccessType != verificationKey.AccessType { return nil, errors.TraceNew("invalid access type") } if auth.Expires.IsZero() { return nil, errors.TraceNew("invalid expiry") } if auth.Expires.Before(time.Now().UTC()) { return nil, errors.TraceNew("expired authorization") } return &auth, nil }
Psiphon-Labs/psiphon-tunnel-core
psiphon/common/accesscontrol/accesscontrol.go
GO
gpl-3.0
8,880
/* * Copyright (c) 2010-2012 Thiago T. Sá * * This file is part of CloudReports. * * CloudReports 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. * * CloudReports 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. * * For more information about your rights as a user of CloudReports, * refer to the LICENSE file or see <http://www.gnu.org/licenses/>. */ package cloudreports.gui; import java.awt.Component; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * A helper class that generates customizable dialogs. * * @author Thiago T. Sá * @since 1.0 */ public class Dialog { /** * Shows a warning message. * * @param parent the parent component of the dialog. * @param message the message to be shown. * @since 1.0 */ public static void showWarning(Component parent, String message) { JOptionPane.showMessageDialog(parent, message, "Warning", JOptionPane.INFORMATION_MESSAGE, new javax.swing.ImageIcon(ImageIcon.class.getResource("/cloudreports/gui/resources/warning.png"))); } /** * Shows an information message. * * @param parent the parent component of the dialog. * @param message the message to be shown. * @since 1.0 */ public static void showInfo(Component parent, String message) { JOptionPane.showMessageDialog(parent, message, "Information", JOptionPane.INFORMATION_MESSAGE, new javax.swing.ImageIcon(ImageIcon.class.getResource("/cloudreports/gui/resources/biginfo.png"))); } /** * Shows an error message. * * @param parent the parent component of the dialog. * @param message the message to be shown. * @since 1.0 */ public static void showErrorMessage(Component parent, String message) { JOptionPane.showMessageDialog(parent, message, "Error", JOptionPane.ERROR_MESSAGE, new javax.swing.ImageIcon(ImageIcon.class.getResource("/cloudreports/gui/resources/error.png"))); } /** * Shows an success message. * * @param parent the parent component of the dialog. * @param message the message to be shown. * @since 1.0 */ public static void showSuccessMessage(Component parent, String message) { JOptionPane.showMessageDialog(parent, message, "Information", JOptionPane.INFORMATION_MESSAGE, new javax.swing.ImageIcon(ImageIcon.class.getResource("/cloudreports/gui/resources/success.png"))); } /** * Shows a dialog with a question. * * @param parent the parent component of the dialog. * @param title the title of the dialog. * @param question the question to be shown. * @since 1.0 */ public static int showQuestionDialog(Component parent, String title, String question) { Object[] options = {"Cancel", "Yes"}; int n = JOptionPane.showOptionDialog(parent, question, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new javax.swing.ImageIcon(ImageIcon.class.getResource("/cloudreports/gui/resources/question.png")), options, options[0]); return n; } }
thiagotts/CloudReports
src/main/java/cloudreports/gui/Dialog.java
Java
gpl-3.0
4,355
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Win32; namespace RemotePotatoServer { public class MCLibraryFolderHelper { public MCLibraryFolderHelper() { } public enum Libraries { Image, Movie, Video } public List<string> MediaCenterLibraryFolders(Libraries library) { List<string> output = new List<string>(); RegistryKey rkRoot = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Media Center\\MediaFolders\\" + library.ToString() + "\\", false); if (rkRoot == null) return output; // NO folders object oFolderCount = rkRoot.GetValue("FolderCount"); if (oFolderCount == null) return output; // No folders int folderCount = (int)oFolderCount; if (folderCount > 0) { for (int i = 0; i < folderCount; i++) { object oFolderName = rkRoot.GetValue("Folder" + i.ToString()); if (oFolderName != null) { string sFolderName = (string)oFolderName; output.Add(sFolderName); } } } return output; } } }
isawred2/RemotePotatoLiveTV
Server/RPServer/Code/FileBrowsing/MCLibraryFolderHelper.cs
C#
gpl-3.0
1,369
/* * Copyright (C) 2011 Hans Vandierendonck (hvandierendonck@acm.org) * Copyright (C) 2011 George Tzenakis (tzenakis@ics.forth.gr) * Copyright (C) 2011 Dimitrios S. Nikolopoulos (dsn@ics.forth.gr) * * This file is part of Swan. * * Swan 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. * * Swan 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 Swan. If not, see <http://www.gnu.org/licenses/>. */ // -*- c++ -*- #include <cstdlib> #include <cstring> #include <cassert> #include <iostream> #include "wf_interface.h" #include "logger.h" using namespace obj; pthread_mutex_t io_lock_var; void iolock() { pthread_mutex_lock( &io_lock_var ); } void iounlock() { pthread_mutex_unlock( &io_lock_var ); } int my_main( int argc, char * argv[] ); /* int f( int n, outdep<char> obj ) __attribute__((noinline)); int g( int n, indep<char> obj ) __attribute__((noinline)); int f( int n, outdep<char> obj ) { if( n == 1 ) usleep(10000); else usleep(100000); iolock(); std::cerr << "This is the f function with n=" << n << " object=" << *obj.get_object() << " ptr=" << obj.get_ptr<int>() << "\n"; iounlock(); return n; } int g( int n, indep obj ) { iolock(); std::cerr << "This is the g function with n=" << n << " object=" << *obj.get_object() << " ptr=" << obj.get_ptr<int>() << "\n"; iounlock(); return n; } */ int stage_a( int i, outdep<float> ab ) { float * f = ab.get_ptr(); *f = float(i); iolock(); std::cerr << "stage A: f in=" << f << " " << *ab.get_version() << '\n'; iounlock(); return 0; } int stage_b( indep<float> ab, outdep<int> bc ) { float * f = ab.get_ptr(); int * i = bc.get_ptr(); *i = int(*f); iolock(); std::cerr << "stage B: i=" << *i << " in " << i << ' ' << *bc.get_version() << " and f in " << f << " " << *ab.get_version() << '\n'; iounlock(); return 0; } int stage_c( indep<int> bc ) { static int seen[100] = { 0 }; int * i = bc.get_ptr(); iolock(); std::cerr << "stage C: i=" << *i << " in " << i << ' ' << *bc.get_version() << '\n'; iounlock(); assert( seen[*i] == 0 ); seen[*i] = 1; return 0; } void apipe( int n ) { object_t<float> obj_ab = object_t<float>::create( 1 ); object_t<int> obj_bc = object_t<int>::create( 1 ); chandle<int> ka[n], kb[n], kc[n]; *obj_ab.get_ptr() = -1.0; *obj_bc.get_ptr() = -1; for( int i=0; i < n; ++i ) { spawn( stage_a, ka[i], i, (outdep<float>)obj_ab ); // iolock(); std::cerr << "Between A and B\n"; iounlock(); spawn( stage_b, kb[i], (indep<float>)obj_ab, (outdep<int>)obj_bc ); // iolock(); std::cerr << "Between B and C\n"; iounlock(); spawn( stage_c, kc[i], (indep<int>)obj_bc ); // iolock(); std::cerr << "Between C and A\n"; iounlock(); } ssync(); } int my_main( int argc, char * argv[] ) { pthread_mutex_init( &io_lock_var, NULL ); if( argc <= 1 ) { std::cerr << "Usage: " << argv[0] << " <n>\n"; return 1; } int n = atoi( argv[1] ); object_t<char> obj = object_t<char>::create( 128 ); std::cerr << "obj=" << obj << "\n"; /* chandle<int> k, l, m; spawn( f, k, n, (outdep)obj ); spawn( f, m, 1, (outdep)obj ); spawn( g, l, n, (indep)obj ); ssync(); std::cerr << "f(" << n << ", " << obj << ") = " << k << "\n"; */ call( apipe, n ); return 0; }
hvdieren/swan
tests/exobject.cc
C++
gpl-3.0
3,826
/** * Copyright (C) 2013-2014 Project-Vethrfolnir * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.vethrfolnir.game.controllers; import gnu.trove.map.hash.TIntObjectHashMap; import com.vethrfolnir.game.entitys.GameObject; /** * @author Vlad * */ public class NpcController { private TIntObjectHashMap<NpcController.Controller> controllers = new TIntObjectHashMap<>(); @SuppressWarnings("unchecked") public <T extends Controller> T getController(int npcId, Class<T> type) { Controller obj = controllers.get(npcId); if(type.isInstance(obj)) return (T) obj; return null; } public void register(NpcController.Controller con, int... npcIds) { for (int i = 0; i < npcIds.length; i++) { int npcId = npcIds[i]; controllers.put(npcId, con); } } public void remove(int npcId) { controllers.remove(npcId); } public int size() { return controllers.size(); } public interface Controller { } public interface ActionController extends Controller { // for initial public void action(int npcId, GameObject player, GameObject npc); } }
Setekh/vethrfolnir-mu
src/main/game-core/com/vethrfolnir/game/controllers/NpcController.java
Java
gpl-3.0
1,769
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Jeroen Hoekx <jeroen@hoekx.be> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. import binascii import datetime import math import re import select import socket import sys import time HAS_PSUTIL = False try: import psutil HAS_PSUTIL = True # just because we can import it on Linux doesn't mean we will use it except ImportError: pass DOCUMENTATION = ''' --- module: wait_for short_description: Waits for a condition before continuing. description: - You can wait for a set amount of time C(timeout), this is the default if nothing is specified. - Waiting for a port to become available is useful for when services are not immediately available after their init scripts return which is true of certain Java application servers. It is also useful when starting guests with the M(virt) module and needing to pause until they are ready. - This module can also be used to wait for a regex match a string to be present in a file. - In 1.6 and later, this module can also be used to wait for a file to be available or absent on the filesystem. - In 1.8 and later, this module can also be used to wait for active connections to be closed before continuing, useful if a node is being rotated out of a load balancer pool. version_added: "0.7" options: host: description: - A resolvable hostname or IP address to wait for required: false default: "127.0.0.1" timeout: description: - maximum number of seconds to wait for required: false default: 300 connect_timeout: description: - maximum number of seconds to wait for a connection to happen before closing and retrying required: false default: 5 delay: description: - number of seconds to wait before starting to poll required: false default: 0 port: description: - port number to poll required: false state: description: - either C(present), C(started), or C(stopped), C(absent), or C(drained) - When checking a port C(started) will ensure the port is open, C(stopped) will check that it is closed, C(drained) will check for active connections - When checking for a file or a search string C(present) or C(started) will ensure that the file or string is present before continuing, C(absent) will check that file is absent or removed choices: [ "present", "started", "stopped", "absent", "drained" ] default: "started" path: version_added: "1.4" required: false description: - path to a file on the filesytem that must exist before continuing search_regex: version_added: "1.4" required: false description: - Can be used to match a string in either a file or a socket connection. Defaults to a multiline regex. exclude_hosts: version_added: "1.8" required: false description: - list of hosts or IPs to ignore when looking for active TCP connections for C(drained) state notes: - The ability to use search_regex with a port connection was added in 1.7. requirements: [] author: - "Jeroen Hoekx (@jhoekx)" - "John Jarvis (@jarv)" - "Andrii Radyk (@AnderEnder)" ''' EXAMPLES = ''' # wait 300 seconds for port 8000 to become open on the host, don't start checking for 10 seconds - wait_for: port=8000 delay=10 # wait 300 seconds for port 8000 of any IP to close active connections, don't start checking for 10 seconds - wait_for: host=0.0.0.0 port=8000 delay=10 state=drained # wait 300 seconds for port 8000 of any IP to close active connections, ignoring connections for specified hosts - wait_for: host=0.0.0.0 port=8000 state=drained exclude_hosts=10.2.1.2,10.2.1.3 # wait until the file /tmp/foo is present before continuing - wait_for: path=/tmp/foo # wait until the string "completed" is in the file /tmp/foo before continuing - wait_for: path=/tmp/foo search_regex=completed # wait until the lock file is removed - wait_for: path=/var/lock/file.lock state=absent # wait until the process is finished and pid was destroyed - wait_for: path=/proc/3466/status state=absent # wait 300 seconds for port 22 to become open and contain "OpenSSH", don't assume the inventory_hostname is resolvable # and don't start checking for 10 seconds - local_action: wait_for port=22 host="{{ ansible_ssh_host | default(inventory_hostname) }}" search_regex=OpenSSH delay=10 ''' class TCPConnectionInfo(object): """ This is a generic TCP Connection Info strategy class that relies on the psutil module, which is not ideal for targets, but necessary for cross platform support. A subclass may wish to override some or all of these methods. - _get_exclude_ips() - get_active_connections() All subclasses MUST define platform and distribution (which may be None). """ platform = 'Generic' distribution = None match_all_ips = { socket.AF_INET: '0.0.0.0', socket.AF_INET6: '::', } ipv4_mapped_ipv6_address = { 'prefix': '::ffff', 'match_all': '::ffff:0.0.0.0' } connection_states = { '01': 'ESTABLISHED', '02': 'SYN_SENT', '03': 'SYN_RECV', '04': 'FIN_WAIT1', '05': 'FIN_WAIT2', '06': 'TIME_WAIT', } def __new__(cls, *args, **kwargs): return load_platform_subclass(TCPConnectionInfo, args, kwargs) def __init__(self, module): self.module = module self.ips = _convert_host_to_ip(module.params['host']) self.port = int(self.module.params['port']) self.exclude_ips = self._get_exclude_ips() if not HAS_PSUTIL: module.fail_json(msg="psutil module required for wait_for") def _get_exclude_ips(self): exclude_hosts = self.module.params['exclude_hosts'] exclude_ips = [] if exclude_hosts is not None: for host in exclude_hosts: exclude_ips.extend(_convert_host_to_ip(host)) return exclude_ips def get_active_connections_count(self): active_connections = 0 for p in psutil.process_iter(): connections = p.get_connections(kind='inet') for conn in connections: if conn.status not in self.connection_states.values(): continue (local_ip, local_port) = conn.local_address if self.port != local_port: continue (remote_ip, remote_port) = conn.remote_address if (conn.family, remote_ip) in self.exclude_ips: continue if any(( (conn.family, local_ip) in self.ips, (conn.family, self.match_all_ips[conn.family]) in self.ips, local_ip.startswith(self.ipv4_mapped_ipv6_address['prefix']) and (conn.family, self.ipv4_mapped_ipv6_address['match_all']) in self.ips, )): active_connections += 1 return active_connections # =========================================== # Subclass: Linux class LinuxTCPConnectionInfo(TCPConnectionInfo): """ This is a TCP Connection Info evaluation strategy class that utilizes information from Linux's procfs. While less universal, does allow Linux targets to not require an additional library. """ platform = 'Linux' distribution = None source_file = { socket.AF_INET: '/proc/net/tcp', socket.AF_INET6: '/proc/net/tcp6' } match_all_ips = { socket.AF_INET: '00000000', socket.AF_INET6: '00000000000000000000000000000000', } ipv4_mapped_ipv6_address = { 'prefix': '0000000000000000FFFF0000', 'match_all': '0000000000000000FFFF000000000000' } local_address_field = 1 remote_address_field = 2 connection_state_field = 3 def __init__(self, module): self.module = module self.ips = _convert_host_to_hex(module.params['host']) self.port = "%0.4X" % int(module.params['port']) self.exclude_ips = self._get_exclude_ips() def _get_exclude_ips(self): exclude_hosts = self.module.params['exclude_hosts'] exclude_ips = [] if exclude_hosts is not None: for host in exclude_hosts: exclude_ips.extend(_convert_host_to_hex(host)) return exclude_ips def get_active_connections_count(self): active_connections = 0 for family in self.source_file.keys(): f = open(self.source_file[family]) for tcp_connection in f.readlines(): tcp_connection = tcp_connection.strip().split() if tcp_connection[self.local_address_field] == 'local_address': continue if tcp_connection[self.connection_state_field] not in self.connection_states: continue (local_ip, local_port) = tcp_connection[self.local_address_field].split(':') if self.port != local_port: continue (remote_ip, remote_port) = tcp_connection[self.remote_address_field].split(':') if (family, remote_ip) in self.exclude_ips: continue if any(( (family, local_ip) in self.ips, (family, self.match_all_ips[family]) in self.ips, local_ip.startswith(self.ipv4_mapped_ipv6_address['prefix']) and (family, self.ipv4_mapped_ipv6_address['match_all']) in self.ips, )): active_connections += 1 f.close() return active_connections def _convert_host_to_ip(host): """ Perform forward DNS resolution on host, IP will give the same IP Args: host: String with either hostname, IPv4, or IPv6 address Returns: List of tuples containing address family and IP """ addrinfo = socket.getaddrinfo(host, 80, 0, 0, socket.SOL_TCP) ips = [] for family, socktype, proto, canonname, sockaddr in addrinfo: ip = sockaddr[0] ips.append((family, ip)) if family == socket.AF_INET: ips.append((socket.AF_INET6, "::ffff:" + ip)) return ips def _convert_host_to_hex(host): """ Convert the provided host to the format in /proc/net/tcp* /proc/net/tcp uses little-endian four byte hex for ipv4 /proc/net/tcp6 uses little-endian per 4B word for ipv6 Args: host: String with either hostname, IPv4, or IPv6 address Returns: List of tuples containing address family and the little-endian converted host """ ips = [] if host is not None: for family, ip in _convert_host_to_ip(host): hexip_nf = binascii.b2a_hex(socket.inet_pton(family, ip)) hexip_hf = "" for i in range(0, len(hexip_nf), 8): ipgroup_nf = hexip_nf[i:i+8] ipgroup_hf = socket.ntohl(int(ipgroup_nf, base=16)) hexip_hf = "%s%08X" % (hexip_hf, ipgroup_hf) ips.append((family, hexip_hf)) return ips def _create_connection(host, port, connect_timeout): """ Connect to a 2-tuple (host, port) and return the socket object. Args: 2-tuple (host, port) and connection timeout Returns: Socket object """ if sys.version_info < (2, 6): (family, _) = _convert_host_to_ip(host) connect_socket = socket.socket(family, socket.SOCK_STREAM) connect_socket.settimeout(connect_timeout) connect_socket.connect( (host, port) ) else: connect_socket = socket.create_connection( (host, port), connect_timeout) return connect_socket def _timedelta_total_seconds(timedelta): return ( timedelta.microseconds + 0.0 + (timedelta.seconds + timedelta.days * 24 * 3600) * 10 ** 6) / 10 ** 6 def main(): module = AnsibleModule( argument_spec = dict( host=dict(default='127.0.0.1'), timeout=dict(default=300, type='int'), connect_timeout=dict(default=5, type='int'), delay=dict(default=0, type='int'), port=dict(default=None, type='int'), path=dict(default=None, type='path'), search_regex=dict(default=None), state=dict(default='started', choices=['started', 'stopped', 'present', 'absent', 'drained']), exclude_hosts=dict(default=None, type='list') ), ) params = module.params host = params['host'] timeout = params['timeout'] connect_timeout = params['connect_timeout'] delay = params['delay'] port = params['port'] state = params['state'] path = params['path'] search_regex = params['search_regex'] if search_regex is not None: compiled_search_re = re.compile(search_regex, re.MULTILINE) else: compiled_search_re = None if port and path: module.fail_json(msg="port and path parameter can not both be passed to wait_for") if path and state == 'stopped': module.fail_json(msg="state=stopped should only be used for checking a port in the wait_for module") if path and state == 'drained': module.fail_json(msg="state=drained should only be used for checking a port in the wait_for module") if params['exclude_hosts'] is not None and state != 'drained': module.fail_json(msg="exclude_hosts should only be with state=drained") start = datetime.datetime.now() if delay: time.sleep(delay) if not port and not path and state != 'drained': time.sleep(timeout) elif state in [ 'stopped', 'absent' ]: ### first wait for the stop condition end = start + datetime.timedelta(seconds=timeout) while datetime.datetime.now() < end: if path: try: f = open(path) f.close() time.sleep(1) pass except IOError: break elif port: try: s = _create_connection(host, port, connect_timeout) s.shutdown(socket.SHUT_RDWR) s.close() time.sleep(1) except: break else: time.sleep(1) else: elapsed = datetime.datetime.now() - start if port: module.fail_json(msg="Timeout when waiting for %s:%s to stop." % (host, port), elapsed=elapsed.seconds) elif path: module.fail_json(msg="Timeout when waiting for %s to be absent." % (path), elapsed=elapsed.seconds) elif state in ['started', 'present']: ### wait for start condition end = start + datetime.timedelta(seconds=timeout) while datetime.datetime.now() < end: if path: try: os.stat(path) except OSError, e: # If anything except file not present, throw an error if e.errno != 2: elapsed = datetime.datetime.now() - start module.fail_json(msg="Failed to stat %s, %s" % (path, e.strerror), elapsed=elapsed.seconds) # file doesn't exist yet, so continue else: # File exists. Are there additional things to check? if not compiled_search_re: # nope, succeed! break try: f = open(path) try: if re.search(compiled_search_re, f.read()): # String found, success! break finally: f.close() except IOError: pass elif port: alt_connect_timeout = math.ceil(_timedelta_total_seconds(end - datetime.datetime.now())) try: s = _create_connection(host, port, min(connect_timeout, alt_connect_timeout)) except: # Failed to connect by connect_timeout. wait and try again pass else: # Connected -- are there additional conditions? if compiled_search_re: data = '' matched = False while datetime.datetime.now() < end: max_timeout = math.ceil(_timedelta_total_seconds(end - datetime.datetime.now())) (readable, w, e) = select.select([s], [], [], max_timeout) if not readable: # No new data. Probably means our timeout # expired continue response = s.recv(1024) if not response: # Server shutdown break data += response if re.search(compiled_search_re, data): matched = True break # Shutdown the client socket s.shutdown(socket.SHUT_RDWR) s.close() if matched: # Found our string, success! break else: # Connection established, success! s.shutdown(socket.SHUT_RDWR) s.close() break # Conditions not yet met, wait and try again time.sleep(1) else: # while-else # Timeout expired elapsed = datetime.datetime.now() - start if port: if search_regex: module.fail_json(msg="Timeout when waiting for search string %s in %s:%s" % (search_regex, host, port), elapsed=elapsed.seconds) else: module.fail_json(msg="Timeout when waiting for %s:%s" % (host, port), elapsed=elapsed.seconds) elif path: if search_regex: module.fail_json(msg="Timeout when waiting for search string %s in %s" % (search_regex, path), elapsed=elapsed.seconds) else: module.fail_json(msg="Timeout when waiting for file %s" % (path), elapsed=elapsed.seconds) elif state == 'drained': ### wait until all active connections are gone end = start + datetime.timedelta(seconds=timeout) tcpconns = TCPConnectionInfo(module) while datetime.datetime.now() < end: try: if tcpconns.get_active_connections_count() == 0: break except IOError: pass time.sleep(1) else: elapsed = datetime.datetime.now() - start module.fail_json(msg="Timeout when waiting for %s:%s to drain" % (host, port), elapsed=elapsed.seconds) elapsed = datetime.datetime.now() - start module.exit_json(state=state, port=port, search_regex=search_regex, path=path, elapsed=elapsed.seconds) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
sysadmin75/ansible-modules-core
utilities/logic/wait_for.py
Python
gpl-3.0
20,316
using NLog; using System.Web.Mvc; namespace Web.Attributes { public class GlobalHandleErrorAttribute : HandleErrorAttribute { private static readonly Logger Nlog = LogManager.GetCurrentClassLogger(); public override void OnException(ExceptionContext filterContext) { Nlog.Log(LogLevel.Error, filterContext.Exception); base.OnException(filterContext); } } }
goiwebdev/accountgo
src/Web/Attributes/GlobalHandleErrorAttribute.cs
C#
gpl-3.0
429
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // extrait automatiquement de http://trad.spip.net/tradlang_module/ecrire_?lang_cible=es // ** ne pas modifier le fichier ** if (!defined('_ECRIRE_INC_VERSION')) { return; } $GLOBALS[$GLOBALS['idx_lang']] = array( // A 'activer_plugin' => 'Activar el plugin', 'affichage' => 'Visualización', 'aide_non_disponible' => 'Esta parte de la ayuda en línea aún no está disponible en este idioma.', 'annuler_recherche' => 'Cancelar la búsqueda', 'auteur' => 'Autor/a:', 'avis_acces_interdit' => 'Acceso prohibido.', 'avis_article_modifie' => 'Atención: @nom_auteur_modif@ ha modificado este artículo hace @date_diff@ minutos', 'avis_aucun_resultat' => 'Ningún resultado.', 'avis_base_inaccessible' => 'No se puede conectar a la base de datos @base@.', 'avis_chemin_invalide_1' => 'Ruta de acceso seleccionada', 'avis_chemin_invalide_2' => 'no parece válido. Regrese a la página precedente y compruebe las informaciones procuradas.', 'avis_connexion_echec_1' => 'La conexión con la base de datos ha fallado.', 'avis_connexion_echec_2' => 'Regresa a la página precedente y verifica las informaciones procuradas.', 'avis_connexion_echec_3' => '<b>Aviso:</b> En muchos servidores, es necesario <b>solicitar</b> la activación del acceso a la base de datos SQL antes de poder usarla. En caso de no poder conectarse a la base de datos, compruebe que se ha realizado la activación.', 'avis_connexion_erreur_creer_base' => 'La base de datos no se ha podido crear', 'avis_connexion_erreur_nom_base' => 'El nombre de la base sólo puede contener letras, dígitos y guiones.', 'avis_connexion_ldap_echec_1' => 'La conexión al servidor LDAP ha fallado.', 'avis_connexion_ldap_echec_2' => 'Regrese a la página anterior y compruebe la información procurada.', 'avis_connexion_ldap_echec_3' => 'Alternativamente, no utilice el soporte LDAP para importar usuarios.', 'avis_deplacement_rubrique' => '¡ATENCIÓN! Esta sección contiene @contient_breves@ breve@scb@. Si la desplaza, active esta casilla de confirmación.', 'avis_erreur_connexion_mysql' => 'Error de conexión SQL', 'avis_espace_interdit' => '<b>Espacio prohibido</b><div>SPIP ya está instalado.</div>', 'avis_lecture_noms_bases_1' => 'El programa de instalación no logró leer los nombres de las bases de datos instaladas.', 'avis_lecture_noms_bases_2' => 'Dos posibilidades: o no hay ninguna base disponible o la función de listado de las bases fue desactivada por razones de seguridad (caso frecuente en muchos hospedajes).', 'avis_lecture_noms_bases_3' => 'En el segundo caso, es probable que una base que tenga como nombre su identificador de usuario sea utilizable:', 'avis_non_acces_page' => 'No tiene acceso a esta página.', 'avis_operation_echec' => 'La operación ha fallado.', 'avis_operation_impossible' => 'Operación imposible', 'avis_suppression_base' => '¡ATENCIÓN, la supresión de datos es irreversible!', // B 'bouton_acces_ldap' => 'Añadir un acceso LDAP', 'bouton_ajouter' => 'Añadir', 'bouton_annuler' => 'Anular', 'bouton_cache_activer' => 'Reactivar la caché', 'bouton_cache_desactiver' => 'Desactivar temporalmente la caché', 'bouton_demande_publication' => 'Pedir la publicación de este artículo', 'bouton_desactive_tout' => 'Desactivar todo', 'bouton_desinstaller' => 'Desinstalar', 'bouton_effacer_tout' => '¡Borrar TODO!', 'bouton_envoyer_message' => 'Mensaje definitivo: enviar', 'bouton_fermer' => 'Cerrar', 'bouton_mettre_a_jour_base' => 'Actualizar la base de datos', 'bouton_modifier' => 'Modificar', 'bouton_radio_afficher' => 'Mostrar', 'bouton_radio_apparaitre_liste_redacteurs_connectes' => 'Aparecer en la lista de redactores y redactoras conectados', 'bouton_radio_envoi_annonces_adresse' => 'Enviar los anuncios a la dirección:', 'bouton_radio_envoi_liste_nouveautes' => 'Enviar la lista de novedades', 'bouton_radio_non_apparaitre_liste_redacteurs_connectes' => 'No aparecer en la lista de redactores y redactoras', 'bouton_radio_non_envoi_annonces_editoriales' => 'No enviar anuncios editoriales', 'bouton_redirection' => 'Redirección', 'bouton_relancer_installation' => 'Relanzar la instalación', 'bouton_suivant' => 'Siguiente', 'bouton_tenter_recuperation' => 'Intentar reparar', 'bouton_test_proxy' => 'Probar el proxy', 'bouton_vider_cache' => 'Vaciar la caché', // C 'cache_modifiable_webmestre' => 'Este parámetro es modificable por la webmistress del sitio.', 'calendrier_synchro' => 'Si utiliza un software de agenda compatible <b>iCal</b>, puede sincronizarlo con la actualidad editorial de este sitio.', 'config_activer_champs' => 'Activar los campos siguientes', 'config_choix_base_sup' => 'indicar una base de datos de este servidor', 'config_erreur_base_sup' => 'SPIP no tiene acceso a la lista de bases accesibles', 'config_info_base_sup' => 'Si dispone de otras bases de datos a consultar mediante SPIP, con su servidor SQL o con otro, el formulario siguiente permite declararlas. Si deja vacíos ciertos campos, se usarán los identificadores de la conexión a la base principal.', 'config_info_base_sup_disponibles' => 'Bases de datos suplementarias consultables:', 'config_info_enregistree' => 'La nueva configuración fue guardada', 'config_info_logos' => 'Cada elemento del sitio puede tener un logo, así como un « logo de paso del ratón »', 'config_info_logos_utiliser' => 'Utilizar los logos', 'config_info_logos_utiliser_non' => 'No utilizar los logos', 'config_info_logos_utiliser_survol' => 'Utilizar los logos de paso del ratón', 'config_info_logos_utiliser_survol_non' => 'No utilizar los logos de paso del ratón', 'config_info_redirection' => 'Activando esta opción, se podrán crear artículos virtuales, que son simples referencias de artículos publicados en otros sitios o fuera de SPIP.', 'config_redirection' => 'Artículos virtuales', 'config_titre_base_sup' => 'Declaración de una base suplementaria', 'config_titre_base_sup_choix' => 'Elige una base suplementaria', 'connexion_ldap' => 'Conexión:', 'creer_et_associer_un_auteur' => 'Crear y asociar un autor', // D 'date_mot_heures' => 'horas', // E 'ecran_securite' => ' + pantalla de seguridad @version@', 'email' => 'correo electrónico', 'email_2' => 'correo electrónico:', 'en_savoir_plus' => 'Más información', 'entree_adresse_annuaire' => 'Dirección del anuario', 'entree_adresse_email' => 'Tu correo electrónico', 'entree_adresse_email_2' => 'Dirección correo electrónico', 'entree_base_donnee_1' => 'Dirección de la base de datos', 'entree_base_donnee_2' => '(A menudo esta dirección corresponde a la de su sitio, a veces corresponde a la mención «localhost» y, en ocasiones, se deja totalmente vacía.)', 'entree_biographie' => 'Una corta biografía, en pocas palabras...', 'entree_chemin_acces' => '<b>Introducir</b> el camino de acceso:', 'entree_cle_pgp' => 'Su clave PGP', 'entree_cle_pgp_2' => 'Clave PGP', 'entree_contenu_rubrique' => '(Contenido de la sección en pocas palabras)', 'entree_identifiants_connexion' => 'Sus identificadores de conexión...', 'entree_identifiants_connexion_2' => 'Identificadores de conexión', 'entree_informations_connexion_ldap' => 'Escriba en este formulario los datos de conexión a su directorio LDAP. Tales informaciones le serán transmitidas por el administrador del sistema o de la red.', 'entree_infos_perso' => '¿Quién es usted?', 'entree_infos_perso_2' => '¿Quién es el/la autor/a?', 'entree_interieur_rubrique' => 'En el interior de la sección...', 'entree_liens_sites' => '<b>Enlace hipertexto </b>(referencia, sitio para visitar, ...)', 'entree_login' => 'Su nombre de usuario', 'entree_login_connexion_1' => 'Su identificador de conexión', 'entree_login_connexion_2' => '(A veces corresponde a su identificador de conexión; a veces se deja vacío)', 'entree_mot_passe' => 'Su contraseña', 'entree_mot_passe_1' => 'Su contraseña de conexión', 'entree_mot_passe_2' => '(A veces corresponde a tu contraseña FTP y a veces se deja en blanco)', 'entree_nom_fichier' => 'Introducir el nombre del archivo @texte_compresse@:', 'entree_nom_pseudo' => 'Su nombre o pseudónimo', 'entree_nom_pseudo_1' => '(Su nombre o pseudónimo)', 'entree_nom_pseudo_2' => 'Nombre o seudónimo', 'entree_nom_site' => 'El nombre de su sitio', 'entree_nom_site_2' => 'Nombre del sitio del/a autor/a', 'entree_nouveau_passe' => 'Nueva contraseña', 'entree_passe_ldap' => 'Tu contraseña', 'entree_port_annuaire' => 'El número de puerto del anuario', 'entree_signature' => 'Firma', 'entree_titre_obligatoire' => '<b>Título</b> [Obligatorio]<br />', 'entree_url' => 'La dirección (URL) de su sitio', 'entree_url_2' => 'Dirección (URL) del sitio', 'erreur_connect_deja_existant' => 'Ya existe un servidor con este nombre', 'erreur_email_deja_existant' => 'Esta dirección de correo electrónico ya esta registrada.', 'erreur_nom_connect_incorrect' => 'Este nombre de servidor no esta autorizado', 'erreur_plugin_attribut_balise_manquant' => 'Atributo @attribut@ que falta en la baliza @balise@.', 'erreur_plugin_desinstalation_echouee' => 'La desinstalación del plugin ha fracasado. No obstante, puede desactivarlo.', 'erreur_plugin_fichier_absent' => 'Archivo inexistente ', 'erreur_plugin_fichier_def_absent' => 'Archivo de definición inexistente', 'erreur_plugin_nom_fonction_interdit' => 'Nombre de función prohibido', 'erreur_plugin_nom_manquant' => 'Falta el nombre del plugin', 'erreur_plugin_prefix_manquant' => 'Espacio de nombres del plugin no definido', 'erreur_plugin_tag_plugin_absent' => 'Falta el &lt;plugin&gt; en el archivo de definición', 'erreur_plugin_version_manquant' => 'Falta la versión del plugin', // H 'htaccess_a_simuler' => 'Advertencia: la configuración de su servidor HTTP no toma en cuenta los archivos @htaccess@. Para poder asegurar una buena seguridad, debe modificar la configuración correspondiente, o bien que las constantes @constantes@ (que se pueden definir en el archivo mes_options.php) tomen valores de carpetas fuera de @document_root@.', 'htaccess_inoperant' => 'htaccess inoperante', // I 'ical_info1' => 'En esta página se presentan diferentes maneras de quedar en contacto con la vida del sitio.', 'ical_info2' => 'Para mayor información sobre todas estas técnicas, no dude en consultar <a href="@spipnet@">la documentación de SPIP</a>.', 'ical_info_calendrier' => 'Tiene dos calendarios a tu disposición. El primero es un plano del sitio que anuncia todos los artículos publicados. El segundo contiene los anuncios editoriales y sus últimos mensajes privados: sólo usted lo ve gracias a una clave personal, que podrá modificar en cualquier momento cambiando su contraseña.', 'ical_methode_http' => 'Descargar', 'ical_methode_webcal' => 'Sincronización (webcal://)', 'ical_texte_js' => 'Una línea de javascript le permite mostrar muy simplemente, en cualquier sitio que le pertenezca, los artículos recientes publicados en este sitio.', 'ical_texte_prive' => 'Este calendario, de uso estrictamente personal, le informa de la actividad editorial privada de este sitio (tareas y citas personales, artículos y breves propuestos...).', 'ical_texte_public' => 'Este calendario permite seguir la actividad pública del sitio (artículos y breves publicados).', 'ical_texte_rss' => 'Puede sindicar las novedades de este sitio con cualquier lector de archivos al formato XML/RSS (Rich Site Summary). Igualmente, SPIP puede leer las novedades publicadas en otros sitios que utilizan un formato de intercambio compatible (sitios sindicados). ', 'ical_titre_js' => 'Javascript', 'ical_titre_mailing' => 'Lista de correo', 'ical_titre_rss' => 'Archivos de sindicación', 'icone_accueil' => 'Mis tareas', 'icone_activer_cookie' => 'Activar la "cookie" de correspondencia', 'icone_activite' => 'Actividad', 'icone_admin_plugin' => 'Gestión de los plugins', 'icone_administration' => 'Administración', 'icone_afficher_auteurs' => 'Mostrar los autores', 'icone_afficher_visiteurs' => 'Mostrar los visitantes', 'icone_arret_discussion' => 'No participar más en este diálogo', 'icone_calendrier' => 'Calendario', 'icone_configuration' => 'Configuración', 'icone_creer_auteur' => 'Crear un nuevo autor o autora y asociarla a este artículo', 'icone_creer_mot_cle' => 'Crear una nueva palabra clave y asociarla a este artículo', 'icone_creer_rubrique_2' => 'Crear una nueva sección', 'icone_developpement' => 'Desarrollo', 'icone_edition' => 'Edición', 'icone_ma_langue' => 'Mi idioma', 'icone_mes_infos' => 'Mis datos', 'icone_mes_preferences' => 'Mis preferencias', 'icone_modifier_article' => 'Modificar este artículo', 'icone_modifier_rubrique' => 'Modificar esta sección', 'icone_publication' => 'Publicación', 'icone_relancer_signataire' => 'Recordar al firmante', 'icone_retour' => 'Volver', 'icone_retour_article' => 'Volver al artículo', 'icone_squelette' => 'Esqueletos', 'icone_suivi_publication' => 'Seguir la publicación', 'icone_supprimer_cookie' => 'Suprimir la "cookie" de correspondencia', 'icone_supprimer_rubrique' => 'Suprimir esta sección', 'icone_supprimer_signature' => 'Suprimir esta firma', 'icone_valider_signature' => 'Validar esta firma', 'image_administrer_rubrique' => 'Puedes administrar esta sección', 'info_1_article' => '1 artículo', 'info_1_auteur' => '1 autor/a', 'info_1_message' => '1 mensaje', 'info_1_mot_cle' => '1 palabra-clave', 'info_1_rubrique' => '1 sección', 'info_1_visiteur' => '1 visitante', 'info_activer_cookie' => 'Puede activar una <b>"cookie" de correspondencia</b>, que le permite actualizar páginas y pasar fácilmente de la parte pública a la redacción.', 'info_activer_menu_developpement' => 'Mostrar el menu desarrollo ', 'info_admin_etre_webmestre' => 'Darme derechos de webmaster', 'info_admin_je_suis_webmestre' => 'Soy <b>webmaster</b>', 'info_admin_statuer_webmestre' => 'Dar a este/a administrador/a derechos de webmaster', 'info_admin_webmestre' => 'Este/a administrador/a es <b>webmaster</b>', 'info_administrateur' => 'Administrador', 'info_administrateur_1' => 'Administrador', 'info_administrateur_2' => 'del sitio (<i>a utilizar con precaución</i>)', 'info_administrateur_site_01' => 'Si tiene derechos de administración, se ruega', 'info_administrateur_site_02' => 'presiona y visita este enlace', 'info_administrateurs' => 'Administradores', 'info_administrer_rubrique' => 'Puede administrar esta sección', 'info_adresse' => 'a la dirección:', 'info_adresse_desinscription' => 'Dirección para darse de baja:', 'info_adresse_url' => 'Dirección (URL) del sitio público', 'info_afficher_par_nb' => 'Visualizar por', 'info_aide_en_ligne' => 'Ayuda en línea de SPIP', 'info_ajout_image' => 'Cuando se añaden imágenes en tanto que documentos, SPIP puede crear automáticamente iconos de estas imágenes insertadas (miniaturas). Resulta útil, por ejemplo, para crear una galería o portafolio.', 'info_ajouter_rubrique' => 'Añadir otra sección para administrar:', 'info_annonce_nouveautes' => 'Anunciar novedades', 'info_article' => 'artículo', 'info_article_2' => 'artículos', 'info_article_a_paraitre' => 'Los artículos con fecha posterior a ser publicados', 'info_articles_02' => 'artículos', 'info_articles_2' => 'Artículos', 'info_articles_auteur' => 'Los artículos de este autor o autora', 'info_articles_miens' => 'Mis artículos', 'info_articles_tous' => 'Todos los artículos', 'info_articles_trouves' => 'Artículos localizados', 'info_attente_validation' => 'Sus artículos en espera de validación', 'info_aucun_article' => 'Ningún artículo', 'info_aucun_auteur' => 'Ningún autor', 'info_aucun_message' => 'Ningún mensaje', 'info_aucun_rubrique' => 'Ninguna sección', 'info_aujourdhui' => 'hoy:', 'info_auteur_gere_rubriques' => 'Este autor gestiona las secciones siguientes :', 'info_auteur_gere_toutes_rubriques' => 'este autor gestiona <b>todas las secciones</b>', 'info_auteur_gere_toutes_rubriques_2' => 'yo gestiono <b>todas las secciones</b>', 'info_auteurs' => 'Autores', 'info_auteurs_par_tri' => 'Autores@partri@', 'info_auteurs_trouves' => 'Autores encontrados', 'info_authentification_externe' => 'Autentificación externa', 'info_avertissement' => 'Advertencia', 'info_barre_outils' => '¿con su barra de herramientas?', 'info_base_installee' => 'La estructura de tu base de datos ha sido instalada', 'info_bio' => 'Biografía', 'info_cache_desactive' => 'La caché está temporalmente desactivada.', 'info_chapeau' => 'Epígrafe', 'info_chapeau_2' => 'Epígrafe:', 'info_chemin_acces_1' => 'Opciones: <b>Camino de acceso en el directorio</b>', 'info_chemin_acces_2' => 'Debe configurar el camino de acceso a la información en el anuario. Esta información es indispensable para leer los perfiles de personas almacenadas en el anuario.', 'info_chemin_acces_annuaire' => 'Opciones: <b>Camino de acceso en el directorio</b>', 'info_choix_base' => 'Tercera etapa:', 'info_classement_1' => '<sup>o</sup> sobre @liste@', 'info_classement_2' => '<sup>o</sup> sobre @liste@', 'info_code_acces' => '¡No olvide sus códigos de acceso!', 'info_compatibilite_html' => '¿Qué norma HTML seguir?', 'info_config_suivi' => 'Si esta dirección corresponde a una lista de correo, puede indicar aquí abajo la dirección en la cual los participantes del sitio pueden inscribirse. Esta dirección puede ser una URL (por ejemplo la página de inscripción a la lista por la web), o una dirección de correo electrónico con un asunto específico (por ejemplo: <tt>@adresse_suivi@?subject=subscribe</tt>):', 'info_config_suivi_explication' => 'Puede suscribirse a la lista de correo de este sitio. Recibirás por correo electrónico los anuncios de artículos y de breves propuestas a la publicación.', 'info_confirmer_passe' => 'Confirmar la nueva contraseña:', 'info_conflit_edition_avis_non_sauvegarde' => 'Atención, los siguientes campos han sido modificados por otro lado. Sus modificaciones sobre estos campos no han sido por tanto registradas.', 'info_conflit_edition_differences' => 'Diferencias:', 'info_conflit_edition_version_enregistree' => 'La versión registrada:', 'info_conflit_edition_votre_version' => 'Su versión:', 'info_connexion_base' => 'Intento de conexión a la base', 'info_connexion_base_donnee' => 'Conexión a su base de datos', 'info_connexion_ldap_ok' => '<b>Se logró la conexión LDAP.</b><p> Puede pasar a la etapa siguiente.</p>', 'info_connexion_mysql' => 'Tu conexión SQL', 'info_connexion_ok' => 'La conexión ha funcionado.', 'info_contact' => 'Contacto', 'info_contenu_articles' => 'Contenido de los artículos', 'info_contributions' => 'Contribuciones', 'info_creation_paragraphe' => 'Para crear párrafos, deje simplemente líneas vacías.', 'info_creation_rubrique' => 'Antes de poder escribir artículos,<br /> debe crear al menos una sección.<br />', 'info_creation_tables' => 'Creación de las tablas de la base', 'info_creer_base' => '<b>Crear</b> una nueva base de datos:', 'info_dans_rubrique' => 'En la sección...', 'info_date_publication_anterieure' => 'Fecha de redacción anterior:', 'info_date_referencement' => 'FECHA DE SINDICACIÓN DE ESTE SITIO :', 'info_derniere_etape' => '¡Ya terminamos!', 'info_descriptif' => 'Descripción:', 'info_desinstaller_plugin' => 'suprime los datos y desactiva el plugin', 'info_discussion_cours' => 'Debates en curso', 'info_ecrire_article' => 'Antes de escribir artículos, debe crear una sección.', 'info_email_envoi' => 'Dirección de correo de envío (opcional)', 'info_email_envoi_txt' => 'Indique aqui la dirección a utilizar para enviar los correos electrónicos (por defecto, se utiliza la dirección del destinatario como dirección de envío):', 'info_email_webmestre' => 'Dirección de correo electrónico del webmaster', 'info_envoi_email_automatique' => 'Envío automático de correos electrónicos', 'info_envoyer_maintenant' => 'Enviar ahora', 'info_etape_suivante' => 'Pasar a la siguiente etapa ', 'info_etape_suivante_1' => 'Puede pasar a la siguiente etapa ', 'info_etape_suivante_2' => 'Puede pasar a la siguiente etapa', 'info_exceptions_proxy' => 'Excepciones para el proxy', 'info_exportation_base' => 'exportación de la base hacia @archive@', 'info_facilite_suivi_activite' => 'Para facilitar el seguimiento de la actividad editorial, SPIP puede enviar por correo electrónico, por ejemplo a un lista de redactores, anuncios de solicitudes de publicación y de validación de artículos.', 'info_fichiers_authent' => 'Archivos de autentificación «.htpasswd»', 'info_forums_abo_invites' => 'Su sitio tiene foros para abonados; en el sitio público se invita a los visitantes a que se registren.', 'info_gauche_admin_tech' => '<b>Esta página sólo es accesible para los responsables del sitio.</b><p> Da acceso a las distintas funciones de mantenimiento técnico. Algunas de ellas requieren un proceso de autentificación para el cual es necesario tener acceso por FTP al sitio web.</p>', 'info_gauche_admin_vider' => '<b>Esta página sólo es accesible para los responsables del sitio.</b><p> Da acceso a las distintas funciones de mantenimiento técnico. Algunas de ellas dan lugar a un proceso de autentificación para el cual es necesario tener acceso por FTP al sitio web.</p>', 'info_gauche_auteurs' => 'Aquí figuran todos los autores del sitio. Su estatus se indica mediante el color de su icono (administrador/a = verde; redactor/a = amarillo).', 'info_gauche_auteurs_exterieurs' => 'Los autores exteriores, sin acceso al sitio, están indicados con un icono azul; los que están borrados por un icono gris.', 'info_gauche_messagerie' => 'La mensajería permite comunicarse, crear recordatorios para traer a la memoria algo o publicar anuncios (en el caso de pertenecer al grupo de administración).', 'info_gauche_statistiques_referers' => 'Esta página presenta la lista de los <i>referers</i>, es decir, de los sitios que contienen enlaces que llevan a su propio sitio, sólo para ayer y hoy; esta lista se pone a cero cada 24 horas.', 'info_gauche_visiteurs_enregistres' => 'Aquí se encuentran las personas registradas en el espacio público del sitio (foros con suscripción).', 'info_generation_miniatures_images' => 'Generación de las miniaturas de imágenes', 'info_gerer_trad_objets' => '@objets@: manejar los vínculos de traducción', 'info_hebergeur_desactiver_envoi_email' => 'Algunos servidores no permiten el envío automático de correos electrónicos. En esos casos, las siguientes funciones de SPIP no darán ningún resultado.', 'info_hier' => 'ayer:', 'info_identification_publique' => 'Su identidad pública...', 'info_image_process' => 'Por favor seleccione el mejor método de fabricación de viñetas pinchando en la imágen correspondiente. ', 'info_image_process2' => 'Si no aparece ninguna imagen, es que el servidor que alberga su sitio web no está configurado para usar estas herramientas. Si quiere utilizarlas, contacte al responsable técnico y solicite las extensiones «GD» o «Imagick».', 'info_images_auto' => 'Imágenes calculadas automáticamente', 'info_informations_personnelles' => 'Información personal', 'info_inscription' => 'Inscripción el', 'info_inscription_automatique' => 'Inscripcción automática de nuevos redactores', 'info_jeu_caractere' => 'Juego de caracteres del sitio', 'info_jours' => 'días', 'info_laisser_champs_vides' => 'dejar estos campos vacíos)', 'info_langues' => 'Idiomas del sitio', 'info_ldap_ok' => 'La autentificación LDAP está instalada.', 'info_lien_hypertexte' => 'Enlace hipertexto:', 'info_liste_nouveautes_envoyee' => 'La lista de novedades ha sido enviada', 'info_liste_redacteurs_connectes' => 'Lista de redactores conectados', 'info_login_existant' => 'Este nombre de usuario ya existe.', 'info_login_trop_court' => 'Identificador de usuario muy corto.', 'info_login_trop_court_car_pluriel' => 'El identificador de usuario debe contener por lo menos @nb@ caracteres.', 'info_logos' => 'Los logos', 'info_maximum' => 'máximo:', 'info_meme_rubrique' => 'En la misma sección', 'info_message_en_redaction' => 'Sus mensajes en curso de redacción', 'info_message_technique' => 'Mensaje técnico:', 'info_messagerie_interne' => 'Mensajería interna', 'info_mise_a_niveau_base' => 'actualización de su base SQL', 'info_mise_a_niveau_base_2' => '{{¡ATENCIÓN!}} Ha instalado una versión de los archivos SPIP {anterior} a la que se encontraba antes en este sitio: corre el riesgo de perder la base de datos y que el sitio deje de funcionar.<br />{{Vuelva a instalar los archivos de SPIP.}}', 'info_modification_enregistree' => 'Su modificación fue grabada', 'info_modifier_auteur' => 'Modificar el autor:', 'info_modifier_rubrique' => 'Modificar la sección', 'info_modifier_titre' => 'Modificar @titre@', 'info_mon_site_spip' => 'Mi sitio SPIP', 'info_moyenne' => 'promedio:', 'info_multi_cet_article' => 'Idioma de este artículo:', 'info_multi_langues_choisies' => 'A continuación seleccione los idiomas que quiera poner a disposición de los redactores de su sitio. Los idiomas que ya se utilizan en el sitio (al principio de la lista) no pueden ser desactivados. ', 'info_multi_objets' => '@objets@: activar el menú de idioma', 'info_multi_secteurs' => '... sólo para las secciones situadas en la raíz?', 'info_nb_articles' => '@nb@ artículos', 'info_nb_auteurs' => '@nb@ autores', 'info_nb_messages' => '@nb@ mensajes', 'info_nb_mots_cles' => '@nb@ palabras-claves', 'info_nb_rubriques' => '@nb@ secciones', 'info_nb_visiteurs' => '@nb@ visitantes', 'info_nom' => 'Nombre', 'info_nom_destinataire' => 'Nombre del destinatario o destinataria', 'info_nom_pas_conforme' => 'las etiquetas HTML no están permitidas', 'info_nom_site' => 'Nombre de tu sitio', 'info_nombre_articles' => '@nb_articles@ artículos,', 'info_nombre_rubriques' => '@nb_rubriques@ secciones,', 'info_nombre_sites' => '@nb_sites@ sitios,', 'info_non_deplacer' => 'No desplazar...', 'info_non_envoi_annonce_dernieres_nouveautes' => 'SPIP puede enviar regularmente la lista de las novedades del sitio (artículos y breves).', 'info_non_envoi_liste_nouveautes' => 'No enviar la lista de novedades', 'info_non_modifiable' => 'no puede ser modificado', 'info_non_suppression_mot_cle' => 'No deseo suprimir esta palabra clave', 'info_notes' => 'Notas', 'info_nouvel_article' => 'Nuevo artículo', 'info_nouvelle_traduction' => 'Nueva traducción:', 'info_numero_article' => 'ARTÍCULO NÚMERO:', 'info_obligatoire_02' => '(obligatorio)', 'info_option_accepter_visiteurs' => 'Aceptar la inscripción de los visitantes del sitio público', 'info_option_ne_pas_accepter_visiteurs' => 'Rechazar la inscripción de visitantes', 'info_options_avancees' => 'OPCIONES AVANZADAS', 'info_ou' => 'o...', 'info_page_interdite' => 'Página no accesible', 'info_par_nom' => 'por nombre', 'info_par_nombre_article' => 'por número de artículos', 'info_par_statut' => 'por estatus', 'info_par_tri' => '’(por @tri@)’', 'info_passe_trop_court' => 'Contraseña demasiado corta', 'info_passe_trop_court_car_pluriel' => 'La contraseña debe contener al menos @nb@ caracteres.', 'info_passes_identiques' => 'Hay diferencias entre las dos contraseñas', 'info_plus_cinq_car' => 'más de 5 caracteres', 'info_plus_cinq_car_2' => '(Más de 5 caracteres)', 'info_plus_trois_car' => '(Más de tres caracteres)', 'info_popularite' => 'Popularidad: @popularite@ Visitas: @visites@', 'info_post_scriptum' => 'Post Scríptum', 'info_post_scriptum_2' => 'Post Scríptum:', 'info_pour' => 'para', 'info_preview_texte' => 'Es posible previsualizar los diferentes elementos editoriales del sitio que tengan por lo menos el estatuto de "propuesto", así como los elementos que están en curso de redacción y de los que seamos el autor. Esta función debe estar disponible para los administradores, los redactores, o para nadie ? ', 'info_procedez_par_etape' => 'proceda etapa por etapa', 'info_procedure_maj_version' => 'Se debe ejecutar el proceso de actualización de la base de datos a esta nueva versión de SPIP.', 'info_proxy_ok' => 'Test del proxy logrado.', 'info_ps' => 'P.-S.', 'info_publier' => 'publicar', 'info_publies' => 'Sus artículos publicados', 'info_question_accepter_visiteurs' => 'Si en los esqueletos de su sitio está previsto el registro de visitantes sin acceso al espacio privado, tendrá que activar la opción siguiente:', 'info_question_inscription_nouveaux_redacteurs' => '¿Se aceptan inscripciones de nuevas redactoras y redactores desde el sitio público? Si se aceptan, las personas que visitan el sitio podrán inscribirse desde un formulario automatizado y accederán entonces al espacio privado para proponer sus propios artículos. <div class="notice">Durante la fase de inscripción, reciben un correo electrónico automático que les indica sus códigos de acceso al sitio privado. Ciertos proveedores de hospedaje desactivan el envío de correos electrónicos desde sus servidores: en tal caso, se hace imposible la inscripción automática.</div>', 'info_qui_edite' => '@nom_auteur_modif@ ha trabajado en este contenido hace @date_diff@ minutos', 'info_racine_site' => 'Raíz del sitio', 'info_recharger_page' => 'Por favor recargue esta página dentro de un momento', 'info_recherche_auteur_zero' => 'No hay resultados para « @cherche_auteur@ ».', 'info_recommencer' => 'Vuelva a empezar.', 'info_redacteur_1' => 'Redactor/a', 'info_redacteur_2' => 'teniendo acceso al espacio privado (<i>recomendado</i>)', 'info_redacteurs' => 'Redactores/as', 'info_redaction_en_cours' => 'EN CURSO DE REDACCIÓN', 'info_redirection' => 'Redirección', 'info_redirection_activee' => 'La redirección está activada.', 'info_redirection_boucle' => 'Usted esta probando redirigir el artículo hacía el mismo.', 'info_redirection_desactivee' => 'La redirección se ha suprimido.', 'info_refuses' => 'Sus artículos rechazados', 'info_reglage_ldap' => 'Opciones: <b>Ajustes de la importación LDAP</b>', 'info_renvoi_article' => '<b>Redirección.</b> Este artículo reenvía a la página:', 'info_reserve_admin' => 'Sólo el equipo de administración puede modificar esta dirección', 'info_restreindre_rubrique' => 'Limitar la gestión a la sección:', 'info_resultat_recherche' => 'Resultados de la búsqueda:', 'info_rubriques' => 'Secciones', 'info_rubriques_02' => 'secciones', 'info_rubriques_trouvees' => 'Secciones localizadas', 'info_sans_titre' => 'Sin título', 'info_selection_chemin_acces' => 'Seleccione el camino de acceso en el anuario', 'info_signatures' => 'firmas', 'info_site' => 'Sitio', 'info_site_2' => 'sitio:', 'info_site_min' => 'sitio', 'info_site_reference_2' => 'Sitio referenciado', 'info_site_web' => 'Sitio Web:', 'info_sites' => 'sitios', 'info_sites_lies_mot' => 'Los sitios referenciados ligados a esta palabra clave', 'info_sites_proxy' => 'Utilizar un proxy', 'info_sites_trouves' => 'Sitios hallados', 'info_sous_titre' => 'Subtítulo', 'info_statut_administrateur' => 'Administrador/a', 'info_statut_auteur' => 'Estatus de este autor o autora:', 'info_statut_auteur_2' => 'Soy', 'info_statut_auteur_a_confirmer' => 'Inscripción por confirmar', 'info_statut_auteur_autre' => 'Otro papel:', 'info_statut_redacteur' => 'Redactor/a', 'info_statut_utilisateurs_1' => 'Estatus por defecto de usuarios importados', 'info_statut_utilisateurs_2' => 'Elija el estatus atribuido a las personas presentes en el directorio LDAP cuando se conectan por primera vez. Posteriormente podrá modificar este valor para cada autor en cada caso.', 'info_suivi_activite' => 'Seguimiento de la actividad editorial', 'info_surtitre' => 'Antetítulo:', 'info_syndication_integrale_1' => 'Su sitio propone archivos de sindicación (ver «<a href="@url@">@titre@</a>»).', 'info_syndication_integrale_2' => '¿Desea transmitir íntegramente los artículos, o sólo un resumen compuesto por unos cientos de caracteres?', 'info_table_prefix' => 'Puede modificar el prefijo del nombre de las tablas de datos (es indispensable si se quiere instalar varios sitios en la misma base de datos). Este prefijo debe ser en letras minúsculas, no acentuadas, y sin espacios. ', 'info_taille_maximale_images' => 'SPIP comprobará el tamaño máximo de imagen que puede gestionar (en millones de pixels).<br /> Las imágenes mayores no se reducirán.', 'info_taille_maximale_vignette' => 'Tamaño máximo de los iconos generados por el sistema:', 'info_terminer_installation' => 'Puede terminar ahora el procedimiento de instalación estándar.', 'info_texte' => 'Texto', 'info_texte_explicatif' => 'Texto explicativo', 'info_texte_long' => '(el texto es largo: aparece en varias partes que serán reunidas tras validación)', 'info_texte_message' => 'Texto de su mensaje', 'info_texte_message_02' => 'Texto del mensaje', 'info_titre' => 'Título:', 'info_total' => 'total:', 'info_tous_articles_en_redaction' => 'Todos los artículos en curso de redacción', 'info_tous_articles_presents' => 'Todos los artículos publicados en esta sección', 'info_tous_articles_refuses' => 'Todos los artículos rechazados', 'info_tous_les' => 'todos los:', 'info_tout_site' => 'Todo el sitio', 'info_tout_site2' => 'El artículo no ha sido traducido a este idioma.', 'info_tout_site3' => 'El artículo ha sido traducido a este idioma, pero posteriormente se han aportado modificaciones al artículo de referencia. La traducción debe ser actualizada.', 'info_tout_site4' => 'El artículo ha sido traducido a este idioma, y la traducción está al día. ', 'info_tout_site5' => 'Artículo original', 'info_tout_site6' => '<b>Atención:</b> sólo se muestran los artículos originales. Las traducciones están asociadas al original, en un color que indica su estado:', 'info_traductions' => 'Traducciones', 'info_travail_colaboratif' => 'Trabajo colectivo en los artículos', 'info_un_article' => 'un artículo,', 'info_un_site' => 'un sitio,', 'info_une_rubrique' => 'una sección,', 'info_une_rubrique_02' => '1 sección', 'info_url' => 'URL:', 'info_url_proxy' => 'URL del proxy', 'info_url_site_pas_conforme' => 'la URL del sitio no es válida.', 'info_url_test_proxy' => 'URL de prueba', 'info_urlref' => 'Enlace hipertexto:', 'info_utilisation_spip' => 'Puede comenzar a utilizar el sistema de publicación asistida...', 'info_visites_par_mois' => 'Mostrar por mes:', 'info_visiteur_1' => 'Visitante', 'info_visiteur_2' => 'del sitio público', 'info_visiteurs' => 'Visitantes', 'info_visiteurs_02' => 'Visitantes del sitio público', 'info_webmestre_forces' => 'La lista de webmasters está actualmente definida en <tt>@file_options@</tt>.', 'install_adresse_base_hebergeur' => 'Dirección de la base de datos asignada por el proveedor del alojamiento', 'install_connect_ok' => 'La nueva base de datos fue declarada con éxito con el nombre de servidor @connect@.', 'install_echec_annonce' => 'La instalación probablemente va a fallar, o creará un sitio que no funcione...', 'install_extension_mbstring' => 'SPIP no funciona con:', 'install_extension_php_obligatoire' => 'SPIP exige instalar la extensión php:', 'install_login_base_hebergeur' => 'Nombre de usuario de conexión asignado por el proveedor del alojamiento', 'install_nom_base_hebergeur' => 'Nombre de la base asignada por el proveedor:', 'install_pas_table' => 'La base no tiene tablas en este momento', 'install_pass_base_hebergeur' => 'Contraseña de conexión asignada por el proveedor', 'install_php_version' => 'PHP versión @version@ insuficiente (mínimo = @minimum@)', 'install_select_langue' => 'Seleccione un idioma y después pulse el botón «siguiente» para iniciar el proceso de instalación.', 'install_select_type_db' => 'Indicar el tipo de base de datos:', 'install_select_type_mysql' => 'MySQL', 'install_select_type_pg' => 'PostgreSQL', 'install_select_type_sqlite2' => 'SQLite 2', 'install_select_type_sqlite3' => 'SQLite 3', 'install_serveur_hebergeur' => 'Servidor de base de datos asignado por tu proveedor', 'install_table_prefix_hebergeur' => 'Prefijo de la tabla asignada por el proveedor:', 'install_tables_base' => 'Tablas de la base', 'install_types_db_connus' => 'SPIP sabe utilizar <b>MySQL</b> (el formato más extendido) y <b>SQLite</b>.', 'install_types_db_connus_avertissement' => 'También se propone el soporte para <b>PostgreSQL</b> en modo experimental.', 'instituer_erreur_statut_a_change' => 'El estatus ya ha sido modificado', 'instituer_erreur_statut_non_autorise' => 'No puede elegir este estatus', 'intem_redacteur' => 'redactor/a', 'intitule_licence' => 'Licencia', 'item_accepter_inscriptions' => 'Aceptar las inscripciones', 'item_activer_messages_avertissement' => 'Activar los mensajes de advertencia', 'item_administrateur_2' => 'administrador/a', 'item_afficher_calendrier' => 'Mostrar en el calendario', 'item_autoriser_syndication_integrale' => 'Difundir íntegramente los artículos en los archivos de sindicación', 'item_choix_administrateurs' => 'los administradores', 'item_choix_generation_miniature' => 'Generar automáticamente las miniaturas de las imágenes', 'item_choix_non_generation_miniature' => 'No generar miniaturas de las imágenes', 'item_choix_redacteurs' => 'los redactores', 'item_choix_visiteurs' => 'los visitantes del sitio público', 'item_creer_fichiers_authent' => 'Crear los archivos «.htpasswd»', 'item_login' => 'Login', 'item_messagerie_agenda' => 'Activar la mensajería y la agenda', 'item_mots_cles_association_articles' => 'a los artículos', 'item_mots_cles_association_rubriques' => 'a las secciones', 'item_mots_cles_association_sites' => 'a los sitios referenciados o sindicados', 'item_non' => 'No', 'item_non_accepter_inscriptions' => 'No aceptar inscripciones', 'item_non_activer_messages_avertissement' => 'Sin mensajes de advertencia', 'item_non_afficher_calendrier' => 'No mostrar en el calendario', 'item_non_autoriser_syndication_integrale' => 'Sólo difundir un resumen', 'item_non_creer_fichiers_authent' => 'No crear esos archivos', 'item_non_messagerie_agenda' => 'Desactivar la mensajería y la agenda', 'item_non_publier_articles' => 'No publicar los artículos antes de la fecha de publicación indicada', 'item_nouvel_auteur' => 'Nueva autora o autor', 'item_nouvelle_rubrique' => 'Nueva sección', 'item_oui' => 'Sí', 'item_publier_articles' => 'Publicar los artículos sin tener en cuenta la fecha de publicación', 'item_reponse_article' => 'Respuesta al artículo', 'item_version_html_max_html4' => 'Limitarse al HTML4 en el sitio público', 'item_version_html_max_html5' => 'Permitir el HTML5', 'item_visiteur' => 'visitante', // J 'jour_non_connu_nc' => 'n.c.', // L 'label_bando_outils' => 'Barra de herramientas', 'label_bando_outils_afficher' => 'Mostrar herramientas', 'label_bando_outils_masquer' => 'Ocultar herramientas', 'label_choix_langue' => 'Seleccione su idioma', 'label_nom_fichier_connect' => 'Indica el nombre utilizado para este servidor', 'label_slogan_site' => 'Eslogan del sitio', 'label_taille_ecran' => 'Ancho de pantalla', 'label_texte_et_icones_navigation' => 'Menú de navegación', 'label_texte_et_icones_page' => 'Aparencia en la página', 'ldap_correspondance' => 'herencia del campo @champ@', 'ldap_correspondance_1' => 'Herencia de los campos LDAP', 'ldap_correspondance_2' => 'Por cada uno de los campos SPIP siguientes, indicar el nombre del campo LDAP correspondiente. Dejar vacío para no indicar ninguno, y separar con espacios o comas para que se prueben varios campos LDAP.', 'lien_ajouter_auteur' => 'Añadir este autor', 'lien_ajouter_une_rubrique' => 'Añadir esta sección', 'lien_email' => 'correo electrónico', 'lien_nom_site' => 'NOMBRE DEL SITIO:', 'lien_retirer_auteur' => 'Retirar el autor', 'lien_retirer_rubrique' => 'Retirar la sección', 'lien_retirer_tous_auteurs' => 'Quitar todos los autores', 'lien_retirer_toutes_rubriques' => 'Retirar todas las secciones', 'lien_site' => 'sitio', 'lien_tout_decocher' => 'desmarcar todo', 'lien_tout_deplier' => 'Desplegar todo', 'lien_tout_replier' => 'Replegar todo', 'lien_tout_supprimer' => 'Suprimir todo', 'lien_trier_nom' => 'Ordenar por nombre', 'lien_trier_nombre_articles' => 'Ordenar por número de artículos', 'lien_trier_statut' => 'Ordenar por estatus', 'lien_voir_en_ligne' => 'VER LA LÍNEA:', 'logo_article' => 'Logotipo del artículo', 'logo_auteur' => 'Logotipo del autor', 'logo_rubrique' => 'Logotipo de la sección', 'logo_site' => 'Logotipo del sitio', 'logo_standard_rubrique' => 'Logotipo estándar de las secciones', 'logo_survol' => 'Logotipo paso del ratón', // M 'menu_aide_installation_choix_base' => 'Elección de su base', 'module_fichier_langue' => 'Archivo de idioma', 'module_raccourci' => 'Acceso directo', 'module_texte_affiche' => 'Texto mostrado', 'module_texte_explicatif' => 'Puede insertar los siguientes accesos directos en los esqueletos de su sitio público. Serán traducidos automáticamente en los diferentes idiomas para los que existe un archivo de idioma.', 'module_texte_traduction' => 'El archivo de idioma « @module@ » está disponible en:', 'mois_non_connu' => 'desconocido', // N 'nouvelle_version_spip' => 'La versión @version@ de SPIP está disponible', 'nouvelle_version_spip_majeure' => 'Una nueva versión SPIP @version@ está disponible', // O 'onglet_contenu' => 'Contenido', 'onglet_declarer_une_autre_base' => 'Declarar otra base', 'onglet_discuter' => 'Discutir', 'onglet_interactivite' => 'Interactividad', 'onglet_proprietes' => 'Propriedades', 'onglet_repartition_actuelle' => 'actualmente', 'onglet_sous_rubriques' => 'Subsecciones', // P 'page_pas_proxy' => 'Esta página no debe pasar por el proxy', 'pas_de_proxy_pour' => 'Si fuera el caso, indica los servidores o dominios para los cuales este proxy no debe aplicarse. (por ejemplo: @exemple@)', 'plugin_charge_paquet' => 'Carga del paquete @name@', 'plugin_charger' => 'Descargar', 'plugin_erreur_charger' => 'error: no es posible cargar @zip@', 'plugin_erreur_droit1' => 'La carpeta <code>@dest@</code> no es accesible en modo escritura.', 'plugin_erreur_droit2' => 'Tendrás que verificar los derechos en esta carpeta (o crearla si es el caso), o instalar los archivos por FTP.', 'plugin_erreur_zip' => 'fallo de pclzip: error @status@', 'plugin_etat_developpement' => 'en desarrollo', 'plugin_etat_experimental' => 'experimental', 'plugin_etat_stable' => 'estable', 'plugin_etat_test' => 'en prueba', 'plugin_impossible_activer' => 'Imposible activar el plugin @plugin@', 'plugin_info_automatique1' => 'Si quiere autorizar la instalación automática de los plugins, ha de:', 'plugin_info_automatique1_lib' => 'Si desea autorizar la instalación automática de esta librería, consulte:', 'plugin_info_automatique2' => 'crear una carpeta <code>@rep@</code> ;', 'plugin_info_automatique3' => 'verificar que el servidor tiene permiso para escribir en esa carpeta.', 'plugin_info_automatique_creer' => 'que hay que crear en la raíz del sitio.', 'plugin_info_automatique_exemples' => 'ejemplos:', 'plugin_info_automatique_ftp' => 'Puede instalar plugins, por FTP, en la carpeta <tt>@rep@</tt>', 'plugin_info_automatique_lib' => 'Ciertos plugins también requieren que se pueda descargar archivos a la carpeta <code>lib/</code>, que habrá que crear, si es el caso, en la raíz del sitio.', 'plugin_info_automatique_liste' => 'Sus listas de plugins:', 'plugin_info_automatique_liste_officielle' => 'los plugins oficiales', 'plugin_info_automatique_liste_update' => 'Actualizar las listas', 'plugin_info_automatique_ou' => 'o...', 'plugin_info_automatique_select' => 'Seleccione un plugin de aquí: SPIP lo descargará y lo instalará en la carpeta <code>@rep@</code>; si el plugin ya existe, se actualizará.', 'plugin_info_credit' => 'Créditos', 'plugin_info_erreur_xml' => 'La declaración de este plugin es incorrecta', 'plugin_info_install_ok' => 'Instalación exitosa', 'plugin_info_necessite' => 'Necesita:', 'plugin_info_non_compatible_spip' => 'Este plugin no es compatible con esta versión de SPIP', 'plugin_info_plugins_dist_1' => 'Las plugins siguientes se cargan y se activan en la carpeta @plugins_dist@.', 'plugin_info_plugins_dist_2' => 'No pueden desactivarse.', 'plugin_info_telecharger' => 'se descargará de @url@ y se instalará en @rep@', 'plugin_info_upgrade_ok' => 'Actualización exitosa', 'plugin_librairies_installees' => 'Bibliotecas instaladas', 'plugin_necessite_lib' => 'Este plugin necesita la biblioteca @lib@', 'plugin_necessite_plugin' => 'Necesita el plugin @plugin@ con versión @version@ por lo menos.', 'plugin_necessite_plugin_sans_version' => 'Necesita el plugin @plugin@', 'plugin_necessite_spip' => 'Necesita como mínimo un SPIP de versión @version@.', 'plugin_source' => 'fuente: ', 'plugin_titre_automatique' => 'Instalación automática', 'plugin_titre_automatique_ajouter' => 'Añadir plugins', 'plugin_titre_installation' => 'Instalación del plugin @plugin@', 'plugin_titre_modifier' => 'Mis plugins', 'plugin_utilise_plugin' => 'Utiliza le plugin @plugin@ en versión @version@.', 'plugin_zip_active' => 'Continúe para activarlo', 'plugin_zip_adresse' => 'indique aquí la dirección de un archivo zip de plugin a descargar, o también la dirección de una lista de plugins.', 'plugin_zip_adresse_champ' => 'Dirección del plugin o de la lista ', 'plugin_zip_content' => 'Contiene los siguientes archivos (@taille@),<br />que se instalarán en la carpeta <code>@rep@</code>', 'plugin_zip_installe_finie' => 'El archivo @zip@ se ha descomprimido e instalado.', 'plugin_zip_installe_rep_finie' => 'El archivo @zip@ se ha descomprimido y se ha instalado en la carpeta @rep@', 'plugin_zip_installer' => 'Ahora puede instalarlo.', 'plugin_zip_telecharge' => 'Se ha descargado el archivo @zip@', 'plugins_actif_aucun' => 'Ningún plugin activado.', 'plugins_actif_un' => 'Un plugin activado.', 'plugins_actifs' => '@count@ plugins activados.', 'plugins_actifs_liste' => 'Activos', 'plugins_compte' => '@count@ plugins', 'plugins_disponible_un' => 'Un plugin disponible.', 'plugins_disponibles' => '@count@ plugins disponibles.', 'plugins_erreur' => 'Error en los plugins: @plugins@', 'plugins_liste' => 'Lista de plugins', 'plugins_liste_dist' => 'Plugins cerrados', 'plugins_recents' => 'Plugins recientes.', 'plugins_tous_liste' => 'Todos', 'plugins_vue_hierarchie' => 'Jerarquía', 'plugins_vue_liste' => 'Lista', 'protocole_ldap' => 'Versión del protocolo:', // Q 'queue_executer_maintenant' => 'Ejecutar ahora', 'queue_info_purger' => 'Puede eliminar todos los trabajos pendientes y reinicializar la lista con los trabajos periódicos', 'queue_nb_jobs_in_queue' => '@nb@ trabajos en espera', 'queue_next_job_in_nb_sec' => 'Próximo trabajo en @nb@ s', 'queue_no_job_in_queue' => 'Ningún trabajo en espera', 'queue_one_job_in_queue' => '1 trabajo en espera', 'queue_purger_queue' => 'Purgar la lista de trabajos', 'queue_titre' => 'Lista de trabajos', // R 'repertoire_plugins' => 'Carpeta:', 'required' => '(obligatorio)', // S 'sans_heure' => 'sin hora', 'statut_admin_restreint' => 'administrador restringido', 'statut_webmestre' => 'webmaster', // T 'tache_cron_asap' => 'Tarea CRON @function@ (ASAP)', 'tache_cron_secondes' => 'Tarea CRON @function@ (cada @nb@ s)', 'taille_cache_image' => 'Las imágenes calculadas automáticamente por SPIP (miniaturas de documentos, títulos presentados en forma gráfica, fórmulas matemáticas en formato TeX...) ocupan en el directorio @dir@ un total de @taille@.', 'taille_cache_infinie' => 'En este sitio no se limita el tamaño de la carpeta de cache.', 'taille_cache_maxi' => 'SPIP intenta limitar el tamaño de la carpeta de cache de este sitio a unos <b>@octets@</b> de datos.', 'taille_cache_moins_de' => 'El tamaño de la cache es menor a @octets@.', 'taille_cache_octets' => 'El tamaño de la caché es actualmente de @octets@.', 'taille_cache_vide' => 'La cache está vacía.', 'taille_repertoire_cache' => 'Tamaño de la carpeta cache', 'text_article_propose_publication' => 'Artículo propuesto para su publicación.', 'texte_acces_ldap_anonyme_1' => 'Algunos servidores LDAP no aceptan accesos anónimos. En ese caso debe especificar un identificador de acceso inicial para poder luego buscar información en el directorio. En la mayoría de los casos los campos siguientes pueden estar vacíos.', 'texte_admin_effacer_01' => 'Este comando borra <i>TODO</i> el contenido de la base de datos, e incluye <i>todos</i> los accesos redactores y administradores. Después de ejecutarlo tendrá que volver a instalar SPIP, creando una nueva base al igual que un primer acceso de administración.', 'texte_adresse_annuaire_1' => '(Si su carpeta está instalada en la misma máquina que el sitio Web, se trata probablemente de "localhost").', 'texte_ajout_auteur' => 'El siguiente autor ha sido añadido al artículo:', 'texte_annuaire_ldap_1' => 'Si tiene un acceso a un directorio (LDAP), puede utilizarlo para importar automáticamente usuarios de SPIP.', 'texte_article_statut' => 'Este artículo está:', 'texte_article_virtuel' => 'Artículo virtual', 'texte_article_virtuel_reference' => '<b>Artículo virtual:</b> Artículo referenciado en su sitio SPIP, pero redirigido hacia otra URL. Para eliminar la redirección, borre la URL .', 'texte_aucun_resultat_auteur' => 'Ningún resultado por "@cherche_auteur@"', 'texte_auteur_messagerie' => 'Este sitio puede indicarle permanentemente la lista de personas conectadas, lo que permite intercambiar mensajes en directo. Además, puede decidir no aparecer en la lista (figura como «invisible» para los otros usuarios).', 'texte_auteurs' => 'LOS AUTORES', 'texte_choix_base_1' => 'Eleja la base:', 'texte_choix_base_2' => 'El servidor SQL contiene varias bases de datos.', 'texte_choix_base_3' => '<b>Seleccione</b> aquí la que te fue atribuída por tu proveedor de hospedaje:', 'texte_choix_table_prefix' => 'Prefijo de las tablas:', 'texte_compatibilite_html' => 'Puede elegir si quiere que SPIP produzca, en el sitio público, un código compatible con la norma <i>HTML4</i>, o si prefiere usar las posibilidades más modernas de <i>HTML5</i>.', 'texte_compatibilite_html_attention' => 'No hay ningún riesgo en activar la opción <i>HTML5</i>, pero entonces las páginas de su sitio tienen que empezar por la mención siguiente (para ser válidas): <code>&lt;!DOCTYPE html&gt;</code>.', 'texte_compte_element' => '@count@ elemento', 'texte_compte_elements' => '@count@ elementos', 'texte_conflit_edition_correction' => 'Por favor revise aquí debajo las diferencias entre las dos versiones del texto; también podrá copiar sus modificaciones, y luego volver a empezar.', 'texte_connexion_mysql' => 'Consulte la información facilitada por su hospedaje: ahí debería encontrar el nombre del servidor de base de datos que le ofrece y las claves e identificador para conectarse.', 'texte_contenu_article' => '(Contenido del artículo en pocas palabras)', 'texte_contenu_articles' => 'Según el diseño de su sitio, puede decidir que algunos elementos de los artículos no sean utilizados. Utilice la siguiente lista para indicar qué elementos están disponibles.', 'texte_crash_base' => 'Si su base de datos ha fallado, puede intentar una reparación automática. ', 'texte_creer_rubrique' => 'Antes de poder escribir artículos,<br /> debe crear una sección.', 'texte_date_creation_article' => 'FECHA DE CREACIÓN DEL ARTÍCULO:', 'texte_date_creation_objet' => 'Fecha de creación:', # on ajoute le ":" 'texte_date_publication_anterieure' => 'Fecha de redacción anterior:', 'texte_date_publication_anterieure_nonaffichee' => 'No mostrar fecha de redacción anterior.', 'texte_date_publication_article' => 'FECHA DE PUBLICACIÓN EN LÍNEA:', 'texte_date_publication_objet' => 'Fecha de publicación en línea:', 'texte_definir_comme_traduction_rubrique' => 'Esta rúbrica es una traducción de la rúbrica número :', 'texte_descriptif_rapide' => 'Descripción rápida', 'texte_effacer_base' => 'Borrar la base de datos SPIP', 'texte_effacer_statistiques' => 'Borrar las estadísticas', 'texte_en_cours_validation' => 'Los contenidos a continuación están a la espera de validación.', 'texte_enrichir_mise_a_jour' => 'Puedes enriquecer el formato de tu texto utilizando "atajos tipográficos"', 'texte_fichier_authent' => '<b>¿Debe SPIP crear los archivos especiales <tt>.htpasswd</tt> y <tt>.htpasswd-admin</tt> en la carpeta @dossier@?</b><p> Estos archivos pueden servir para restringir el acceso a los autores y administradores en otros lugares de su sitio (programa externo de estadísticas, por ejemplo).<p> Si no le ve utilidad, puede dejar esta opción con su valor por defecto (no crear los archivos).</p>', 'texte_informations_personnelles_1' => 'El sistema va a crear ahora un acceso personalizado al sitio.', 'texte_informations_personnelles_2' => '(Nota: si se trata de una reinstalación, y su acceso todavía funciona, puede ', 'texte_introductif_article' => '(Introducción del artículo)', 'texte_jeu_caractere' => 'Se aconseja emplear para el sitio el alfabeto universal <tt>utf-8</tt>): permite visualizar textos en todos los idiomas, y ya no plantea problemas de compatibilidad con navegadores modernos.', 'texte_jeu_caractere_3' => 'Su sitio está actualmente instalado en el juego de caracteres:', 'texte_jeu_caractere_4' => 'Si no corresponde a la realidad de Sus datos (por ejemplo, después de una restauración de base de datos), o si <em>empieza este sitio</em> y desea hacerlo con otro juego de caracteres, indíquelo aquí:', 'texte_login_ldap_1' => '(Dejar en blanco para un acceso anónimo, o indicar la ruta completa, por ejemplo "<tt>uid=perez, ou=users, dc=mi-dominio, dc=com</tt>".)', 'texte_login_precaution' => '¡Atención! Éste es el nombre de usuario con el que está conectado actualmente. Utilice este formulario con precaución...', 'texte_messagerie_agenda' => 'Una mensajería permite a los redactores del sitio comunicarse entre ellos directamente en el espacio privado. Esta mensajería está asociada a una agenda.', 'texte_mise_a_niveau_base_1' => 'Acaba de actualizar los archivos de SPIP. Ahora se debe actualizar la base de datos del sitio.', 'texte_modifier_article' => 'Modificar el artículo:', 'texte_multilinguisme' => 'Si desea manejar objetos en varios idiomas, con una navegación compleja, puede agregar un menú de selección de idioma para esos objetos, en función de la organización de su sitio.', 'texte_multilinguisme_trad' => 'También puede activar un sistema de gestión de enlaces entre las diferentes traducciones de ciertos objetos. ', 'texte_non_compresse' => '<i>no comprimido</i> (tu servidor no soporta esta funcionalidad)', 'texte_nouvelle_version_spip_1' => 'Ha instalado una versión nueva de SPIP.', 'texte_nouvelle_version_spip_2' => 'Esta nueva versión necesita una actualización más completa que de costumbre. Si es webmaster del sitio, borre el archivo @connect@ y retome la instalación con el fin de actualizar los parámetros de conexión a la base de datos.<p> (NB: si ha olvidado los parámetros de conexión, eche un vistazo al archivo @connect@ antes de suprimirlo...)</p>', 'texte_operation_echec' => 'Regrese a la página anterior, seleccione otra base o cree una nueva. Verifique la información facilitada por su proveedor de hospedaje.', 'texte_plus_trois_car' => 'más de 3 caracteres', 'texte_plusieurs_articles' => 'Se ha encontrado varios autores para "@cherche_auteur@":', 'texte_port_annuaire' => '(En general, es adecuado el valor predeterminado)', 'texte_presente_plugin' => 'Esta página lista los plugins disponibles en el sitio. Puede activar los plugins necesarios seleccionando la casilla correspondiente. ', 'texte_proposer_publication' => 'Cuando su artículo esté terminado, <br /> puede proponer su publicación.', 'texte_proxy' => 'En algunos casos (intranet, redes protegidas...), los sitios distantes (documentación de SPIP, sitios sindicados, etc.) no son accesibles más que através de un <i>proxy HTTP</i>. En ese caso, indique a continuación su dirección, bajo la forma <tt><html>http://proxy:8080</html></tt>. En general, se dejará esta casilla vacía.', 'texte_publication_articles_post_dates' => '¿Qué comportamiento debe adoptar SPIP frente a los artículos cuya fecha de publicación ha sido fijada con un plazo futuro?', 'texte_rappel_selection_champs' => '[Seleccione correctamente este campo]', 'texte_recalcul_page' => 'Si desea recalcular una sola página utiliza el botón "Recalcular" en el espacio público.', 'texte_recuperer_base' => 'Reparar la base de datos', 'texte_reference_mais_redirige' => 'Artículo referenciado en su sitio y redirigido hacia otra URL.', 'texte_requetes_echouent' => '<b>Cuando algunas peticiones SQL fallan sistemáticamente y sin razón aparente, es posible que sea debido a la base de datos en sí.</b><p> Su servidor SQL es capaz de reparar sus tablas cuando fueron dañadas por accidente. Puede intentar aquí esta reparación: si falla, conservE una copia del resultado, que posiblemente contenga indicios de lo que no funciona...</p><p> Si el problema persiste, contacte a su hospedaje.</p>', 'texte_selection_langue_principale' => 'A continuación puede seleccionar el «idioma principal» del sitio. Esta selección no obliga -¡afortunadamente!- a escribir los artículos en el idioma elegido, pero permite determinar: <ul><li> el formato predeterminado de las fechas en el sitio público;</li> <li> la naturaleza del motor tipográfico que SPIP debe utilizar para reproducir los textos;</li> <li> el idioma utilizado en los formularios del sitio público;</li> <li> el idioma predeterminado para el espacio privado.</li></ul>', 'texte_sous_titre' => 'Subtítulo', 'texte_statistiques_visites' => '(Barras oscuras: domingo / curva oscura: evolución del promedio)', 'texte_statut_attente_validation' => 'En espera de validación', 'texte_statut_publies' => 'Publicados', 'texte_statut_refuses' => 'Rechazados', 'texte_suppression_fichiers' => 'Utilice esta operación para suprimir todos los archivos presentes en la caché de SPIP. Esto permite, por ejemplo, forzar la actualización de todas las páginas si se hicieron importantes modificaciones gráficas o de estructura del sitio.', 'texte_sur_titre' => 'Antetítulo', 'texte_table_ok' => ': esta tabla está bien.', 'texte_tentative_recuperation' => 'Tentativa de reparación.', 'texte_tenter_reparation' => 'Intentar la reparación de la base de datos.', 'texte_test_proxy' => 'Para ensayar este "proxy" indique aquí la URL del sitio.', 'texte_titre_02' => 'Título', 'texte_titre_obligatoire' => '<b>Título</b> [Obligatorio]', 'texte_travail_article' => '@nom_auteur_modif@ ha trabajado sobre este artículo hace @date_diff@ minutos.', 'texte_travail_collaboratif' => 'Es frecuente que varios redactores y redactoras trabajen sobre el mismo artículo, el sistema puede mostrar los artículos recientemente «abiertos» para evitar las modificaciones simultáneas. Esta opción está desactivada por omisión para evitar mostrar mensajes de advertencia intempestivos.', 'texte_vide' => 'vacío', 'texte_vider_cache' => 'Vaciar la caché', 'titre_admin_tech' => 'Mantenimiento técnico', 'titre_admin_vider' => 'Mantenimiento técnico', 'titre_ajouter_un_auteur' => 'Añadir una autora', 'titre_ajouter_un_mot' => 'Añadir una palabra-clave', 'titre_cadre_afficher_article' => 'Mostrar los artículos', 'titre_cadre_afficher_traductions' => 'Mostrar el estado de las traducciones para los idiomas siguientes:', 'titre_cadre_ajouter_auteur' => 'Añadir un autor', 'titre_cadre_interieur_rubrique' => 'Al interior de la sección', 'titre_cadre_numero_auteur' => 'AUTOR NÚMERO', 'titre_cadre_numero_objet' => '@objet@ NÚMERO:', 'titre_cadre_signature_obligatoire' => '<b>Firma</b> [Obligatoria]<br />', 'titre_config_contenu_notifications' => 'Notificaciones', 'titre_config_contenu_prive' => 'En el espacio privado', 'titre_config_contenu_public' => 'En el sitio público', 'titre_config_fonctions' => 'Configuración del sitio', 'titre_config_langage' => 'Configuración del idioma', 'titre_configuration' => 'Configuración del sitio', 'titre_configurer_preferences' => 'Sus preferencias', 'titre_conflit_edition' => 'Conflicto durante la edición', 'titre_connexion_ldap' => 'Opciones: <b>Tu conexión LDAP</b>', 'titre_groupe_mots' => 'Grupo de palabras', 'titre_identite_site' => 'Identidad del sitio', 'titre_langue_article' => 'Idioma del artículo', 'titre_langue_rubrique' => 'Idioma de la sección', 'titre_langue_trad_article' => 'IDIOMA Y TRADUCCIONES DEL ARTÍCULO', 'titre_les_articles' => 'Los artículos', 'titre_messagerie_agenda' => 'Mensajería y agenda', 'titre_naviguer_dans_le_site' => 'Navegar por el sitio...', 'titre_nouvelle_rubrique' => 'Nueva sección', 'titre_numero_rubrique' => 'SECCIÓN NÚMERO:', 'titre_page_articles_edit' => 'Modificar: @titre@', 'titre_page_articles_page' => 'Los artículos', 'titre_page_articles_tous' => 'Todo el sitio', 'titre_page_calendrier' => 'Calendario @nom_mois@ @annee@', 'titre_page_config_contenu' => 'Configuración del sitio', 'titre_page_delete_all' => 'Supresión total e irreversible', 'titre_page_recherche' => 'Resultados de la búsqueda @recherche@', 'titre_page_statistiques_referers' => 'Estadísticas (enlaces entrantes)', 'titre_page_upgrade' => 'Actualización de SPIP', 'titre_publication_articles_post_dates' => 'Publicación de los artículos con fecha posterior', 'titre_reparation' => 'Reparación', 'titre_suivi_petition' => 'Gestión de las peticiones', 'tls_ldap' => 'Transport Layer Security:', 'trad_article_traduction' => 'Todas las versiones de este artículo:', 'trad_delier' => 'Dejar de ligar a estas traducciones ', 'trad_lier' => 'Este artículo es una traducción del artículo número:', 'trad_new' => 'Escribir una nueva traducción', // U 'utf8_convert_erreur_orig' => 'Error: el juego de caracteres no está soportado.', // V 'version' => 'Versión:' ); ?>
ernestovi/ups
spip/ecrire/lang/ecrire_es.php
PHP
gpl-3.0
62,766
#!/usr/bin/env python ######################################################################## # File : dirac-proxy-init.py # Author : Adrian Casajus ###########################################################from DIRAC.Core.Base import Script############# import sys import DIRAC from DIRAC.Core.Base import Script from DIRAC.FrameworkSystem.Client.ProxyManagerClient import ProxyManagerClient from DIRAC.Core.Security import CS, Properties from DIRAC.Core.Security.ProxyInfo import getProxyInfo __RCSID__ = "$Id:" userName = False def setUser( arg ): global userName userName = arg return DIRAC.S_OK() Script.registerSwitch( "u:", "user=", "User to query (by default oneself)", setUser ) Script.parseCommandLine() result = getProxyInfo() if not result[ 'OK' ]: print "Do you have a valid proxy?" print result[ 'Message' ] sys.exit( 1 ) proxyProps = result[ 'Value' ] if not userName: userName = proxyProps[ 'username' ] if userName in CS.getAllUsers(): if Properties.PROXY_MANAGEMENT not in proxyProps[ 'groupProperties' ]: if userName != proxyProps[ 'username' ] and userName != proxyProps[ 'issuer' ]: print "You can only query info about yourself!" sys.exit( 1 ) result = CS.getDNForUsername( userName ) if not result[ 'OK' ]: print "Oops %s" % result[ 'Message' ] dnList = result[ 'Value' ] if not dnList: print "User %s has no DN defined!" % userName sys.exit( 1 ) userDNs = dnList else: userDNs = [ userName ] print "Checking for DNs %s" % " | ".join( userDNs ) pmc = ProxyManagerClient() result = pmc.getDBContents( { 'UserDN' : userDNs } ) if not result[ 'OK' ]: print "Could not retrieve the proxy list: %s" % result[ 'Value' ] sys.exit( 1 ) data = result[ 'Value' ] colLengths = [] for pN in data[ 'ParameterNames' ]: colLengths.append( len( pN ) ) for row in data[ 'Records' ] : for i in range( len( row ) ): colLengths[ i ] = max( colLengths[i], len( str( row[i] ) ) ) lines = [""] for i in range( len( data[ 'ParameterNames' ] ) ): pN = data[ 'ParameterNames' ][i] lines[0] += "| %s " % pN.ljust( colLengths[i] ) lines[0] += "|" tL = len( lines[0] ) lines.insert( 0, "-"*tL ) lines.append( "-"*tL ) for row in data[ 'Records' ] : nL = "" for i in range( len( row ) ): nL += "| %s " % str( row[i] ).ljust( colLengths[i] ) nL += "|" lines.append( nL ) lines.append( "-"*tL ) print "\n".join( lines )
Andrew-McNab-UK/DIRAC
FrameworkSystem/scripts/dirac-proxy-get-uploaded-info.py
Python
gpl-3.0
2,416
package org.livingdoc.intellij.run; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.testframework.ui.TestStatusLine; import com.intellij.ide.browsers.BrowserLauncher; import com.intellij.ide.browsers.BrowserLauncherImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.util.ColorProgressBar; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import org.apache.commons.lang3.StringUtils; import org.livingdoc.intellij.common.I18nSupport; import org.livingdoc.intellij.common.PluginProperties; import org.livingdoc.intellij.connector.LivingDocConnector; import org.livingdoc.intellij.domain.ExecutionCounter; import org.livingdoc.intellij.domain.LivingDocException; import org.livingdoc.intellij.domain.LivingDocExecution; import org.livingdoc.intellij.domain.ProjectSettings; import org.livingdoc.intellij.gui.toolwindows.RepositoryViewUtils; import javax.swing.*; import java.io.*; import java.nio.charset.StandardCharsets; /** * This class will monitor the execution of a LivingDoc execution and it will capture its output. * * @see ProcessAdapter */ public class ProcessListenerLivingDoc extends ProcessAdapter { private static final Logger LOG = Logger.getInstance(ProcessListenerLivingDoc.class); private final RemoteRunConfiguration runConfiguration; private final FilesManager livingDocFilesManager; private final ExecutionCounter executionCounter; private final TestStatusLine statusLine; private boolean hasError = false; public ProcessListenerLivingDoc(final RemoteRunConfiguration runConfiguration) { this.runConfiguration = runConfiguration; this.livingDocFilesManager = new FilesManager(this.runConfiguration); this.statusLine = runConfiguration.getStatusLine(); this.executionCounter = runConfiguration.getExecutionCounter(); } @Override public void startNotified(ProcessEvent event) { if (executionCounter.getStartTime() == 0) { // Set the start time only the first time. executionCounter.setStartTime(System.currentTimeMillis()); } SwingUtilities.invokeLater(() -> { statusLine.setText(I18nSupport.getValue("run.execution.running.label")); statusLine.setStatusColor(ColorProgressBar.GREEN); statusLine.setFraction(0d); }); } @Override public void processTerminated(ProcessEvent processEvent) { executionCounter.setEndTime(System.currentTimeMillis()); if (processEvent.getExitCode() == 0) { try { LivingDocExecution execution = getLivingDocExecution(); updateStatusLine(execution); File resultFile = loadResultFile(execution); BrowserLauncher browser = new BrowserLauncherImpl(); browser.open(resultFile.getPath()); } catch (IOException | LivingDocException e) { LOG.error(e); } } else { statusLine.setText(I18nSupport.getValue("run.execution.error.process")); statusLine.setStatusColor(ColorProgressBar.RED); statusLine.setFraction(100d); } } private void updateStatusLine(final LivingDocExecution execution) { if (!hasError && (execution.hasException() || execution.hasFailed())) { hasError = true; } executionCounter.setTotalErrors(executionCounter.getTotalErrors() + execution.getErrors()); executionCounter.setFailuresCount(executionCounter.getFailuresCount() + execution.getFailures()); executionCounter.setFinishedTestsCount(executionCounter.getFinishedTestsCount() + execution.getSuccess()); executionCounter.setIgnoreTestsCount(executionCounter.getIgnoreTestsCount() + execution.getIgnored()); SwingUtilities.invokeLater(() -> { if (hasError) { runConfiguration.getStatusLine().setStatusColor(ColorProgressBar.RED); } else if (executionCounter.getIgnoreTestsCount() >= 1 || executionCounter.getFailuresCount() >= 1 || executionCounter.getTotalErrors() >= 1) { runConfiguration.getStatusLine().setStatusColor(ColorProgressBar.YELLOW); } else { ToolWindow toolWindow = ToolWindowManager.getInstance(runConfiguration.getProject()) .getToolWindow(PluginProperties.getValue("toolwindows.id")); toolWindow.activate(null); } int testsTotal = executionCounter.getFinishedTestsCount() + executionCounter.getTotalErrors() + executionCounter.getFailuresCount() + executionCounter.getIgnoreTestsCount(); Long duration = executionCounter.getEndTime() - executionCounter.getStartTime(); statusLine.formatTestMessage( testsTotal, executionCounter.getFinishedTestsCount(), executionCounter.getFailuresCount(), executionCounter.getIgnoreTestsCount(), duration, executionCounter.getEndTime()); statusLine.setFraction(1d); runConfiguration.getSelectedNode().setIcon(RepositoryViewUtils.getResultIcon(hasError, runConfiguration.getSelectedNode())); }); } private LivingDocExecution getLivingDocExecution() throws IOException, LivingDocException { File reportFile = livingDocFilesManager.createReportFile(); LivingDocConnector livingDocConnector = LivingDocConnector.newInstance(ProjectSettings.getInstance(runConfiguration.getProject())); return livingDocConnector.getSpecificationExecution(runConfiguration, reportFile); } private File loadResultFile(final LivingDocExecution execution) throws IOException { File resultFile = livingDocFilesManager.createResultFile(); String content = execution.hasException() ? execution.getExecutionErrorId() : execution.getResults(); if (StringUtils.isEmpty(content)) { content = I18nSupport.getValue("run.execution.error.no.response"); } try (Writer fileWriter = new OutputStreamWriter(new FileOutputStream(resultFile), StandardCharsets.UTF_8)) { fileWriter.write(content); } return resultFile; } }
pkleimann/livingdoc-intellij
src/main/java/org/livingdoc/intellij/run/ProcessListenerLivingDoc.java
Java
gpl-3.0
6,471
# # Copyright 2005,2006,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from __future__ import print_function from __future__ import absolute_import from __future__ import division import struct import numpy import six from gnuradio import gru from . import crc def conv_packed_binary_string_to_1_0_string(s): """ '\xAF' --> '10101111' """ r = [] for ch in s: x = ord(ch) for i in range(7,-1,-1): t = (x >> i) & 0x1 r.append(t) return ''.join([chr(x + ord('0')) for x in r]) def conv_1_0_string_to_packed_binary_string(s): """ '10101111' -> ('\xAF', False) Basically the inverse of conv_packed_binary_string_to_1_0_string, but also returns a flag indicating if we had to pad with leading zeros to get to a multiple of 8. """ if not is_1_0_string(s): raise ValueError("Input must be a string containing only 0's and 1's") # pad to multiple of 8 padded = False rem = len(s) % 8 if rem != 0: npad = 8 - rem s = '0' * npad + s padded = True assert len(s) % 8 == 0 r = [] i = 0 while i < len(s): t = 0 for j in range(8): t = (t << 1) | (ord(s[i + j]) - ord('0')) r.append(chr(t)) i += 8 return (''.join(r), padded) default_access_code = \ conv_packed_binary_string_to_1_0_string('\xAC\xDD\xA4\xE2\xF2\x8C\x20\xFC') default_preamble = \ conv_packed_binary_string_to_1_0_string('\xA4\xF2') def is_1_0_string(s): if not isinstance(s, str): return False for ch in s: if not ch in ('0', '1'): return False return True def string_to_hex_list(s): return [hex(ord(x)) for x in s] def whiten(s, o): sa = numpy.fromstring(s, numpy.uint8) z = sa ^ random_mask_vec8[o:len(sa)+o] return z.tostring() def dewhiten(s, o): return whiten(s, o) # self inverse def make_header(payload_len, whitener_offset=0): # Upper nibble is offset, lower 12 bits is len val = ((whitener_offset & 0xf) << 12) | (payload_len & 0x0fff) #print("offset =", whitener_offset, " len =", payload_len, " val=", val) return struct.pack(b'!HH', val, val) def make_packet(payload, samples_per_symbol, bits_per_symbol, preamble=default_preamble, access_code=default_access_code, pad_for_usrp=True, whitener_offset=0, whitening=True, calc_crc=True): """ Build a packet, given access code, payload, and whitener offset Args: payload: packet payload, len [0, 4096] samples_per_symbol: samples per symbol (needed for padding calculation) (int) bits_per_symbol: (needed for padding calculation) (int) preamble: string of ascii 0's and 1's access_code: string of ascii 0's and 1's pad_for_usrp: If true, packets are padded such that they end up a multiple of 128 samples(512 bytes) whitener_offset: offset into whitener string to use [0-16) whitening: Whether to turn on data whitening(scrambling) (boolean) calc_crc: Whether to calculate CRC32 or not (boolean) Packet will have access code at the beginning, followed by length, payload and finally CRC-32. """ if not is_1_0_string(preamble): raise ValueError("preamble must be a string containing only 0's and 1's (%r)" % (preamble,)) if not is_1_0_string(access_code): raise ValueError("access_code must be a string containing only 0's and 1's (%r)" % (access_code,)) if not whitener_offset >=0 and whitener_offset < 16: raise ValueError("whitener_offset must be between 0 and 15, inclusive (%i)" % (whitener_offset,)) (packed_access_code, padded) = conv_1_0_string_to_packed_binary_string(access_code) (packed_preamble, ignore) = conv_1_0_string_to_packed_binary_string(preamble) if(calc_crc): payload_with_crc = crc.gen_and_append_crc32(payload) else: payload_with_crc = payload #print("outbound crc =", string_to_hex_list(payload_with_crc[-4:])) L = len(payload_with_crc) MAXLEN = len(random_mask_tuple) if L > MAXLEN: raise ValueError("len(payload) must be in [0, %d]" % (MAXLEN,)) if whitening: pkt = b''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset), whiten(payload_with_crc, whitener_offset), b'\x55')) else: pkt = b''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset), (payload_with_crc), b'\x55')) if pad_for_usrp: pkt = pkt + (_npadding_bytes(len(pkt), int(samples_per_symbol), bits_per_symbol) * b'\x55') #print("make_packet: len(pkt) =", len(pkt)) return pkt def _npadding_bytes(pkt_byte_len, samples_per_symbol, bits_per_symbol): """ Generate sufficient padding such that each packet ultimately ends up being a multiple of 512 bytes when sent across the USB. We send 4-byte samples across the USB (16-bit I and 16-bit Q), thus we want to pad so that after modulation the resulting packet is a multiple of 128 samples. Args: ptk_byte_len: len in bytes of packet, not including padding. samples_per_symbol: samples per bit (1 bit / symbolwidth GMSK) (int) bits_per_symbol: bits per symbol (log2(modulation order)) (int) Returns: number of bytes of padding to append. """ modulus = 128 byte_modulus = gru.lcm(modulus // 8, samples_per_symbol) * bits_per_symbol // samples_per_symbol r = pkt_byte_len % byte_modulus if r == 0: return 0 return byte_modulus - r def unmake_packet(whitened_payload_with_crc, whitener_offset=0, dewhitening=True, check_crc=True): """ Return (ok, payload) Args: whitened_payload_with_crc: string whitener_offset: integer offset into whitener table dewhitening: True if we should run this through the dewhitener check_crc: True if we should check the CRC of the packet """ if dewhitening: payload_with_crc = dewhiten(whitened_payload_with_crc, whitener_offset) else: payload_with_crc = (whitened_payload_with_crc) if check_crc: ok, payload = crc.check_crc32(payload_with_crc) else: payload = payload_with_crc ok = True if 0: print("payload_with_crc =", string_to_hex_list(payload_with_crc)) print("ok = %r, len(payload) = %d" % (ok, len(payload))) print("payload =", string_to_hex_list(payload)) print("") return ok, payload # FYI, this PN code is the output of a 15-bit LFSR random_mask_tuple = ( 255, 63, 0, 16, 0, 12, 0, 5, 192, 3, 16, 1, 204, 0, 85, 192, 63, 16, 16, 12, 12, 5, 197, 195, 19, 17, 205, 204, 85, 149, 255, 47, 0, 28, 0, 9, 192, 6, 208, 2, 220, 1, 153, 192, 106, 208, 47, 28, 28, 9, 201, 198, 214, 210, 222, 221, 152, 89, 170, 186, 255, 51, 0, 21, 192, 15, 16, 4, 12, 3, 69, 193, 243, 16, 69, 204, 51, 21, 213, 207, 31, 20, 8, 15, 70, 132, 50, 227, 85, 137, 255, 38, 192, 26, 208, 11, 28, 7, 73, 194, 182, 209, 182, 220, 118, 217, 230, 218, 202, 219, 23, 27, 78, 139, 116, 103, 103, 106, 170, 175, 63, 60, 16, 17, 204, 12, 85, 197, 255, 19, 0, 13, 192, 5, 144, 3, 44, 1, 221, 192, 89, 144, 58, 236, 19, 13, 205, 197, 149, 147, 47, 45, 220, 29, 153, 201, 170, 214, 255, 30, 192, 8, 80, 6, 188, 2, 241, 193, 132, 80, 99, 124, 41, 225, 222, 200, 88, 86, 186, 190, 243, 48, 69, 212, 51, 31, 85, 200, 63, 22, 144, 14, 236, 4, 77, 195, 117, 145, 231, 44, 74, 157, 247, 41, 134, 158, 226, 232, 73, 142, 182, 228, 118, 203, 102, 215, 106, 222, 175, 24, 124, 10, 161, 199, 56, 82, 146, 189, 173, 177, 189, 180, 113, 183, 100, 118, 171, 102, 255, 106, 192, 47, 16, 28, 12, 9, 197, 198, 211, 18, 221, 205, 153, 149, 170, 239, 63, 12, 16, 5, 204, 3, 21, 193, 207, 16, 84, 12, 63, 69, 208, 51, 28, 21, 201, 207, 22, 212, 14, 223, 68, 88, 51, 122, 149, 227, 47, 9, 220, 6, 217, 194, 218, 209, 155, 28, 107, 73, 239, 118, 204, 38, 213, 218, 223, 27, 24, 11, 74, 135, 119, 34, 166, 153, 186, 234, 243, 15, 5, 196, 3, 19, 65, 205, 240, 85, 132, 63, 35, 80, 25, 252, 10, 193, 199, 16, 82, 140, 61, 165, 209, 187, 28, 115, 73, 229, 246, 203, 6, 215, 66, 222, 177, 152, 116, 106, 167, 111, 58, 172, 19, 61, 205, 209, 149, 156, 111, 41, 236, 30, 205, 200, 85, 150, 191, 46, 240, 28, 68, 9, 243, 70, 197, 242, 211, 5, 157, 195, 41, 145, 222, 236, 88, 77, 250, 181, 131, 55, 33, 214, 152, 94, 234, 184, 79, 50, 180, 21, 183, 79, 54, 180, 22, 247, 78, 198, 180, 82, 247, 125, 134, 161, 162, 248, 121, 130, 162, 225, 185, 136, 114, 230, 165, 138, 251, 39, 3, 90, 129, 251, 32, 67, 88, 49, 250, 148, 67, 47, 113, 220, 36, 89, 219, 122, 219, 99, 27, 105, 203, 110, 215, 108, 94, 173, 248, 125, 130, 161, 161, 184, 120, 114, 162, 165, 185, 187, 50, 243, 85, 133, 255, 35, 0, 25, 192, 10, 208, 7, 28, 2, 137, 193, 166, 208, 122, 220, 35, 25, 217, 202, 218, 215, 27, 30, 139, 72, 103, 118, 170, 166, 255, 58, 192, 19, 16, 13, 204, 5, 149, 195, 47, 17, 220, 12, 89, 197, 250, 211, 3, 29, 193, 201, 144, 86, 236, 62, 205, 208, 85, 156, 63, 41, 208, 30, 220, 8, 89, 198, 186, 210, 243, 29, 133, 201, 163, 22, 249, 206, 194, 212, 81, 159, 124, 104, 33, 238, 152, 76, 106, 181, 239, 55, 12, 22, 133, 206, 227, 20, 73, 207, 118, 212, 38, 223, 90, 216, 59, 26, 147, 75, 45, 247, 93, 134, 185, 162, 242, 249, 133, 130, 227, 33, 137, 216, 102, 218, 170, 219, 63, 27, 80, 11, 124, 7, 97, 194, 168, 81, 190, 188, 112, 113, 228, 36, 75, 91, 119, 123, 102, 163, 106, 249, 239, 2, 204, 1, 149, 192, 111, 16, 44, 12, 29, 197, 201, 147, 22, 237, 206, 205, 148, 85, 175, 127, 60, 32, 17, 216, 12, 90, 133, 251, 35, 3, 89, 193, 250, 208, 67, 28, 49, 201, 212, 86, 223, 126, 216, 32, 90, 152, 59, 42, 147, 95, 45, 248, 29, 130, 137, 161, 166, 248, 122, 194, 163, 17, 185, 204, 114, 213, 229, 159, 11, 40, 7, 94, 130, 184, 97, 178, 168, 117, 190, 167, 48, 122, 148, 35, 47, 89, 220, 58, 217, 211, 26, 221, 203, 25, 151, 74, 238, 183, 12, 118, 133, 230, 227, 10, 201, 199, 22, 210, 142, 221, 164, 89, 187, 122, 243, 99, 5, 233, 195, 14, 209, 196, 92, 83, 121, 253, 226, 193, 137, 144, 102, 236, 42, 205, 223, 21, 152, 15, 42, 132, 31, 35, 72, 25, 246, 138, 198, 231, 18, 202, 141, 151, 37, 174, 155, 60, 107, 81, 239, 124, 76, 33, 245, 216, 71, 26, 178, 139, 53, 167, 87, 58, 190, 147, 48, 109, 212, 45, 159, 93, 168, 57, 190, 146, 240, 109, 132, 45, 163, 93, 185, 249, 178, 194, 245, 145, 135, 44, 98, 157, 233, 169, 142, 254, 228, 64, 75, 112, 55, 100, 22, 171, 78, 255, 116, 64, 39, 112, 26, 164, 11, 59, 71, 83, 114, 189, 229, 177, 139, 52, 103, 87, 106, 190, 175, 48, 124, 20, 33, 207, 88, 84, 58, 191, 83, 48, 61, 212, 17, 159, 76, 104, 53, 238, 151, 12, 110, 133, 236, 99, 13, 233, 197, 142, 211, 36, 93, 219, 121, 155, 98, 235, 105, 143, 110, 228, 44, 75, 93, 247, 121, 134, 162, 226, 249, 137, 130, 230, 225, 138, 200, 103, 22, 170, 142, 255, 36, 64, 27, 112, 11, 100, 7, 107, 66, 175, 113, 188, 36, 113, 219, 100, 91, 107, 123, 111, 99, 108, 41, 237, 222, 205, 152, 85, 170, 191, 63, 48, 16, 20, 12, 15, 69, 196, 51, 19, 85, 205, 255, 21, 128, 15, 32, 4, 24, 3, 74, 129, 247, 32, 70, 152, 50, 234, 149, 143, 47, 36, 28, 27, 73, 203, 118, 215, 102, 222, 170, 216, 127, 26, 160, 11, 56, 7, 82, 130, 189, 161, 177, 184, 116, 114, 167, 101, 186, 171, 51, 63, 85, 208, 63, 28, 16, 9, 204, 6, 213, 194, 223, 17, 152, 12, 106, 133, 239, 35, 12, 25, 197, 202, 211, 23, 29, 206, 137, 148, 102, 239, 106, 204, 47, 21, 220, 15, 25, 196, 10, 211, 71, 29, 242, 137, 133, 166, 227, 58, 201, 211, 22, 221, 206, 217, 148, 90, 239, 123, 12, 35, 69, 217, 243, 26, 197, 203, 19, 23, 77, 206, 181, 148, 119, 47, 102, 156, 42, 233, 223, 14, 216, 4, 90, 131, 123, 33, 227, 88, 73, 250, 182, 195, 54, 209, 214, 220, 94, 217, 248, 90, 194, 187, 17, 179, 76, 117, 245, 231, 7, 10, 130, 135, 33, 162, 152, 121, 170, 162, 255, 57, 128, 18, 224, 13, 136, 5, 166, 131, 58, 225, 211, 8, 93, 198, 185, 146, 242, 237, 133, 141, 163, 37, 185, 219, 50, 219, 85, 155, 127, 43, 96, 31, 104, 8, 46, 134, 156, 98, 233, 233, 142, 206, 228, 84, 75, 127, 119, 96, 38, 168, 26, 254, 139, 0, 103, 64, 42, 176, 31, 52, 8, 23, 70, 142, 178, 228, 117, 139, 103, 39, 106, 154, 175, 43, 60, 31, 81, 200, 60, 86, 145, 254, 236, 64, 77, 240, 53, 132, 23, 35, 78, 153, 244, 106, 199, 111, 18, 172, 13, 189, 197, 177, 147, 52, 109, 215, 109, 158, 173, 168, 125, 190, 161, 176, 120, 116, 34, 167, 89, 186, 186, 243, 51, 5, 213, 195, 31, 17, 200, 12, 86, 133, 254, 227, 0, 73, 192, 54, 208, 22, 220, 14, 217, 196, 90, 211, 123, 29, 227, 73, 137, 246, 230, 198, 202, 210, 215, 29, 158, 137, 168, 102, 254, 170, 192, 127, 16, 32, 12, 24, 5, 202, 131, 23, 33, 206, 152, 84, 106, 191, 111, 48, 44, 20, 29, 207, 73, 148, 54, 239, 86, 204, 62, 213, 208, 95, 28, 56, 9, 210, 134, 221, 162, 217, 185, 154, 242, 235, 5, 143, 67, 36, 49, 219, 84, 91, 127, 123, 96, 35, 104, 25, 238, 138, 204, 103, 21, 234, 143, 15, 36, 4, 27, 67, 75, 113, 247, 100, 70, 171, 114, 255, 101, 128, 43, 32, 31, 88, 8, 58, 134, 147, 34, 237, 217, 141, 154, 229, 171, 11, 63, 71, 80, 50, 188, 21, 177, 207, 52, 84, 23, 127, 78, 160, 52, 120, 23, 98, 142, 169, 164, 126, 251, 96, 67, 104, 49, 238, 148, 76, 111, 117, 236, 39, 13, 218, 133, 155, 35, 43, 89, 223, 122, 216, 35, 26, 153, 203, 42, 215, 95, 30, 184, 8, 114, 134, 165, 162, 251, 57, 131, 82, 225, 253, 136, 65, 166, 176, 122, 244, 35, 7, 89, 194, 186, 209, 179, 28, 117, 201, 231, 22, 202, 142, 215, 36, 94, 155, 120, 107, 98, 175, 105, 188, 46, 241, 220, 68, 89, 243, 122, 197, 227, 19, 9, 205, 198, 213, 146, 223, 45, 152, 29, 170, 137, 191, 38, 240, 26, 196, 11, 19, 71, 77, 242, 181, 133, 183, 35, 54, 153, 214, 234, 222, 207, 24, 84, 10, 191, 71, 48, 50, 148, 21, 175, 79, 60, 52, 17, 215, 76, 94, 181, 248, 119, 2, 166, 129, 186, 224, 115, 8, 37, 198, 155, 18, 235, 77, 143, 117, 164, 39, 59, 90, 147, 123, 45, 227, 93, 137, 249, 166, 194, 250, 209, 131, 28, 97, 201, 232, 86, 206, 190, 212, 112, 95, 100, 56, 43, 82, 159, 125, 168, 33, 190, 152, 112, 106, 164, 47, 59, 92, 19, 121, 205, 226, 213, 137, 159, 38, 232, 26, 206, 139, 20, 103, 79, 106, 180, 47, 55, 92, 22, 185, 206, 242, 212, 69, 159, 115, 40, 37, 222, 155, 24, 107, 74, 175, 119, 60, 38, 145, 218, 236, 91, 13, 251, 69, 131, 115, 33, 229, 216, 75, 26, 183, 75, 54, 183, 86, 246, 190, 198, 240, 82, 196, 61, 147, 81, 173, 252, 125, 129, 225, 160, 72, 120, 54, 162, 150, 249, 174, 194, 252, 81, 129, 252, 96, 65, 232, 48, 78, 148, 52, 111, 87, 108, 62, 173, 208, 125, 156, 33, 169, 216, 126, 218, 160, 91, 56, 59, 82, 147, 125, 173, 225, 189, 136, 113, 166, 164, 122, 251, 99, 3, 105, 193, 238, 208, 76, 92, 53, 249, 215, 2, 222, 129, 152, 96, 106, 168, 47, 62, 156, 16, 105, 204, 46, 213, 220, 95, 25, 248, 10, 194, 135, 17, 162, 140, 121, 165, 226, 251, 9, 131, 70, 225, 242, 200, 69, 150, 179, 46, 245, 220, 71, 25, 242, 138, 197, 167, 19, 58, 141, 211, 37, 157, 219, 41, 155, 94, 235, 120, 79, 98, 180, 41, 183, 94, 246, 184, 70, 242, 178, 197, 181, 147, 55, 45, 214, 157, 158, 233, 168, 78, 254, 180, 64, 119, 112, 38, 164, 26, 251, 75, 3, 119, 65, 230, 176, 74, 244, 55, 7, 86, 130, 190, 225, 176, 72, 116, 54, 167, 86, 250, 190, 195, 48, 81, 212, 60, 95, 81, 248, 60, 66, 145, 241, 172, 68, 125, 243, 97, 133, 232, 99, 14, 169, 196, 126, 211, 96, 93, 232, 57, 142, 146, 228, 109, 139, 109, 167, 109, 186, 173, 179, 61, 181, 209, 183, 28, 118, 137, 230, 230, 202, 202, 215, 23, 30, 142, 136, 100, 102, 171, 106, 255, 111, 0, 44, 0, 29, 192, 9, 144, 6, 236, 2, 205, 193, 149, 144, 111, 44, 44, 29, 221, 201, 153, 150, 234, 238, 207, 12, 84, 5, 255, 67, 0, 49, 192, 20, 80, 15, 124, 4, 33, 195, 88, 81, 250, 188, 67, 49, 241, 212, 68, 95, 115, 120, 37, 226, 155, 9, 171, 70, 255, 114, 192, 37, 144, 27, 44, 11, 93, 199, 121, 146, 162, 237, 185, 141, 178, 229, 181, 139, 55, 39, 86, 154, 190, 235, 48, 79, 84, 52, 63, 87, 80, 62, 188, 16, 113, 204, 36, 85, 219, 127, 27, 96, 11, 104, 7, 110, 130, 172, 97, 189, 232, 113, 142, 164, 100, 123, 107, 99, 111, 105, 236, 46, 205, 220, 85, 153, 255, 42, 192, 31, 16, 8, 12, 6, 133, 194, 227, 17, 137, 204, 102, 213, 234, 223, 15, 24, 4, 10, 131, 71, 33, 242, 152, 69, 170, 179, 63, 53, 208, 23, 28, 14, 137, 196, 102, 211, 106, 221, 239, 25, 140, 10, 229, 199, 11, 18, 135, 77, 162, 181, 185, 183, 50, 246, 149, 134, 239, 34, 204, 25, 149, 202, 239, 23, 12, 14, 133, 196, 99, 19, 105, 205, 238, 213, 140, 95, 37, 248, 27, 2, 139, 65, 167, 112, 122, 164, 35, 59, 89, 211, 122, 221, 227, 25, 137, 202, 230, 215, 10, 222, 135, 24, 98, 138, 169, 167, 62, 250, 144, 67, 44, 49, 221, 212, 89, 159, 122, 232, 35, 14, 153, 196, 106, 211, 111, 29, 236, 9, 141, 198, 229, 146, 203, 45, 151, 93, 174, 185, 188, 114, 241, 229, 132, 75, 35, 119, 89, 230, 186, 202, 243, 23, 5, 206, 131, 20, 97, 207, 104, 84, 46, 191, 92, 112, 57, 228, 18, 203, 77, 151, 117, 174, 167, 60, 122, 145, 227, 44, 73, 221, 246, 217, 134, 218, 226, 219, 9, 155, 70, 235, 114, 207, 101, 148, 43, 47, 95, 92, 56, 57, 210, 146, 221, 173, 153, 189, 170, 241, 191, 4, 112, 3, 100, 1, 235, 64, 79, 112, 52, 36, 23, 91, 78, 187, 116, 115, 103, 101, 234, 171, 15, 63, 68, 16, 51, 76, 21, 245, 207, 7, 20, 2, 143, 65, 164, 48, 123, 84, 35, 127, 89, 224, 58, 200, 19, 22, 141, 206, 229, 148, 75, 47, 119, 92, 38, 185, 218, 242, 219, 5, 155, 67, 43, 113, 223, 100, 88, 43, 122, 159, 99, 40, 41, 222, 158, 216, 104, 90, 174, 187, 60, 115, 81, 229, 252, 75, 1, 247, 64, 70, 176, 50, 244, 21, 135, 79, 34, 180, 25, 183, 74, 246, 183, 6, 246, 130, 198, 225, 146, 200, 109, 150, 173, 174, 253, 188, 65, 177, 240, 116, 68, 39, 115, 90, 165, 251, 59, 3, 83, 65, 253, 240, 65, 132, 48, 99, 84, 41, 255, 94, 192, 56, 80, 18, 188, 13, 177, 197, 180, 83, 55, 125, 214, 161, 158, 248, 104, 66, 174, 177, 188, 116, 113, 231, 100, 74, 171, 119, 63, 102, 144, 42, 236, 31, 13, 200, 5, 150, 131, 46, 225, 220, 72, 89, 246, 186, 198, 243, 18, 197, 205, 147, 21, 173, 207, 61, 148, 17, 175, 76, 124, 53, 225, 215, 8, 94, 134, 184, 98, 242, 169, 133, 190, 227, 48, 73, 212, 54, 223, 86, 216, 62, 218, 144, 91, 44, 59, 93, 211, 121, 157, 226, 233, 137, 142, 230, 228, 74, 203, 119, 23, 102, 142, 170, 228, 127, 11, 96, 7, 104, 2, 174, 129, 188, 96, 113, 232, 36, 78, 155, 116, 107, 103, 111, 106, 172, 47, 61, 220, 17, 153, 204, 106, 213, 239, 31, 12, 8, 5, 198, 131, 18, 225, 205, 136, 85, 166, 191, 58, 240, 19, 4, 13, 195, 69, 145, 243, 44, 69, 221, 243, 25, 133, 202, 227, 23, 9, 206, 134, 212, 98, 223, 105, 152, 46, 234, 156, 79, 41, 244, 30, 199, 72, 82, 182, 189, 182, 241, 182, 196, 118, 211, 102, 221, 234, 217, 143, 26, 228, 11, 11, 71, 71, 114, 178, 165, 181, 187, 55, 51, 86, 149, 254, 239, 0, 76, 0, 53, 192, 23, 16, 14, 140, 4, 101, 195, 107, 17, 239, 76, 76, 53, 245, 215, 7, 30, 130, 136, 97, 166, 168, 122, 254, 163, 0, 121, 192, 34, 208, 25, 156, 10, 233, 199, 14, 210, 132, 93, 163, 121, 185, 226, 242, 201, 133, 150, 227, 46, 201, 220, 86, 217, 254, 218, 192, 91, 16, 59, 76, 19, 117, 205, 231, 21, 138, 143, 39, 36, 26, 155, 75, 43, 119, 95, 102, 184, 42, 242, 159, 5, 168, 3, 62, 129, 208, 96, 92, 40, 57, 222, 146, 216, 109, 154, 173, 171, 61, 191, 81, 176, 60, 116, 17, 231, 76, 74, 181, 247, 55, 6, 150, 130, 238, 225, 140, 72, 101, 246, 171, 6, 255, 66, 192, 49, 144, 20, 108, 15, 109, 196, 45, 147, 93, 173, 249, 189, 130, 241, 161, 132, 120, 99, 98, 169, 233, 190, 206, 240, 84, 68, 63, 115, 80, 37, 252, 27, 1, 203, 64, 87, 112, 62, 164, 16, 123, 76, 35, 117, 217, 231, 26, 202, 139, 23, 39, 78, 154, 180, 107, 55, 111, 86, 172, 62, 253, 208, 65, 156, 48, 105, 212, 46, 223, 92, 88, 57, 250, 146, 195, 45, 145, 221, 172, 89, 189, 250, 241, 131, 4, 97, 195, 104, 81, 238, 188, 76, 113, 245, 228, 71, 11, 114, 135, 101, 162, 171, 57, 191, 82, 240, 61, 132, 17, 163, 76, 121, 245, 226, 199, 9, 146, 134, 237, 162, 205, 185, 149, 178, 239, 53, 140, 23, 37, 206, 155, 20, 107, 79, 111, 116, 44, 39, 93, 218, 185, 155, 50, 235, 85, 143, 127, 36, 32, 27, 88, 11, 122, 135, 99, 34, 169, 217, 190, 218, 240, 91, 4, 59, 67, 83, 113, 253, 228, 65, 139, 112, 103, 100, 42, 171, 95, 63, 120, 16, 34, 140, 25, 165, 202, 251, 23, 3, 78, 129, 244, 96, 71, 104, 50, 174, 149, 188, 111, 49, 236, 20, 77, 207, 117, 148, 39, 47, 90, 156, 59, 41, 211, 94, 221, 248, 89, 130, 186, 225, 179, 8, 117, 198, 167, 18, 250, 141, 131, 37, 161, 219, 56, 91, 82, 187, 125, 179, 97, 181, 232, 119, 14, 166, 132, 122, 227, 99, 9, 233, 198, 206, 210, 212, 93, 159, 121, 168, 34, 254, 153, 128, 106, 224, 47, 8, 28, 6, 137, 194, 230, 209, 138, 220, 103, 25, 234, 138, 207, 39, 20, 26, 143, 75, 36, 55, 91, 86, 187, 126, 243, 96, 69, 232, 51, 14, 149, 196, 111, 19, 108, 13, 237, 197, 141, 147, 37, 173, 219, 61, 155, 81, 171, 124, 127, 97, 224, 40, 72, 30, 182, 136, 118, 230, 166, 202, 250, 215, 3, 30, 129, 200, 96, 86, 168, 62, 254, 144, 64, 108, 48, 45, 212, 29, 159, 73, 168, 54, 254, 150, 192, 110, 208, 44, 92, 29, 249, 201, 130, 214, 225, 158, 200, 104, 86, 174, 190, 252, 112, 65, 228, 48, 75, 84, 55, 127, 86, 160, 62, 248, 16, 66, 140, 49, 165, 212, 123, 31, 99, 72, 41, 246, 158, 198, 232, 82, 206, 189, 148, 113, 175, 100, 124, 43, 97, 223, 104, 88, 46, 186, 156, 115, 41, 229, 222, 203, 24, 87, 74, 190, 183, 48, 118, 148, 38, 239, 90, 204, 59, 21, 211, 79, 29, 244, 9, 135, 70, 226, 178, 201, 181, 150, 247, 46, 198, 156, 82, 233, 253, 142, 193, 164, 80, 123, 124, 35, 97, 217, 232, 90, 206, 187, 20, 115, 79, 101, 244, 43, 7, 95, 66, 184, 49, 178, 148, 117, 175, 103, 60, 42, 145, 223, 44, 88, 29, 250, 137, 131, 38, 225, 218, 200, 91, 22, 187, 78, 243, 116, 69, 231, 115, 10, 165, 199, 59, 18, 147, 77, 173, 245, 189, 135, 49, 162, 148, 121, 175, 98, 252, 41, 129, 222, 224, 88, 72, 58, 182, 147, 54, 237, 214, 205, 158, 213, 168, 95, 62, 184, 16, 114, 140, 37, 165, 219, 59, 27, 83, 75, 125, 247, 97, 134, 168, 98, 254, 169, 128, 126, 224, 32, 72, 24, 54, 138, 150, 231, 46, 202, 156, 87, 41, 254, 158, 192, 104, 80, 46, 188, 28, 113, 201, 228, 86, 203, 126, 215, 96, 94, 168, 56, 126, 146, 160, 109, 184, 45, 178, 157, 181, 169, 183, 62, 246, 144, 70, 236, 50, 205, 213, 149, 159, 47, 40, 28, 30, 137, 200, 102, 214, 170, 222, 255, 24, 64, 10, 176, 7, 52, 2, 151, 65, 174, 176, 124, 116, 33, 231, 88, 74, 186, 183, 51, 54, 149, 214, 239, 30, 204, 8, 85, 198, 191, 18, 240, 13, 132, 5, 163, 67, 57, 241, 210, 196, 93, 147, 121, 173, 226, 253, 137, 129, 166, 224, 122, 200, 35, 22, 153, 206, 234, 212, 79, 31, 116, 8, 39, 70, 154, 178, 235, 53, 143, 87, 36, 62, 155, 80, 107, 124, 47, 97, 220, 40, 89, 222, 186, 216, 115, 26, 165, 203, 59, 23, 83, 78, 189, 244, 113, 135, 100, 98, 171, 105, 191, 110, 240, 44, 68, 29, 243, 73, 133, 246, 227, 6, 201, 194, 214, 209, 158, 220, 104, 89, 238, 186, 204, 115, 21, 229, 207, 11, 20, 7, 79, 66, 180, 49, 183, 84, 118, 191, 102, 240, 42, 196, 31, 19, 72, 13, 246, 133, 134, 227, 34, 201, 217, 150, 218, 238, 219, 12, 91, 69, 251, 115, 3, 101, 193, 235, 16, 79, 76, 52, 53, 215, 87, 30, 190, 136, 112, 102, 164, 42, 251, 95, 3, 120, 1, 226, 128, 73, 160, 54, 248, 22, 194, 142, 209, 164, 92, 123, 121, 227, 98, 201, 233, 150, 206, 238, 212, 76, 95, 117, 248, 39, 2, 154, 129, 171, 32, 127, 88, 32, 58, 152, 19, 42, 141, 223, 37, 152, 27, 42, 139, 95, 39, 120, 26, 162, 139, 57, 167, 82, 250, 189, 131, 49, 161, 212, 120, 95, 98, 184, 41, 178, 158, 245, 168, 71, 62, 178, 144, 117, 172, 39, 61, 218, 145, 155, 44, 107, 93, 239, 121, 140, 34, 229, 217, 139, 26, 231, 75, 10, 183, 71, 54, 178, 150, 245, 174, 199, 60, 82, 145, 253, 172, 65, 189, 240, 113, 132, 36, 99, 91, 105, 251, 110, 195, 108, 81, 237, 252, 77, 129, 245, 160, 71, 56, 50, 146, 149, 173, 175, 61, 188, 17, 177, 204, 116, 85, 231, 127, 10, 160, 7, 56, 2, 146, 129, 173, 160, 125, 184, 33, 178, 152, 117, 170, 167, 63, 58, 144, 19, 44, 13, 221, 197, 153, 147, 42, 237, 223, 13, 152, 5, 170, 131, 63, 33, 208, 24, 92, 10, 185, 199, 50, 210, 149, 157, 175, 41, 188, 30, 241, 200, 68, 86, 179, 126, 245, 224, 71, 8, 50, 134, 149, 162, 239, 57, 140, 18, 229, 205, 139, 21, 167, 79, 58, 180, 19, 55, 77, 214, 181, 158, 247, 40, 70, 158, 178, 232, 117, 142, 167, 36, 122, 155, 99, 43, 105, 223, 110, 216, 44, 90, 157, 251, 41, 131, 94, 225, 248, 72, 66, 182, 177, 182, 244, 118, 199, 102, 210, 170, 221, 191, 25, 176, 10, 244, 7, 7, 66, 130, 177, 161, 180, 120, 119, 98, 166, 169, 186, 254, 243, 0, 69, 192, 51, 16, 21, 204, 15, 21, 196, 15, 19, 68, 13, 243, 69, 133, 243, 35, 5, 217, 195, 26, 209, 203, 28, 87, 73, 254, 182, 192, 118, 208, 38, 220, 26, 217, 203, 26, 215, 75, 30, 183, 72, 118, 182, 166, 246, 250, 198, 195, 18, 209, 205, 156, 85, 169, 255, 62, 192, 16, 80, 12, 60, 5, 209, 195, 28, 81, 201, 252, 86, 193, 254, 208, 64, 92, 48, 57, 212, 18, 223, 77, 152, 53, 170, 151, 63, 46, 144, 28, 108, 9, 237, 198, 205, 146, 213, 173, 159, 61, 168, 17, 190, 140, 112, 101, 228, 43, 11, 95, 71, 120, 50, 162, 149, 185, 175, 50, 252, 21, 129, 207, 32, 84, 24, 63, 74, 144, 55, 44, 22, 157, 206, 233, 148, 78, 239, 116, 76, 39, 117, 218, 167, 27, 58, 139, 83, 39, 125, 218, 161, 155, 56, 107, 82, 175, 125, 188, 33, 177, 216, 116, 90, 167, 123, 58, 163, 83, 57, 253, 210, 193, 157, 144, 105, 172, 46, 253, 220, 65, 153, 240, 106, 196, 47, 19, 92, 13, 249, 197, 130, 211, 33, 157, 216, 105, 154, 174, 235, 60, 79, 81, 244, 60, 71, 81, 242, 188, 69, 177, 243, 52, 69, 215, 115, 30, 165, 200, 123, 22, 163, 78, 249, 244, 66, 199, 113, 146, 164, 109, 187, 109, 179, 109, 181, 237, 183, 13, 182, 133, 182, 227, 54, 201, 214, 214, 222, 222, 216, 88, 90, 186, 187, 51, 51, 255, 63 ) random_mask_vec8 = numpy.array(random_mask_tuple, numpy.uint8)
jdemel/gnuradio
gr-digital/python/digital/packet_utils.py
Python
gpl-3.0
27,833
<?php /** * * @package mahara * @subpackage blocktype-recentforumposts * @author Nigel McNie * @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later * @copyright For copyright information on Mahara, please see the README file distributed with this software. * @copyright (C) 2009 Nigel McNie http://nigel.mcnie.name/ * */ defined('INTERNAL') || die(); class PluginBlocktypeRecentForumPosts extends MaharaCoreBlocktype { public static function get_title() { return get_string('title', 'blocktype.recentforumposts'); } public static function get_description() { return get_string('description', 'blocktype.recentforumposts'); } public static function get_categories() { return array('general' => 23000); } private static function get_group(BlockInstance $instance) { static $groups = array(); $block = $instance->get('id'); if (!isset($groups[$block])) { // When this block is in a group view it should always display the // forum posts from that group $groupid = $instance->get_view()->get('group'); $configdata = $instance->get('configdata'); if (!$groupid && !empty($configdata['groupid'])) { $groupid = intval($configdata['groupid']); } if ($groupid) { $groups[$block] = get_record_select('group', 'id = ? AND deleted = 0', array($groupid), '*, ' . db_format_tsfield('ctime')); } else { $groups[$block] = false; } } return $groups[$block]; } public static function render_instance(BlockInstance $instance, $editing=false) { if ($group = self::get_group($instance)) { require_once('group.php'); $role = group_user_access($group->id); if ($role || $group->public) { $limit = 5; $configdata = $instance->get('configdata'); if (!empty($configdata['limit'])) { $limit = intval($configdata['limit']); } $foruminfo = get_records_sql_array(' SELECT p.id, p.subject, p.body, p.poster, p.topic, t.forum, pt.subject AS topicname, u.firstname, u.lastname, u.username, u.preferredname, u.email, u.profileicon, u.admin, u.staff, u.deleted, u.urlid FROM {interaction_forum_post} p INNER JOIN {interaction_forum_topic} t ON (t.id = p.topic) INNER JOIN {interaction_instance} i ON (i.id = t.forum) INNER JOIN {interaction_forum_post} pt ON (pt.topic = p.topic AND pt.parent IS NULL) INNER JOIN {usr} u ON p.poster = u.id WHERE i.group = ? AND i.deleted = 0 AND t.deleted = 0 AND p.deleted = 0 ORDER BY p.ctime DESC', array($group->id), 0, $limit ); if ($foruminfo) { $userfields = array( 'firstname', 'lastname', 'username', 'preferredname', 'email', 'profileicon', 'admin', 'staff', 'deleted', 'urlid', ); foreach ($foruminfo as $f) { $f->author = (object) array('id' => $f->poster); foreach ($userfields as $uf) { $f->author->$uf = $f->$uf; unset($f->$uf); } } } $smarty = smarty_core(); $smarty->assign('group', $group); $smarty->assign('foruminfo', $foruminfo); if ($instance->get_view()->get('type') == 'grouphomepage') { return $smarty->fetch('blocktype:recentforumposts:latestforumposts.tpl'); } return $smarty->fetch('blocktype:recentforumposts:recentforumposts.tpl'); } } return ''; } public static function has_instance_config() { return true; } public static function instance_config_form(BlockInstance $instance) { global $USER; $elements = array(); $groupid = $instance->get_view()->get('group'); $configdata = $instance->get('configdata'); if ($groupid || $instance->get_view()->get('institution')) { // This block will show recent forum posts from this group $elements['groupid'] = array( 'type' => 'hidden', 'value' => $groupid, ); } else { // Allow the user to choose a group they're in to show posts for if (!empty($configdata['groupid'])) { $groupid = intval($configdata['groupid']); $group = get_record_select('group', 'id = ? AND deleted = 0', array($groupid), '*, ' . db_format_tsfield('ctime')); } $usergroups = get_records_sql_array( "SELECT g.id, g.name FROM {group} g JOIN {group_member} gm ON (gm.group = g.id) WHERE gm.member = ? AND g.deleted = 0 ORDER BY g.name", array($USER->get('id'))); if ($usergroups) { $choosablegroups = array(); foreach ($usergroups as $group) { $choosablegroups[$group->id] = $group->name; } $elements['groupid'] = array( 'type' => 'select', 'title' => get_string('group', 'blocktype.recentforumposts'), 'options' => $choosablegroups, 'collapseifoneoption' => false, 'defaultvalue' => $groupid, 'rules' => array( 'required' => true, ), ); } } if (isset($elements['groupid'])) { $elements['limit'] = array( 'type' => 'text', 'title' => get_string('poststoshow', 'blocktype.recentforumposts'), 'description' => get_string('poststoshowdescription', 'blocktype.recentforumposts'), 'defaultvalue' => (isset($configdata['limit'])) ? intval($configdata['limit']) : 5, 'size' => 3, 'minvalue' => 1, 'maxvalue' => 100, ); } else { $elements = array( 'whoops' => array( 'type' => 'html', 'value' => '<p class="noartefacts">' . get_string('nogroupstochoosefrom', 'blocktype.recentforumposts') . '</p>', ), ); } return $elements; } public static function default_copy_type() { return 'shallow'; } public static function feed_url(BlockInstance $instance) { if ($group = self::get_group($instance)) { if ($group->public) { return get_config('wwwroot') . 'interaction/forum/atom.php?type=g&id=' . $group->id; } } } public static function get_instance_title(BlockInstance $instance) { if ($instance->get_view()->get('type') == 'grouphomepage') { return get_string('latestforumposts', 'interaction.forum'); } return get_string('title', 'blocktype.recentforumposts'); } public static function should_ajaxify() { return true; } /** * Shouldn't be linked to any artefacts via the view_artefacts table. * * @param BlockInstance $instance * @return multitype: */ public static function get_artefacts(BlockInstance $instance) { return array(); } }
piersharding/mahara
htdocs/blocktype/recentforumposts/lib.php
PHP
gpl-3.0
8,075
package de.metas.ui.web.view.json; import java.util.List; import java.util.Set; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import de.metas.ui.web.document.filter.json.JSONDocumentFilterDescriptor; import de.metas.ui.web.view.ViewCloseAction; import de.metas.ui.web.view.ViewProfileId; import de.metas.ui.web.view.descriptor.IncludedViewLayout; import de.metas.ui.web.view.descriptor.ViewLayout; import de.metas.ui.web.window.datatypes.WindowId; import de.metas.ui.web.window.datatypes.json.JSONDocumentLayoutElement; import de.metas.ui.web.window.datatypes.json.JSONDocumentLayoutOptions; import de.metas.ui.web.window.descriptor.DocumentFieldWidgetType; import lombok.Builder; import lombok.Value; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2016 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public final class JSONViewLayout { public static JSONViewLayout of(final ViewLayout gridLayout, final JSONDocumentLayoutOptions options) { return new JSONViewLayout(gridLayout, options); } @JsonProperty("viewId") @JsonInclude(JsonInclude.Include.NON_EMPTY) private String viewId; // /** i.e. AD_Window_ID */ @JsonProperty("type") @JsonInclude(JsonInclude.Include.NON_NULL) @Deprecated private final WindowId type; @JsonProperty("windowId") @JsonInclude(JsonInclude.Include.NON_NULL) private final WindowId windowId; @JsonProperty("profileId") @JsonInclude(JsonInclude.Include.NON_NULL) private final ViewProfileId profileId; @JsonProperty("caption") @JsonInclude(JsonInclude.Include.NON_NULL) private final String caption; @JsonProperty("description") @JsonInclude(JsonInclude.Include.NON_NULL) private final String description; @JsonProperty("emptyResultText") @JsonInclude(JsonInclude.Include.NON_NULL) private final String emptyResultText; @JsonProperty("emptyResultHint") @JsonInclude(JsonInclude.Include.NON_NULL) private final String emptyResultHint; @JsonProperty("elements") @JsonInclude(JsonInclude.Include.NON_EMPTY) private final List<JSONDocumentLayoutElement> elements; @JsonProperty("filters") @JsonInclude(JsonInclude.Include.NON_EMPTY) private final List<JSONDocumentFilterDescriptor> filters; public static final String PROPERTY_supportAttributes = "supportAttributes"; @JsonProperty(value = PROPERTY_supportAttributes) private boolean supportAttributes; // @JsonProperty("supportTree") private final boolean supportTree; @JsonProperty("collapsible") @JsonInclude(JsonInclude.Include.NON_NULL) private final Boolean collapsible; @JsonProperty("expandedDepth") @JsonInclude(JsonInclude.Include.NON_NULL) private final Integer expandedDepth; @JsonProperty("allowedCloseActions") private final Set<ViewCloseAction> allowedCloseActions; // @JsonProperty("includedView") private final JSONIncludedViewSupport includedView; // @Deprecated @JsonProperty("supportIncludedView") private final boolean supportIncludedView; @Deprecated @JsonProperty("supportIncludedViewOnSelect") private final Boolean supportIncludedViewOnSelect; // // New record support @JsonProperty("supportNewRecord") private boolean supportNewRecord = false; @JsonProperty("newRecordCaption") @JsonInclude(JsonInclude.Include.NON_NULL) private String newRecordCaption = null; // // @JsonProperty("supportOpenRecord") @JsonInclude(JsonInclude.Include.NON_NULL) private final Boolean supportOpenRecord; @JsonProperty("supportGeoLocations") @JsonInclude(JsonInclude.Include.NON_NULL) private final Boolean supportGeoLocations; @JsonProperty("focusOnFieldName") @JsonInclude(JsonInclude.Include.NON_NULL) private final String focusOnFieldName; private JSONViewLayout(final ViewLayout layout, final JSONDocumentLayoutOptions options) { windowId = layout.getWindowId(); type = windowId; profileId = layout.getProfileId(); final String adLanguage = options.getAdLanguage(); caption = layout.getCaption(adLanguage); description = layout.getDescription(adLanguage); emptyResultText = layout.getEmptyResultText(adLanguage); emptyResultHint = layout.getEmptyResultHint(adLanguage); // // Elements List<JSONDocumentLayoutElement> elements = JSONDocumentLayoutElement.ofList(layout.getElements(), options); final String idFieldName = layout.getIdFieldName(); if (options.isDebugShowColumnNamesForCaption() && idFieldName != null && !JSONDocumentLayoutElement.hasField(elements, idFieldName)) { elements = ImmutableList.<JSONDocumentLayoutElement> builder() .add(JSONDocumentLayoutElement.debuggingField(idFieldName, DocumentFieldWidgetType.Text)) .addAll(elements) .build(); } this.elements = elements; filters = JSONDocumentFilterDescriptor.ofCollection(layout.getFilters(), options); supportAttributes = layout.isAttributesSupport(); allowedCloseActions = layout.getAllowedViewCloseActions(); // // Included view includedView = JSONIncludedViewSupport.fromNullable(layout.getIncludedViewLayout()); if (includedView != null) { supportIncludedView = true; supportIncludedViewOnSelect = includedView.isOpenOnSelect() ? Boolean.TRUE : null; } else { supportIncludedView = false; supportIncludedViewOnSelect = null; } // // Tree supportTree = layout.isTreeSupport(); if (supportTree) { collapsible = layout.isTreeCollapsible(); if (collapsible) { expandedDepth = layout.getTreeExpandedDepth(); } else { expandedDepth = null; } } else { collapsible = null; expandedDepth = null; } supportOpenRecord = layout.isAllowOpeningRowDetails(); supportGeoLocations = layout.isGeoLocationSupport(); focusOnFieldName = layout.getFocusOnFieldName(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("AD_Window_ID", windowId) .add("caption", caption) .add("elements", elements.isEmpty() ? null : elements) .add("filters", filters.isEmpty() ? null : filters) .toString(); } public String getCaption() { return caption; } public String getDescription() { return description; } public String getEmptyResultText() { return emptyResultText; } public String getEmptyResultHint() { return emptyResultHint; } public List<JSONDocumentLayoutElement> getElements() { return elements; } public boolean hasElements() { return !elements.isEmpty(); } public List<JSONDocumentFilterDescriptor> getFilters() { return filters; } public boolean isSupportAttributes() { return supportAttributes; } public void setSupportAttributes(final boolean supportAttributes) { this.supportAttributes = supportAttributes; } public boolean isSupportTree() { return supportTree; } public void enableNewRecord(final String newRecordCaption) { supportNewRecord = true; this.newRecordCaption = newRecordCaption; } public void setViewId(final String viewId) { this.viewId = viewId; } @Value @Builder @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public static final class JSONIncludedViewSupport { public static JSONIncludedViewSupport fromNullable(final IncludedViewLayout includedViewLayout) { if (includedViewLayout == null) { return null; } return builder() .openOnSelect(includedViewLayout.isOpenOnSelect()) .blurWhenOpen(includedViewLayout.isBlurWhenOpen()) .build(); } private final boolean openOnSelect; private final boolean blurWhenOpen; } }
metasfresh/metasfresh-webui-api
src/main/java/de/metas/ui/web/view/json/JSONViewLayout.java
Java
gpl-3.0
8,641
# Copyright (C) 2008-2009 Adam Olsen # # 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, 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., 675 Mass Ave, Cambridge, MA 02139, USA. # # # The developers of the Exaile media player hereby grant permission # for non-GPL compatible GStreamer and Exaile plugins to be used and # distributed together with GStreamer and Exaile. This permission is # above and beyond the permissions granted by the GPL license by which # Exaile is covered. If you modify this code, you may extend this # exception to your version of the code, but you are not obligated to # do so. If you do not wish to do so, delete this exception statement # from your version. from metadata._base import BaseFormat from mutagen import oggspeex class SpeexFormat(BaseFormat): MutagenType = oggspeex.OggSpeex writable = True # vim: et sts=4 sw=4
jeromeLB/client175
metadata/speex.py
Python
gpl-3.0
1,397
/** * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.android.settings.applications; import java.util.Collections; import java.util.List; import android.app.ListFragment; import android.app.LoaderManager; import android.content.AsyncTaskLoader; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.Loader; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import at.jclehner.appopsxposed.R; import com.android.settings.applications.AppOpsState.AppOpEntry; public class AppOpsCategory extends ListFragment implements LoaderManager.LoaderCallbacks<List<AppOpEntry>> { private static final int RESULT_APP_DETAILS = 1; AppOpsState mState; // This is the Adapter being used to display the list's data. AppListAdapter mAdapter; String mCurrentPkgName; public AppOpsCategory() { } public AppOpsCategory(AppOpsState.OpsTemplate template) { Bundle args = new Bundle(); args.putParcelable("template", template); setArguments(args); } /** * Helper for determining if the configuration has changed in an interesting * way so we need to rebuild the app list. */ public static class InterestingConfigChanges { final Configuration mLastConfiguration = new Configuration(); int mLastDensity; boolean applyNewConfig(Resources res) { int configChanges = mLastConfiguration.updateFrom(res.getConfiguration()); boolean densityChanged = mLastDensity != res.getDisplayMetrics().densityDpi; if (densityChanged || (configChanges&(ActivityInfo.CONFIG_LOCALE |ActivityInfo.CONFIG_UI_MODE|ActivityInfo.CONFIG_SCREEN_LAYOUT)) != 0) { mLastDensity = res.getDisplayMetrics().densityDpi; return true; } return false; } } /** * Helper class to look for interesting changes to the installed apps * so that the loader can be updated. */ public static class PackageIntentReceiver extends BroadcastReceiver { final AppListLoader mLoader; public PackageIntentReceiver(AppListLoader loader) { mLoader = loader; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_CHANGED); filter.addDataScheme("package"); mLoader.getContext().registerReceiver(this, filter); // Register for events related to sdcard installation. IntentFilter sdFilter = new IntentFilter(); sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE); sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); mLoader.getContext().registerReceiver(this, sdFilter); } @Override public void onReceive(Context context, Intent intent) { // Tell the loader about the change. mLoader.onContentChanged(); } } /** * A custom Loader that loads all of the installed applications. */ public static class AppListLoader extends AsyncTaskLoader<List<AppOpEntry>> { final InterestingConfigChanges mLastConfig = new InterestingConfigChanges(); final AppOpsState mState; final AppOpsState.OpsTemplate mTemplate; final Handler mHandler; List<AppOpEntry> mApps; PackageIntentReceiver mPackageObserver; public AppListLoader(Context context, AppOpsState state, AppOpsState.OpsTemplate template) { super(context); mState = state; mTemplate = template; mHandler = new Handler(); } @Override public List<AppOpEntry> loadInBackground() { //return mState.buildStateWithChangedOpsOnly(); try { return mState.buildState(mTemplate); } catch (final SecurityException e) { mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show(); Log.w("AOX", e); } }); return Collections.emptyList(); } } /** * Called when there is new data to deliver to the client. The * super class will take care of delivering it; the implementation * here just adds a little more logic. */ @Override public void deliverResult(List<AppOpEntry> apps) { if (isReset()) { // An async query came in while the loader is stopped. We // don't need the result. if (apps != null) { onReleaseResources(apps); } } List<AppOpEntry> oldApps = apps; mApps = apps; if (isStarted()) { // If the Loader is currently started, we can immediately // deliver its results. super.deliverResult(apps); } // At this point we can release the resources associated with // 'oldApps' if needed; now that the new result is delivered we // know that it is no longer in use. if (oldApps != null) { onReleaseResources(oldApps); } } /** * Handles a request to start the Loader. */ @Override protected void onStartLoading() { // We don't monitor changed when loading is stopped, so need // to always reload at this point. onContentChanged(); if (mApps != null) { // If we currently have a result available, deliver it // immediately. deliverResult(mApps); } // Start watching for changes in the app data. if (mPackageObserver == null) { mPackageObserver = new PackageIntentReceiver(this); } // Has something interesting in the configuration changed since we // last built the app list? boolean configChange = mLastConfig.applyNewConfig(getContext().getResources()); if (takeContentChanged() || mApps == null || configChange) { // If the data has changed since the last time it was loaded // or is not currently available, start a load. forceLoad(); } } /** * Handles a request to stop the Loader. */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } /** * Handles a request to cancel a load. */ @Override public void onCanceled(List<AppOpEntry> apps) { super.onCanceled(apps); // At this point we can release the resources associated with 'apps' // if needed. onReleaseResources(apps); } /** * Handles a request to completely reset the Loader. */ @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); // At this point we can release the resources associated with 'apps' // if needed. if (mApps != null) { onReleaseResources(mApps); mApps = null; } // Stop monitoring for changes. if (mPackageObserver != null) { getContext().unregisterReceiver(mPackageObserver); mPackageObserver = null; } } /** * Helper function to take care of releasing resources associated * with an actively loaded data set. */ protected void onReleaseResources(List<AppOpEntry> apps) { // For a simple List<> there is nothing to do. For something // like a Cursor, we would close it here. } } public static class AppListAdapter extends BaseAdapter { private final Resources mResources; private final LayoutInflater mInflater; private final AppOpsState mState; private final Context mContext; List<AppOpEntry> mList; public AppListAdapter(Context context, AppOpsState state) { mResources = context.getResources(); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mState = state; mContext = context; } public void setData(List<AppOpEntry> data) { mList = data; notifyDataSetChanged(); } @Override public int getCount() { return mList != null ? mList.size() : 0; } @Override public AppOpEntry getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } /** * Populate new items in the list. */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.app_ops_item, parent, false); } else { view = convertView; } AppOpEntry item = getItem(position); ((ImageView)view.findViewById(R.id.app_icon)).setImageDrawable( item.getAppEntry().getIcon()); ((TextView)view.findViewById(R.id.app_name)).setText(item.getAppEntry().getLabel()); ((TextView)view.findViewById(R.id.op_name)).setText(item.getSummaryText(mContext, mState)); ((TextView)view.findViewById(R.id.op_time)).setText( item.getTimeText(mResources, false)); return view; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mState = new AppOpsState(getActivity()); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Give some text to display if there is no data. In a real // application this would come from a resource. setEmptyText("No applications"); // We have a menu item to show in action bar. setHasOptionsMenu(true); // Create an empty adapter we will use to display the loaded data. mAdapter = new AppListAdapter(getActivity(), mState); setListAdapter(mAdapter); // Start out with a progress indicator. setListShown(false); // Prepare the loader. getLoaderManager().initLoader(0, null, this); } // utility method used to start sub activity private void startApplicationDetailsActivity() { // start new fragment to display extended information Bundle args = new Bundle(); args.putString(AppOpsDetails.ARG_PACKAGE_NAME, mCurrentPkgName); PreferenceActivity pa = (PreferenceActivity)getActivity(); pa.startPreferencePanel(AppOpsDetails.class.getName(), args, R.string.app_ops_settings, null, this, RESULT_APP_DETAILS); } @Override public void onListItemClick(ListView l, View v, int position, long id) { AppOpEntry entry = mAdapter.getItem(position); if (entry != null) { mCurrentPkgName = entry.getAppEntry().getApplicationInfo().packageName; startApplicationDetailsActivity(); } } @Override public Loader<List<AppOpEntry>> onCreateLoader(int id, Bundle args) { Bundle fargs = getArguments(); AppOpsState.OpsTemplate template = null; if (fargs != null) { template = (AppOpsState.OpsTemplate)fargs.getParcelable("template"); } return new AppListLoader(getActivity(), mState, template); } @Override public void onLoadFinished(Loader<List<AppOpEntry>> loader, List<AppOpEntry> data) { // Set the new data in the adapter. mAdapter.setData(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<List<AppOpEntry>> loader) { // Clear the data in the adapter. mAdapter.setData(null); } }
wanam/AppOpsXposed
src/com/android/settings/applications/AppOpsCategory.java
Java
gpl-3.0
13,860
/* This file is part of LibQtLua. LibQtLua is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LibQtLua 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 Lesser General Public License along with LibQtLua. If not, see <http://www.gnu.org/licenses/>. Copyright (C) 2008, Alexandre Becoulet <alexandre.becoulet@free.fr> */ #ifndef QTLUAENUM_HH_ #define QTLUAENUM_HH_ #include <QMetaObject> #include <QMetaEnum> #include <internal/qtluamember.hh> namespace QtLua { /** * @short Qt enum wrapper class * @header internal/Enum * @module {QObject wrapping} * @internal * * This internal class implements the wrapper which give * access to enums of @ref QObject objects from lua. */ class Enum : public Member { public: QTLUA_REFTYPE(Enum); Enum(const QMetaObject *mo, int index); private: Value meta_index(State *ls, const Value &key); Ref<Iterator> new_iterator(State *ls); bool support(Value::Operation c) const; String get_value_str() const; void completion_patch(String &path, String &entry, int &offset); }; } #endif
likwueron/libqtlua_fork
src/internal/qtluaenum.hh
C++
gpl-3.0
1,522
angular.module("app").controller("DeleteRequiredSignoffsCtrl", function ($scope, $modalInstance, $q, CSRF, ProductRequiredSignoffs, PermissionsRequiredSignoffs, required_signoffs, mode, product, channel, current_user) { $scope.saving = false; $scope.errors = {}; $scope.required_signoffs = required_signoffs; $scope.mode = mode; $scope.product = product; $scope.channel = channel; $scope.to_delete = {}; $scope.title = "Remove Signoff Requirements for "; if ($scope.mode === "channel") { $scope.to_delete = $scope.required_signoffs[$scope.product]["channels"][$scope.channel]; $scope.title += " for the " + $scope.product + " " + $scope.channel + " channel"; } else { $scope.to_delete = $scope.required_signoffs[$scope.product]["permissions"]; $scope.title += " for " + $scope.product + " Permissions"; } $scope.saveChanges = function() { $scope.errors = {}; var service = null; if ($scope.mode === "channel") { service = ProductRequiredSignoffs; } else if ($scope.mode === "permissions") { service = PermissionsRequiredSignoffs; } else { $scope.errors["exception"] = "Couldn't detect mode"; return; } CSRF.getToken() .then(function(csrf_token) { $scope.saving = true; var promises = []; var successCallback = function(data, deferred) { return function(response) { var namespace = null; if ($scope.mode === "channel") { namespace = required_signoffs[$scope.product]["channels"][$scope.channel]; } else { namespace = required_signoffs[$scope.product]["permissions"]; } // Required Signoff wasn't pending, so a deletion will be a new Scheduled Change if (namespace[data["role"]]["sc"] === null) { namespace[data["role"]]["sc"] = { "required_signoffs": {}, "signoffs_required": 0, "sc_id": response["sc_id"], "scheduled_by": current_user, "sc_data_version": 1, "signoffs": {}, "change_type": "delete", }; } // Required Signoff was previously pending, so it was directly removed else { // If it was *only* a scheduled change, we delete the whole thing if (namespace[data["role"]]["data_version"] === null) { delete namespace[data["role"]]; } // If it was a scheduled change to an existing Required Signoff, just remove // the Scheduled Change portion else { namespace[data["role"]]["sc"] = null; } } deferred.resolve(); }; }; var errorCallback = function(data, deferred) { return function(response, status) { if (typeof response === "object") { $scope.errors = response; } else if (typeof response === "string"){ $scope.errors["exception"] = response; } else { sweetAlert("Unknown error occurred"); } deferred.resolve(); }; }; Object.keys($scope.to_delete).forEach(function(role_name) { var deferred = $q.defer(); promises.push(deferred.promise); var data = {"product": $scope.product, "role": role_name, "data_version": $scope.to_delete[role_name]["data_version"], "csrf_token": csrf_token}; if ($scope.mode === "channel") { data["channel"] = $scope.channel; } // Not a Scheduled Change, we'll have to create one to delete it if ($scope.to_delete[role_name]["sc"] === null) { data["when"] = new Date().getTime() + 5000; data["change_type"] = "delete"; service.addScheduledChange(data) .success(successCallback(data, deferred)) .error(errorCallback(data, deferred)); } // Already has a Scheduled Change else { var change_type = $scope.to_delete[role_name]["sc"]["change_type"]; // If that Scheduled Change is already a delete, great, nothing to do! if (change_type === "delete") { deferred.resolve(); return; } // If the Scheduled Change is an insert or update, we'll need to // remove that. For inserts, that's all we need to do, because // there is no current Required Signoff to deal with. data["sc_data_version"] = $scope.to_delete[role_name]["sc"]["sc_data_version"]; service.deleteScheduledChange($scope.to_delete[role_name]["sc"]["sc_id"], data) .success(successCallback(data, deferred)) .error(errorCallback(data, deferred)); // If we deleted an update, we'll need to queue up a delete to deal with // the current Required Signoff if (change_type === "update") { delete data["sc_data_version"]; data["when"] = new Date().getTime() + 5000; data["change_type"] = "delete"; service.addScheduledChange(data) .success(successCallback(data, deferred)) .error(errorCallback(data, deferred)); } } }); $q.all(promises) .then(function() { if (Object.keys($scope.errors).length === 0) { $modalInstance.close(); } $scope.saving = false; }); }); }; $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; });
testbhearsum/balrog
ui/app/js/controllers/required_signoffs_delete.js
JavaScript
mpl-2.0
5,585
using System; using System.Globalization; using System.Windows.Data; namespace AutoCompleteTextBoxLib { public class PopupWidthConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { var val = ((double) value) - 10; return val > 0 ? val : 0; } catch (Exception ex) { Console.WriteLine(ex); return value; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }
evrenaker/Vidyo
src/VidyoIntegration/Addin/AutoCompleteTextBoxLib/PopupWidthConverter.cs
C#
mpl-2.0
713
//call this to add a warning icon to a graph and log an error to the console function error(args) { console.log('ERROR : ', args.target, ' : ', args.error); d3.select(args.target).select('.mg-chart-title') .append('i') .attr('class', 'fa fa-x fa-exclamation-circle warning'); }
HDAT/hdat-statstest
src/js/misc/error.js
JavaScript
mpl-2.0
307
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.api; import java.util.List; import java.util.Map; import org.openmrs.Person; import org.openmrs.Privilege; import org.openmrs.PrivilegeListener; import org.openmrs.Role; import org.openmrs.User; import org.openmrs.annotation.Authorized; import org.openmrs.annotation.Logging; import org.openmrs.api.context.UserContext; import org.openmrs.util.PersonByNameComparator; import org.openmrs.util.PrivilegeConstants; /** * Contains methods pertaining to Users in the system Use:<br> * * <pre> * * * List&lt;User&gt; users = Context.getUserService().getAllUsers(); * </pre> * * @see org.openmrs.api.context.Context */ public interface UserService extends OpenmrsService { /** * Create user with given password. * * @param user the user to create * @param password the password for created user * @return created user * @throws APIException */ @Authorized( { PrivilegeConstants.ADD_USERS }) @Logging(ignoredArgumentIndexes = { 1 }) public User createUser(User user, String password) throws APIException; /** * Change user password. * * @param user the user to update password * @param oldPassword the user password to update * @param newPassword the new user password * @throws APIException for not existing user and if old password is weak * @since 1.12 * @should throw APIException if old password is not correct * @should throw APIException if given user does not exist * @should change password for given user if oldPassword is correctly passed * @should change password for given user if oldPassword is null and changing user have privileges * @should throw exception if oldPassword is null and changing user have not privileges * @should throw exception if new password is too short */ @Authorized( { PrivilegeConstants.EDIT_USER_PASSWORDS }) @Logging(ignoredArgumentIndexes = { 1, 2 }) public void changePassword(User user, String oldPassword, String newPassword) throws APIException; /** * Get user by internal user identifier. * * @param userId internal identifier * @return requested user * @throws APIException * @should fetch user with given userId */ @Authorized( { PrivilegeConstants.GET_USERS }) public User getUser(Integer userId) throws APIException; /** * Get user by the given uuid. * * @param uuid * @return user or null * @throws APIException * @should fetch user with given uuid * @should find object given valid uuid * @should return null if no object found with given uuid */ @Authorized( { PrivilegeConstants.GET_USERS }) public User getUserByUuid(String uuid) throws APIException; /** * Get user by username (user's login identifier) * * @param username user's identifier used for authentication * @return requested user * @throws APIException * @should get user by username */ @Authorized( { PrivilegeConstants.GET_USERS }) public User getUserByUsername(String username) throws APIException; /** * true/false if username or systemId is already in db in username or system_id columns * * @param user User to compare * @return boolean * @throws APIException * @should verify that username and system id is unique */ @Authorized( { PrivilegeConstants.GET_USERS }) public boolean hasDuplicateUsername(User user) throws APIException; /** * Get users by role granted * * @param role Role that the Users must have to be returned * @return users with requested role * @throws APIException * @should fetch users assigned given role * @should not fetch user that does not belong to given role */ @Authorized( { PrivilegeConstants.GET_USERS }) public List<User> getUsersByRole(Role role) throws APIException; /** * Updates a given <code>user</code> in the database. * * @param user * @return the saved user * @throws APIException */ @Authorized( { PrivilegeConstants.EDIT_USERS }) public User saveUser(User user) throws APIException; /** * Deactive a user account so that it can no longer log in. * * @param user * @param reason * @throws APIException * @should retire user and set attributes */ @Authorized( { PrivilegeConstants.EDIT_USERS }) public User retireUser(User user, String reason) throws APIException; /** * Clears retired flag for a user. * * @param user * @throws APIException * @should unretire and unmark all attributes */ @Authorized( { PrivilegeConstants.EDIT_USERS }) public User unretireUser(User user) throws APIException; /** * Completely remove a location from the database (not reversible). This method delegates to * #purgeLocation(location, boolean) method. * * @param user the User to remove from the database. * @should delete given user */ @Authorized( { PrivilegeConstants.PURGE_USERS }) public void purgeUser(User user) throws APIException; /** * Completely remove a user from the database (not reversible). This is a delete from the * database. This is included for troubleshooting and low-level system administration. Ideally, * this method should <b>never</b> be called &mdash; <code>Users</code> should be * <em>voided</em> and not <em>deleted</em> altogether (since many foreign key constraints * depend on users, deleting a user would require deleting all traces, and any historical trail * would be lost). This method only clears user roles and attempts to delete the user record. If * the user has been included in any other parts of the database (through a foreign key), the * attempt to delete the user will violate foreign key constraints and fail. * * @param cascade <code>true</code> to delete associated content * @should throw APIException if cascade is true * @should delete given user when cascade equals false * @should not delete user roles for given user when cascade equals false */ @Authorized( { PrivilegeConstants.PURGE_USERS }) public void purgeUser(User user, boolean cascade) throws APIException; /** * Returns all privileges currently possible for any User * * @return Global list of privileges * @throws APIException * @should return all privileges in the system */ public List<Privilege> getAllPrivileges() throws APIException; /** * Returns all roles currently possible for any User * * @return Global list of roles * @throws APIException * @should return all roles in the system */ public List<Role> getAllRoles() throws APIException; /** * Save the given role in the database * * @param role Role to update * @return the saved role * @throws APIException * @should throw error if role inherits from itself * @should save given role to the database */ @Authorized( { PrivilegeConstants.MANAGE_ROLES }) public Role saveRole(Role role) throws APIException; /** * Complete remove a role from the database * * @param role Role to delete from the database * @throws APIException * @should throw error when role is a core role * @should return if role is null * @should delete given role from database */ @Authorized( { PrivilegeConstants.PURGE_ROLES }) public void purgeRole(Role role) throws APIException; /** * Save the given privilege in the database * * @param privilege Privilege to update * @return the saved privilege * @throws APIException * @should save given privilege to the database */ @Authorized( { PrivilegeConstants.MANAGE_PRIVILEGES }) public Privilege savePrivilege(Privilege privilege) throws APIException; /** * Completely remove a privilege from the database * * @param privilege Privilege to delete * @throws APIException * @should delete given privilege from the database * @should throw error when privilege is core privilege */ @Authorized( { PrivilegeConstants.PURGE_PRIVILEGES }) public void purgePrivilege(Privilege privilege) throws APIException; /** * Returns role object with given string role * * @return Role object for specified string * @throws APIException * @should fetch role for given role name */ public Role getRole(String r) throws APIException; /** * Get Role by its UUID * * @param uuid * @return role or null * @should find object given valid uuid * @should return null if no object found with given uuid */ public Role getRoleByUuid(String uuid) throws APIException; /** * Returns Privilege in the system with given String privilege * * @return Privilege * @throws APIException * @should fetch privilege for given name */ public Privilege getPrivilege(String p) throws APIException; /** * Get Privilege by its UUID * * @param uuid * @return privilege or null * @should find object given valid uuid * @should return null if no object found with given uuid * @should fetch privilege for given uuid */ public Privilege getPrivilegeByUuid(String uuid) throws APIException; /** * Returns all users in the system * * @return Global list of users * @throws APIException * @should fetch all users in the system * @should not contains any duplicate users */ @Authorized( { PrivilegeConstants.GET_USERS }) public List<User> getAllUsers() throws APIException; /** * Changes the current user's password. * * @param pw current password * @param pw2 new password * @throws APIException * @should match on correctly hashed sha1 stored password * @should match on incorrectly hashed sha1 stored password * @should match on sha512 hashed password * @should be able to update password multiple times */ @Logging(ignoredArgumentIndexes = { 0, 1 }) public void changePassword(String pw, String pw2) throws APIException; /** * Changes the current user's password directly. This is most useful if migrating users from * other systems and you want to retain the existing passwords. This method will simply save the * passed hashed password and salt directly to the database. * * @param user the user whose password you want to change * @param hashedPassword - the <em>already hashed</em> password to store * @param salt - the salt which should be used with this hashed password * @throws APIException * @since 1.5 * @should change the hashed password for the given user */ @Authorized( { PrivilegeConstants.EDIT_USER_PASSWORDS }) public void changeHashedPassword(User user, String hashedPassword, String salt) throws APIException; /** * Changes the passed user's secret question and answer. * * @param u User to change * @param question * @param answer * @throws APIException * @since 1.5 * @should change the secret question and answer for given user */ @Authorized( { PrivilegeConstants.EDIT_USER_PASSWORDS }) @Logging(ignoredArgumentIndexes = { 1, 2 }) public void changeQuestionAnswer(User u, String question, String answer) throws APIException; /** * Changes the current user's secret question and answer. * * @param pw user's password * @param q question * @param a answer * @throws APIException * @should match on correctly hashed stored password * @should match on incorrectly hashed stored password */ @Logging(ignoreAllArgumentValues = true) public void changeQuestionAnswer(String pw, String q, String a) throws APIException; /** * Compares <code>answer</code> against the <code>user</code>'s secret answer. * * @param u user * @param answer * @throws APIException * @should return true when given answer matches stored secret answer * @should return false when given answer does not match the stored secret answer */ @Logging(ignoredArgumentIndexes = { 1 }) public boolean isSecretAnswer(User u, String answer) throws APIException; /** * Return a list of users sorted by personName (see {@link PersonByNameComparator}) if any part * of the search matches first/last/system id and the user has one at least one of the given * <code>roles</code> assigned to them * * @param nameSearch string to compare to the beginning of user's given/middle/family/family2 * names * @param roles all the Roles the user must contain * @param includeVoided true/false whether to include voided users * @return list of users matching the given attributes * @should match search to familyName2 * @should fetch voided users if includedVoided is true * @should not fetch voided users if includedVoided is false * @should fetch users with name that contains given nameSearch * @should fetch users with systemId that contains given nameSearch * @should fetch users with at least one of the given role objects * @should not fetch duplicate users * @should fetch all users if nameSearch is empty or null * @should not fail if roles are searched but name is empty */ @Authorized( { PrivilegeConstants.GET_USERS }) public List<User> getUsers(String nameSearch, List<Role> roles, boolean includeVoided) throws APIException; /** * Search for a list of users by exact first name and last name. * * @param givenName * @param familyName * @param includeRetired * @return List&lt;User&gt; object of users matching criteria * @should fetch users exactly matching the given givenName and familyName * @should fetch voided users whenincludeVoided is true * @should not fetch any voided users when includeVoided is false * @should not fetch any duplicate users */ @Authorized( { PrivilegeConstants.GET_USERS }) public List<User> getUsersByName(String givenName, String familyName, boolean includeRetired) throws APIException; /** * Get all user accounts that belong to a given person. * * @param person * @param includeRetired * @return all user accounts that belong to person, including retired ones if specified * @throws APIException * @should fetch all accounts for a person when include retired is true * @should not fetch retired accounts when include retired is false */ @Authorized( { PrivilegeConstants.GET_USERS }) public List<User> getUsersByPerson(Person person, boolean includeRetired) throws APIException; /** * Adds the <code>key</code>/<code>value</code> pair to the given <code>user</code>. * <p> * <b>Implementations of this method should handle privileges</b> * * @param user * @param key * @param value * @return the user that was passed in and added to * @should return null if user is null * @should throw error when user is not authorized to edit users * @should add property with given key and value when key does not already exist * @should modify property with given key and value when key already exists */ public User setUserProperty(User user, String key, String value) throws APIException; /** * Removes the property denoted by <code>key</code> from the <code>user</code>'s properties. * <b>Implementations of this method should handle privileges</b> * * @param user * @param key * @return the user that was passed in and removed from * @should return null if user is null * @should throw error when user is not authorized to edit users * @should remove user property for given user and key */ public User removeUserProperty(User user, String key) throws APIException; /** * Get/generate/find the next system id to be doled out. Assume check digit /not/ applied in * this method * * @return new system id */ public String generateSystemId(); /** * Return a batch of users of a specific size sorted by personName (see * {@link PersonByNameComparator}) if any part of the search matches first/last/system id and * the user has one at least one of the given <code>roles</code> assigned to them. If start and * length are not specified, then all matches are returned, If name is empty or null, then all * all users will be returned taking into consideration the values of start and length * arguments. * * @param name string to compare to the beginning of user's given/middle/family/family2 names * @param roles all the Roles the user must contain * @param includeRetired true/false whether to include voided users * @param start beginning index for the batch * @param length number of users to return in the batch * @return list of matching users of a size based on the specified arguments * @since 1.8 * @should return users whose roles inherit requested roles */ @Authorized( { PrivilegeConstants.GET_USERS }) public List<User> getUsers(String name, List<Role> roles, boolean includeRetired, Integer start, Integer length) throws APIException; /** * Return the number of users with a matching name or system id and have at least one of the * given roles assigned to them * * @param name patient name * @param roles all the Roles the user must contain * @param includeRetired Specifies whether voided users should be included * @return the number of users matching the given attributes * @since 1.8 */ @Authorized( { PrivilegeConstants.GET_USERS }) public Integer getCountOfUsers(String name, List<Role> roles, boolean includeRetired); /** * Notifies privilege listener beans about any privilege check. * <p> * It is called by {@link UserContext#hasPrivilege(java.lang.String)}. * * @see PrivilegeListener * @param user the authenticated user or <code>null</code> if not authenticated * @param privilege the checked privilege * @param hasPrivilege <code>true</code> if the authenticated user has the required privilege or * if it is a proxy privilege * @since 1.8.4, 1.9.1, 1.10 */ public void notifyPrivilegeListeners(User user, String privilege, boolean hasPrivilege); /** * Saves the current key/value as a user property for the current user. * * @param key the authenticated user's property * @param value value of the property * @since 1.10 */ @Authorized public User saveUserProperty(String key, String value); /** * Replaces all user properties with the given map of properties for the current user * * @param properties the authenticated user's properties * @since 1.10 */ @Authorized public User saveUserProperties(Map<String, String> properties); }
kabariyamilind/openMRSDEV
api/src/main/java/org/openmrs/api/UserService.java
Java
mpl-2.0
18,568
describe('EncounterService tests', function() { var encounterService; var q; var deferred; beforeEach(module('encounterService')); // create mock Encounter resource var mockEncounter = jasmine.createSpyObj('Encounter', ['query']); mockEncounter.query.andCallFake(function() { deferred = q.defer(); var promise_mock = { $promise: deferred.promise }; return promise_mock; }); beforeEach(module(function($provide) { $provide.value('Encounter', mockEncounter); })); // inject necessary dependencies beforeEach(inject(function (_EncounterService_,$q) { encounterService = _EncounterService_; q = $q; })); it('should call Encounter resource with query value', function() { encounterService.getEncounters({ 'q': 'abc' }); expect(mockEncounter.query).toHaveBeenCalledWith({ 'q': 'abc' }); }); });
yadamz/first-module
omod/src/test/webapp/resources/scripts/services/encounterServiceTest.js
JavaScript
mpl-2.0
942
load(libdir + "parallelarray-helpers.js"); // The bug this is testing for: // the input p and the scatter vector have length 4 // and the output p2 has length 3. Even though p2 // is shorter than the input lengths, we still need // to scan the entirety of the scatter vector, because // it may hold valid targets at distant indices. function test() { var p = new ParallelArray([2,3,5,17]); var r = p.scatter([0,0,2,1], 9, function (x,y) { return x * y; }, 3); var p2 = new ParallelArray([6,17,5]); assertEqParallelArray(r, p2); } if (getBuildConfiguration().parallelJS) test();
SlateScience/MozillaJS
js/src/jit-test/tests/parallelarray/scatter-regression-1.js
JavaScript
mpl-2.0
592
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // Keep track of events tied to both email and IP addresses module.exports = function (RATE_LIMIT_INTERVAL_MS, MAX_BAD_LOGINS, now) { now = now || Date.now var PASSWORD_CHECKING_ACTION = { accountLogin : true, accountDestroy : true, passwordChange : true, } function isPasswordCheckingAction(action) { return PASSWORD_CHECKING_ACTION[action] } function IpEmailRecord() { this.lf = [] } IpEmailRecord.parse = function (object) { var rec = new IpEmailRecord() object = object || {} rec.rl = object.rl // timestamp when the account was rate-limited rec.lf = object.lf || [] // timestamps when a login failure occurred return rec } IpEmailRecord.prototype.isOverBadLogins = function () { this.trimBadLogins(now()) return this.lf.length > MAX_BAD_LOGINS } IpEmailRecord.prototype.addBadLogin = function () { this.trimBadLogins(now()) this.lf.push(now()) } IpEmailRecord.prototype.trimBadLogins = function (now) { if (this.lf.length === 0) { return } // lf is naturally ordered from oldest to newest // and we only need to keep up to MAX_BAD_LOGINS + 1 var i = this.lf.length - 1 var n = 0 var login = this.lf[i] while (login > (now - RATE_LIMIT_INTERVAL_MS) && n <= MAX_BAD_LOGINS) { login = this.lf[--i] n++ } this.lf = this.lf.slice(i + 1) } IpEmailRecord.prototype.shouldBlock = function () { return this.isRateLimited() } IpEmailRecord.prototype.isRateLimited = function () { return !!(this.rl && (now() - this.rl < RATE_LIMIT_INTERVAL_MS)) } IpEmailRecord.prototype.rateLimit = function () { this.rl = now() this.lf = [] } IpEmailRecord.prototype.unblockIfReset = function (resetAt) { if (resetAt > this.rl) { this.lf = [] delete this.rl return true } return false } IpEmailRecord.prototype.retryAfter = function () { return Math.max(0, Math.floor(((this.rl || 0) + RATE_LIMIT_INTERVAL_MS - now()) / 1000)) } IpEmailRecord.prototype.update = function (action) { // if this is not an action that allows checking password, // then all ok (no block) if ( !isPasswordCheckingAction(action) ) { return 0 } if ( this.shouldBlock() ) { // if already blocked, then return a block return this.retryAfter() } // if over the bad logins, rate limit them and return the block if (this.isOverBadLogins()) { this.rateLimit() return this.retryAfter() } // no block, not yet over limit return 0 } return IpEmailRecord }
ofer43211/fxa-customs-server
ip_email_record.js
JavaScript
mpl-2.0
2,820
// Copyright (C) 2016 Jordan Harband. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Object.getOwnPropertyDescriptors does not see inherited properties. esid: pending author: Jordan Harband ---*/ var F = function () {}; F.prototype.a = {}; F.prototype.b = {}; var f = new F(); var bValue = {}; f.b = bValue; // shadow the prototype Object.defineProperty(f, 'c', { enumerable: false, configurable: true, writable: false, value: {} }); // solely an own property var result = Object.getOwnPropertyDescriptors(f); assert.sameValue(!!result.b, true, 'b has a descriptor'); assert.sameValue(!!result.c, true, 'c has a descriptor'); assert.sameValue(result.b.enumerable, true, 'b is enumerable'); assert.sameValue(result.b.configurable, true, 'b is configurable'); assert.sameValue(result.b.writable, true, 'b is writable'); assert.sameValue(result.b.value, bValue, 'b’s value is `bValue`'); assert.sameValue(result.c.enumerable, false, 'c is enumerable'); assert.sameValue(result.c.configurable, true, 'c is configurable'); assert.sameValue(result.c.writable, false, 'c is writable'); assert.sameValue(result.c.value, f.c, 'c’s value is `f.c`'); assert.sameValue( Object.keys(result).length, 2, 'result has same number of own property names as f' );
cstipkovic/spidermonkey-research
js/src/tests/test262/built-ins/Object/getOwnPropertyDescriptors/inherited-properties-omitted.js
JavaScript
mpl-2.0
1,334
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package openstack import ( "regexp" "github.com/go-goose/goose/v4/neutron" "github.com/go-goose/goose/v4/nova" "github.com/go-goose/goose/v4/swift" "github.com/juju/collections/set" "github.com/juju/juju/core/instance" "github.com/juju/juju/environs" "github.com/juju/juju/environs/context" "github.com/juju/juju/environs/instances" envstorage "github.com/juju/juju/environs/storage" "github.com/juju/juju/provider/common" "github.com/juju/juju/storage" "github.com/juju/juju/testing" ) var ( ShortAttempt = &shortAttempt StorageAttempt = &storageAttempt CinderAttempt = &cinderAttempt ) func InstanceServerDetail(inst instances.Instance) *nova.ServerDetail { return inst.(*openstackInstance).serverDetail } func InstanceFloatingIP(inst instances.Instance) *string { return inst.(*openstackInstance).floatingIP } var ( NovaListAvailabilityZones = &novaListAvailabilityZones NewOpenstackStorage = &newOpenstackStorage ) func NewCinderVolumeSource(s OpenstackStorage, env common.ZonedEnviron) storage.VolumeSource { return NewCinderVolumeSourceForModel(s, testing.ModelTag.Id(), env) } func NewCinderVolumeSourceForModel(s OpenstackStorage, modelUUID string, env common.ZonedEnviron) storage.VolumeSource { const envName = "testmodel" return &cinderVolumeSource{ storageAdapter: s, envName: envName, modelUUID: modelUUID, namespace: fakeNamespace{}, zonedEnv: env, } } type fakeNamespace struct { instance.Namespace } func (fakeNamespace) Value(s string) string { return "juju-" + s } func SetUpGlobalGroup(e environs.Environ, ctx context.ProviderCallContext, name string, apiPort int) (neutron.SecurityGroupV2, error) { switching := &neutronFirewaller{firewallerBase: firewallerBase{environ: e.(*Environ)}} return switching.setUpGlobalGroup(name, apiPort) } func EnsureGroup(e environs.Environ, ctx context.ProviderCallContext, name string, rules []neutron.RuleInfoV2) (neutron.SecurityGroupV2, error) { switching := &neutronFirewaller{firewallerBase: firewallerBase{environ: e.(*Environ)}} return switching.ensureGroup(name, rules) } func MachineGroupRegexp(e environs.Environ, machineId string) string { switching := &neutronFirewaller{firewallerBase: firewallerBase{environ: e.(*Environ)}} return switching.machineGroupRegexp(machineId) } func MachineGroupName(e environs.Environ, controllerUUID, machineId string) string { switching := &neutronFirewaller{firewallerBase: firewallerBase{environ: e.(*Environ)}} return switching.machineGroupName(controllerUUID, machineId) } func MatchingGroup(e environs.Environ, ctx context.ProviderCallContext, nameRegExp string) (neutron.SecurityGroupV2, error) { switching := &neutronFirewaller{firewallerBase: firewallerBase{environ: e.(*Environ)}} return switching.matchingGroup(ctx, nameRegExp) } // ImageMetadataStorage returns a Storage object pointing where the goose // infrastructure sets up its keystone entry for image metadata func ImageMetadataStorage(e environs.Environ) envstorage.Storage { env := e.(*Environ) return &openstackstorage{ containerName: "imagemetadata", swift: swift.New(env.clientUnlocked), } } // CreateCustomStorage creates a swift container and returns the Storage object // so you can put data into it. func CreateCustomStorage(e environs.Environ, containerName string) envstorage.Storage { env := e.(*Environ) swiftClient := swift.New(env.clientUnlocked) if err := swiftClient.CreateContainer(containerName, swift.PublicRead); err != nil { panic(err) } return &openstackstorage{ containerName: containerName, swift: swiftClient, } } // BlankContainerStorage creates a Storage object with blank container name. func BlankContainerStorage() envstorage.Storage { return &openstackstorage{} } // GetNeutronClient returns the neutron client for the current environs. func GetNeutronClient(e environs.Environ) *neutron.Client { return e.(*Environ).neutron() } // GetNovaClient returns the nova client for the current environs. func GetNovaClient(e environs.Environ) *nova.Client { return e.(*Environ).nova() } // ResolveNetwork exposes environ helper function resolveNetwork for testing func ResolveNetwork(e environs.Environ, networkName string, external bool) (string, error) { return e.(*Environ).networking.ResolveNetwork(networkName, external) } // FindNetworks exposes environ helper function FindNetworks for testing func FindNetworks(e environs.Environ, internal bool) (set.Strings, error) { return e.(*Environ).networking.FindNetworks(internal) } var PortsToRuleInfo = rulesToRuleInfo var SecGroupMatchesIngressRule = secGroupMatchesIngressRule var MakeServiceURL = &makeServiceURL var GetVolumeEndpointURL = getVolumeEndpointURL func GetModelGroupNames(e environs.Environ) ([]string, error) { env := e.(*Environ) neutronFw := env.firewaller.(*neutronFirewaller) groups, err := env.neutron().ListSecurityGroupsV2() if err != nil { return nil, err } modelPattern, err := regexp.Compile(neutronFw.jujuGroupRegexp()) if err != nil { return nil, err } var results []string for _, group := range groups { if modelPattern.MatchString(group.Name) { results = append(results, group.Name) } } return results, nil } func GetFirewaller(e environs.Environ) Firewaller { env := e.(*Environ) return env.firewaller }
freyes/juju
provider/openstack/export_test.go
GO
agpl-3.0
5,450
""" Dictzone @website https://dictzone.com/ @provide-api no @using-api no @results HTML (using search portal) @stable no (HTML can change) @parse url, title, content """ import re from lxml import html from searx.utils import is_valid_lang from searx.url_utils import urljoin categories = ['general'] url = u'http://dictzone.com/{from_lang}-{to_lang}-dictionary/{query}' weight = 100 parser_re = re.compile(b'.*?([a-z]+)-([a-z]+) ([^ ]+)$', re.I) results_xpath = './/table[@id="r"]/tr' def request(query, params): m = parser_re.match(query) if not m: return params from_lang, to_lang, query = m.groups() from_lang = is_valid_lang(from_lang) to_lang = is_valid_lang(to_lang) if not from_lang or not to_lang: return params params['url'] = url.format(from_lang=from_lang[2], to_lang=to_lang[2], query=query.decode('utf-8')) return params def response(resp): results = [] dom = html.fromstring(resp.text) for k, result in enumerate(dom.xpath(results_xpath)[1:]): try: from_result, to_results_raw = result.xpath('./td') except: continue to_results = [] for to_result in to_results_raw.xpath('./p/a'): t = to_result.text_content() if t.strip(): to_results.append(to_result.text_content()) results.append({ 'url': urljoin(resp.url, '?%d' % k), 'title': from_result.text_content(), 'content': '; '.join(to_results) }) return results
potato/searx
searx/engines/dictzone.py
Python
agpl-3.0
1,645
// 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/>. // DialogFlags.cpp : implementation file // #include "stdafx.h" #include "world_editor_fauna_graph_plugin.h" #include "DialogFlags.h" #include "plugin.h" ///////////////////////////////////////////////////////////////////////////// // CDialogFlags dialog CDialogFlags::CDialogFlags(CPlugin *plugin) : DisplayCondition(DisplayAll), _Plugin(plugin) { //AFX_MANAGE_STATE(AfxGetStaticModuleState()); //{{AFX_DATA_INIT(CDialogFlags) m_DisplayFlags = TRUE; m_DisplayIndices = TRUE; m_DisplayTargetIndices = FALSE; //}}AFX_DATA_INIT } void CDialogFlags::DoDataExchange(CDataExchange* pDX) { //AFX_MANAGE_STATE(AfxGetStaticModuleState()); CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDialogFlags) DDX_Check(pDX, IDC_DISPLAY_FLAGS, m_DisplayFlags); DDX_Check(pDX, IDC_DISPLAY_INDICES, m_DisplayIndices); DDX_Check(pDX, IDC_DISPLAY_TARGET_INDICES, m_DisplayTargetIndices); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDialogFlags, CDialog) //{{AFX_MSG_MAP(CDialogFlags) ON_CBN_SELCHANGE(IDC_DISPLAY_CONDITION, OnSelchangeDisplayCondition) ON_BN_CLICKED(IDC_DISPLAY_FLAGS, OnDisplayFlags) ON_BN_CLICKED(IDC_DISPLAY_INDICES, OnDisplayIndices) ON_BN_CLICKED(IDC_DISPLAY_TARGET_INDICES, OnDisplayTargetIndices) ON_WM_CLOSE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDialogFlags message handlers void CDialogFlags::OnSelchangeDisplayCondition() { //AFX_MANAGE_STATE(AfxGetStaticModuleState()); UpdateData(TRUE); CComboBox *lb = (CComboBox *) GetDlgItem(IDC_DISPLAY_CONDITION); DisplayCondition = (TDisplayCondition) lb->GetCurSel(); BOOL enabled = DisplayCondition == DisplayOff ? FALSE : TRUE; GetDlgItem(IDC_DISPLAY_FLAGS)->EnableWindow(enabled); GetDlgItem(IDC_DISPLAY_INDICES)->EnableWindow(enabled); GetDlgItem(IDC_DISPLAY_INDICES)->EnableWindow(enabled); GetDlgItem(IDC_DISPLAY_TARGET_INDICES)->EnableWindow(enabled); _Plugin->getPluginAccess()->invalidateLeftView(); } void CDialogFlags::OnDisplayFlags() { //AFX_MANAGE_STATE(AfxGetStaticModuleState()); UpdateData(TRUE); _Plugin->getPluginAccess()->invalidateLeftView(); } void CDialogFlags::OnDisplayIndices() { //AFX_MANAGE_STATE(AfxGetStaticModuleState()); UpdateData(TRUE); _Plugin->getPluginAccess()->invalidateLeftView(); } void CDialogFlags::OnDisplayTargetIndices() { //AFX_MANAGE_STATE(AfxGetStaticModuleState()); UpdateData(TRUE); _Plugin->getPluginAccess()->invalidateLeftView(); } BOOL CDialogFlags::OnInitDialog() { //AFX_MANAGE_STATE(AfxGetStaticModuleState()); CDialog::OnInitDialog(); // CComboBox *lb = (CComboBox *) GetDlgItem(IDC_DISPLAY_CONDITION); CString str; lb->SetCurSel(0); // return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDialogFlags::OnClose() { //AFX_MANAGE_STATE(AfxGetStaticModuleState()); _Plugin->closePlugin(); CDialog::OnClose(); }
osgcc/ryzom
ryzom/tools/leveldesign/world_editor/world_editor_fauna_graph_plugin/DialogFlags.cpp
C++
agpl-3.0
3,760
/* * * (c) Copyright Ascensio System Limited 2010-2015 * * This program is freeware. You can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html). * In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that * Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights. * * THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html * * You can contact Ascensio System SIA by email at sales@onlyoffice.com * * The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display * Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3. * * Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains * relevant author attributions when distributing the software. If the display of the logo in its graphic * form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE" * in every copy of the program you distribute. * Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks. * */ namespace ASC.Xmpp.Core.protocol.x.rosterx { /// <summary> /// </summary> public enum Action { /// <summary> /// </summary> NONE = -1, /// <summary> /// </summary> add, /// <summary> /// </summary> remove, /// <summary> /// </summary> modify } /// <summary> /// Summary description for RosterItem. /// </summary> public class RosterItem : Base.RosterItem { #region Constructor /// <summary> /// </summary> public RosterItem() { Namespace = Uri.X_ROSTERX; } /// <summary> /// </summary> /// <param name="jid"> </param> public RosterItem(Jid jid) : this() { Jid = jid; } /// <summary> /// </summary> /// <param name="jid"> </param> /// <param name="name"> </param> public RosterItem(Jid jid, string name) : this(jid) { Name = name; } /// <summary> /// </summary> /// <param name="jid"> </param> /// <param name="name"> </param> /// <param name="action"> </param> public RosterItem(Jid jid, string name, Action action) : this(jid, name) { Action = action; } #endregion #region Properties /// <summary> /// </summary> public Action Action { get { return (Action) GetAttributeEnum("action", typeof (Action)); } set { SetAttribute("action", value.ToString()); } } #endregion /* <item action='delete' jid='rosencrantz@denmark' name='Rosencrantz'> <group>Visitors</group> </item> */ } }
Khamull/CommunityServer
module/ASC.Jabber/ASC.Xmpp.Core/protocol/x/rosterx/RosterItem.cs
C#
agpl-3.0
3,291
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package uniter_test import ( "path/filepath" "runtime" "github.com/juju/loggo" jc "github.com/juju/testing/checkers" "github.com/juju/utils/v2/exec" gc "gopkg.in/check.v1" "github.com/juju/juju/juju/sockets" "github.com/juju/juju/testing" "github.com/juju/juju/worker/uniter" "github.com/juju/juju/worker/uniter/runcommands" ) type ListenerSuite struct { testing.BaseSuite socketPath sockets.Socket } var _ = gc.Suite(&ListenerSuite{}) func sockPath(c *gc.C) sockets.Socket { sockPath := filepath.Join(c.MkDir(), "test.listener") if runtime.GOOS == "windows" { return sockets.Socket{Address: `\\.\pipe` + sockPath[2:], Network: "unix"} } return sockets.Socket{Address: sockPath, Network: "unix"} } func (s *ListenerSuite) SetUpTest(c *gc.C) { s.BaseSuite.SetUpTest(c) s.socketPath = sockPath(c) } // Mirror the params to uniter.NewRunListener, but add cleanup to close it. func (s *ListenerSuite) NewRunListener(c *gc.C, operator bool) *uniter.RunListener { listener, err := uniter.NewRunListener(s.socketPath, loggo.GetLogger("test")) c.Assert(err, jc.ErrorIsNil) listener.RegisterRunner("test/0", &mockCommandRunner{ c: c, operator: operator, }) s.AddCleanup(func(*gc.C) { c.Assert(listener.Close(), jc.ErrorIsNil) }) return listener } func (s *ListenerSuite) TestNewRunListenerOnExistingSocketRemovesItAndSucceeds(c *gc.C) { if runtime.GOOS == "windows" { c.Skip("bug 1403084: Current named pipes implementation does not support this") } s.NewRunListener(c, false) s.NewRunListener(c, false) } func (s *ListenerSuite) TestClientCall(c *gc.C) { s.NewRunListener(c, false) client, err := sockets.Dial(s.socketPath) c.Assert(err, jc.ErrorIsNil) defer client.Close() var result exec.ExecResponse args := uniter.RunCommandsArgs{ Commands: "some-command", RelationId: -1, RemoteUnitName: "", ForceRemoteUnit: false, UnitName: "test/0", } err = client.Call(uniter.JujuExecEndpoint, args, &result) c.Assert(err, jc.ErrorIsNil) c.Assert(string(result.Stdout), gc.Equals, "some-command stdout") c.Assert(string(result.Stderr), gc.Equals, "some-command stderr") c.Assert(result.Code, gc.Equals, 42) } func (s *ListenerSuite) TestUnregisterRunner(c *gc.C) { listener := s.NewRunListener(c, false) listener.UnregisterRunner("test/0") client, err := sockets.Dial(s.socketPath) c.Assert(err, jc.ErrorIsNil) defer client.Close() var result exec.ExecResponse args := uniter.RunCommandsArgs{ Commands: "some-command", RelationId: -1, RemoteUnitName: "", ForceRemoteUnit: false, UnitName: "test/0", } err = client.Call(uniter.JujuExecEndpoint, args, &result) c.Assert(err, gc.ErrorMatches, ".*no runner is registered for unit test/0") } func (s *ListenerSuite) TestOperatorFlag(c *gc.C) { s.NewRunListener(c, true) client, err := sockets.Dial(s.socketPath) c.Assert(err, jc.ErrorIsNil) defer client.Close() var result exec.ExecResponse args := uniter.RunCommandsArgs{ Commands: "some-command", RelationId: -1, RemoteUnitName: "", ForceRemoteUnit: false, UnitName: "test/0", Operator: true, } err = client.Call(uniter.JujuExecEndpoint, args, &result) c.Assert(err, jc.ErrorIsNil) c.Assert(string(result.Stdout), gc.Equals, "some-command stdout") c.Assert(string(result.Stderr), gc.Equals, "some-command stderr") c.Assert(result.Code, gc.Equals, 42) } type ChannelCommandRunnerSuite struct { testing.BaseSuite abort chan struct{} commands runcommands.Commands commandChannel chan string runner *uniter.ChannelCommandRunner } var _ = gc.Suite(&ChannelCommandRunnerSuite{}) func (s *ChannelCommandRunnerSuite) SetUpTest(c *gc.C) { s.BaseSuite.SetUpTest(c) s.abort = make(chan struct{}, 1) s.commands = runcommands.NewCommands() s.commandChannel = make(chan string, 1) runner, err := uniter.NewChannelCommandRunner(uniter.ChannelCommandRunnerConfig{ Abort: s.abort, Commands: s.commands, CommandChannel: s.commandChannel, }) c.Assert(err, jc.ErrorIsNil) s.runner = runner } func (s *ChannelCommandRunnerSuite) TestCommandsAborted(c *gc.C) { close(s.abort) _, err := s.runner.RunCommands(uniter.RunCommandsArgs{ Commands: "some-command", }) c.Assert(err, gc.ErrorMatches, "command execution aborted") } type mockCommandRunner struct { c *gc.C operator bool } var _ uniter.CommandRunner = (*mockCommandRunner)(nil) func (r *mockCommandRunner) RunCommands(args uniter.RunCommandsArgs) (results *exec.ExecResponse, err error) { r.c.Log("mock runner: " + args.Commands) r.c.Assert(args.Operator, gc.Equals, r.operator) return &exec.ExecResponse{ Code: 42, Stdout: []byte(args.Commands + " stdout"), Stderr: []byte(args.Commands + " stderr"), }, nil }
freyes/juju
worker/uniter/runlistener_test.go
GO
agpl-3.0
4,915
/* Copyright (C) 2014 Omega software d.o.o. This file is part of Rhetos. 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/>. */ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; using Rhetos.Dsl.DefaultConcepts; using Rhetos.TestCommon; using Rhetos.Utilities; namespace CommonConcepts.Test { [TestClass()] public class ComputationsUtilityTest { class SomeEntity { public string Name; public Guid? Reference; } [TestMethod()] public void SortByGivenOrderTest() { var id1 = Guid.NewGuid(); var id2 = Guid.NewGuid(); var id3 = Guid.NewGuid(); var id4 = Guid.NewGuid(); var expectedOrder = new Guid?[] { id1, id2, id3, id4 }; var items = new[] { new SomeEntity { Name = "a", Reference = id3 }, new SomeEntity { Name = "b", Reference = id2 }, new SomeEntity { Name = "c", Reference = id1 }, new SomeEntity { Name = "d", Reference = id2 }, new SomeEntity { Name = "e", Reference = id4 } }; Graph.SortByGivenOrder(items, expectedOrder, item => item.Reference); string result = string.Join(", ", items.Select(item => item.Name)); const string expectedResult1 = "c, b, d, a, e"; const string expectedResult2 = "c, d, b, a, e"; Console.WriteLine("result: " + result); Console.WriteLine("expectedResult1: " + expectedResult1); Console.WriteLine("expectedResult2: " + expectedResult2); Assert.IsTrue(result == expectedResult1 || result == expectedResult2, "Result '" + result + "' is not '" + expectedResult1 + "' nor '" + expectedResult2 + "'."); } [TestMethod()] public void SortByGivenOrderError() { var id1 = Guid.NewGuid(); var id2 = Guid.NewGuid(); var expectedOrder = new Guid?[] { id1 }; var items = new[] { new SomeEntity { Name = "a", Reference = id1 }, new SomeEntity { Name = "b", Reference = id2 }, }; TestUtility.ShouldFail(() => Graph.SortByGivenOrder(items, expectedOrder, item => item.Reference), "SomeEntity", "ComputationsUtilityTest", id2.ToString()); } } }
bantolov/Rhetos
CommonConcepts/CommonConceptsTest/CommonConcepts.Test/ComputationsUtilityTest.cs
C#
agpl-3.0
3,163
<?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-2011 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". ********************************************************************************/ class ModuleScanner{ private $manifestMap = array( 'pre_execute'=>'pre_execute', 'install_mkdirs'=>'mkdir', 'install_copy'=>'copy', 'install_images'=>'image_dir', 'install_menus'=>'menu', 'install_userpage'=>'user_page', 'install_dashlets'=>'dashlets', 'install_administration'=>'administration', 'install_connectors'=>'connectors', 'install_vardefs'=>'vardefs', 'install_layoutdefs'=>'layoutdefs', 'install_layoutfields'=>'layoutfields', 'install_relationships'=>'relationships', 'install_languages'=>'language', 'install_logichooks'=>'logic_hooks', 'post_execute'=>'post_execute', ); private $blackListExempt = array(); private $validExt = array('png', 'gif', 'jpg', 'css', 'js', 'php', 'txt', 'html', 'htm', 'tpl', 'pdf', 'md5', 'xml'); private $blackList = array( 'popen', 'proc_open', 'escapeshellarg', 'escapeshellcmd', 'proc_close', 'proc_get_status', 'proc_nice', 'basename', 'passthru', 'clearstatcache', 'delete', 'dirname', 'disk_free_space', 'disk_total_space', 'diskfreespace', 'fclose', 'feof', 'fflush', 'fgetc', 'fgetcsv', 'fgets', 'fgetss', 'file_exists', 'file_get_contents', 'filesize', 'filetype', 'flock', 'fnmatch', 'fpassthru', 'fputcsv', 'fputs', 'fread', 'fscanf', 'fseek', 'fstat', 'ftell', 'ftruncate', 'fwrite', 'glob', 'is_dir', 'is_file', 'is_link', 'is_readable', 'is_uploaded_file', 'parse_ini_string', 'pathinfo', 'pclose', 'readfile', 'readlink', 'realpath_cache_get', 'realpath_cache_size', 'realpath', 'rewind', 'set_file_buffer', 'tmpfile', 'umask', 'eval', 'exec', 'system', 'shell_exec', 'passthru', 'chgrp', 'chmod', 'chwown', 'file_put_contents', 'file', 'fileatime', 'filectime', 'filegroup', 'fileinode', 'filemtime', 'fileowner', 'fileperms', 'fopen', 'is_executable', 'is_writable', 'is_writeable', 'lchgrp', 'lchown', 'linkinfo', 'lstat', 'mkdir', 'parse_ini_file', 'rmdir', 'stat', 'tempnam', 'touch', 'unlink', 'getimagesize', 'call_user_func', 'call_user_func_array', 'create_function', //mutliple files per function call 'copy', 'link', 'rename', 'symlink', 'move_uploaded_file', 'chdir', 'chroot', 'create_cache_directory', 'mk_temp_dir', 'write_array_to_file', 'write_encoded_file', 'create_custom_directory', 'sugar_rename', 'sugar_chown', 'sugar_fopen', 'sugar_mkdir', 'sugar_file_put_contents', 'sugar_chgrp', 'sugar_chmod', 'sugar_touch', ); public function printToWiki(){ echo "'''Default Extensions'''<br>"; foreach($this->validExt as $b){ echo '#' . $b . '<br>'; } echo "'''Default Black Listed Functions'''<br>"; foreach($this->blackList as $b){ echo '#' . $b . '<br>'; } } public function __construct(){ if(!empty($GLOBALS['sugar_config']['moduleInstaller']['blackListExempt'])){ $this->blackListExempt = array_merge($this->blackListExempt, $GLOBALS['sugar_config']['moduleInstaller']['blackListExempt']); } if(!empty($GLOBALS['sugar_config']['moduleInstaller']['blackList'])){ $this->blackList = array_merge($this->blackList, $GLOBALS['sugar_config']['moduleInstaller']['blackList']); } if(!empty($GLOBALS['sugar_config']['moduleInstaller']['validExt'])){ $this->validExt = array_merge($this->validExt, $GLOBALS['sugar_config']['moduleInstaller']['validExt']); } } private $issues = array(); private $pathToModule = ''; /** *returns a list of issues */ public function getIssues(){ return $this->issues; } /** *returns true or false if any issues were found */ public function hasIssues(){ return !empty($this->issues); } /** *Ensures that a file has a valid extension */ private function isValidExtension($file){ $file = strtolower($file); $extPos = strrpos($file, '.'); //make sure they don't override the files.md5 if($extPos === false || $file == 'files.md5')return false; $ext = substr($file, $extPos + 1); return in_array($ext, $this->validExt); } /** *Scans a directory and calls on scan file for each file **/ public function scanDir($path){ static $startPath = ''; if(empty($startPath))$startPath = $path; if(!is_dir($path))return false; $d = dir($path); while($e = $d->read()){ $next = $path . '/' . $e; if(is_dir($next)){ if(substr($e, 0, 1) == '.')continue; $this->scanDir($next); }else{ $issues = $this->scanFile($next); } } return true; } /** * Check if the file contents looks like PHP * @param string $contents File contents * @return boolean */ protected function isPHPFile($contents) { if(stripos($contents, '<?php') !== false) return true; for($tag=0;($tag = stripos($contents, '<?', $tag)) !== false;$tag++) { if(strncasecmp(substr($contents, $tag, 13), '<?xml version', 13)) { // <?xml version is OK, skip it $tag++; continue; } // found <?, it's PHP return true; } return false; } /** * Given a file it will open it's contents and check if it is a PHP file (not safe to just rely on extensions) if it finds <?php tags it will use the tokenizer to scan the file * $var() and ` are always prevented then whatever is in the blacklist. * It will also ensure that all files are of valid extension types * */ public function scanFile($file){ $issues = array(); if(!$this->isValidExtension($file)){ $issues[] = translate('ML_INVALID_EXT'); $this->issues['file'][$file] = $issues; return $issues; } $contents = file_get_contents($file); if(!$this->isPHPFile($contents)) return $issues; $tokens = @token_get_all($contents); $checkFunction = false; $possibleIssue = ''; $lastToken = false; foreach($tokens as $index=>$token){ if(is_string($token[0])){ switch($token[0]){ case '`': $issues['backtick'] = translate('ML_INVALID_FUNCTION') . " '`'"; case '(': if($checkFunction)$issues[] = $possibleIssue; break; } $checkFunction = false; $possibleIssue = ''; }else{ $token['_msi'] = token_name($token[0]); switch($token[0]){ case T_WHITESPACE: continue; case T_EVAL: if(in_array('eval', $this->blackList) && !in_array('eval', $this->blackListExempt)) $issues[]= translate('ML_INVALID_FUNCTION') . ' eval()'; break; case T_STRING: $token[1] = strtolower($token[1]); if(!in_array($token[1], $this->blackList))break; if(in_array($token[1], $this->blackListExempt))break; if ($lastToken !== false && ($lastToken[0] == T_NEW || $lastToken[0] == T_OBJECT_OPERATOR || $lastToken[0] == T_DOUBLE_COLON)) { break; } case T_VARIABLE: $checkFunction = true; $possibleIssue = translate('ML_INVALID_FUNCTION') . ' ' . $token[1] . '()'; break; default: $checkFunction = false; $possibleIssue = ''; } if ($token[0] != T_WHITESPACE) { $lastToken = $token; } } } if(!empty($issues)){ $this->issues['file'][$file] = $issues; } return $issues; } /* * checks files.md5 file to see if the file is from sugar * ONLY WORKS ON FILES */ public function sugarFileExists($path){ static $md5 = array(); if(empty($md5) && file_exists('files.md5')) { include('files.md5'); $md5 = $md5_string; } if(isset($md5['./' . $path]))return true; } /** *This function will scan the Manifest for disabled actions specified in $GLOBALS['sugar_config']['moduleInstaller']['disableActions'] *if $GLOBALS['sugar_config']['moduleInstaller']['disableRestrictedCopy'] is set to false or not set it will call on scanCopy to ensure that it is not overriding files */ public function scanManifest($manifestPath){ $issues = array(); if(!file_exists($manifestPath)){ $this->issues['manifest'][$manifestPath] = translate('ML_NO_MANIFEST'); return $issues; } $fileIssues = $this->scanFile($manifestPath); //if the manifest contains malicious code do not open it if(!empty($fileIssues)){ return $fileIssues; } include($manifestPath); //scan for disabled actions if(isset($GLOBALS['sugar_config']['moduleInstaller']['disableActions'])){ foreach($GLOBALS['sugar_config']['moduleInstaller']['disableActions'] as $action){ if(isset($installdefs[$this->manifestMap[$action]])){ $issues[] = translate('ML_INVALID_ACTION_IN_MANIFEST') . $this->manifestMap[$action]; } } } //now lets scan for files that will override our files if(empty($GLOBALS['sugar_config']['moduleInstaller']['disableRestrictedCopy']) && isset($installdefs['copy'])){ foreach($installdefs['copy'] as $copy){ $from = str_replace('<basepath>', $this->pathToModule, $copy['from']); $to = $copy['to']; if(substr_count($from, '..')){ $this->issues['copy'][$from] = translate('ML_PATH_MAY_NOT_CONTAIN').' ".." -' . $from; } if(substr_count($to, '..')){ $this->issues['copy'][$to] = translate('ML_PATH_MAY_NOT_CONTAIN'). ' ".." -' . $to; } while(substr_count($from, '//')){ $from = str_replace('//', '/', $from); } while(substr_count($to, '//')){ $to = str_replace('//', '/', $to); } $this->scanCopy($from, $to); } } if(!empty($issues)){ $this->issues['manifest'][$manifestPath] = $issues; } } /** * Takes in where the file will is specified to be copied from and to * and ensures that there is no official sugar file there. If the file exists it will check * against the MD5 file list to see if Sugar Created the file * */ function scanCopy($from, $to){ //if the file doesn't exist for the $to then it is not overriding anything if(!file_exists($to))return; //if $to is a dir and $from is a file then make $to a full file path as well if(is_dir($to) && is_file($from)){ if(substr($to,-1) === '/'){ $to = substr($to, 0 , strlen($to) - 1); } $to .= '/'. basename($from); } //if the $to is a file and it is found in sugarFileExists then don't allow overriding it if(is_file($to) && $this->sugarFileExists($to)){ $this->issues['copy'][$from] = translate('ML_OVERRIDE_CORE_FILES') . '(' . $to . ')'; } if(is_dir($from)){ $d = dir($from); while($e = $d->read()){ if($e == '.' || $e == '..')continue; $this->scanCopy($from .'/'. $e, $to .'/' . $e); } } } /** *Main external function that takes in a path to a package and then scans *that package's manifest for disabled actions and then it scans the PHP files *for restricted function calls * */ public function scanPackage($path){ $this->pathToModule = $path; $this->scanManifest($path . '/manifest.php'); if(empty($GLOBALS['sugar_config']['moduleInstaller']['disableFileScan'])){ $this->scanDir($path); } } /** *This function will take all issues of the current instance and print them to the screen **/ public function displayIssues($package='Package'){ echo '<h2>'.str_replace('{PACKAGE}' , $package ,translate('ML_PACKAGE_SCANNING')). '</h2><BR><h2 class="error">' . translate('ML_INSTALLATION_FAILED') . '</h2><br><p>' .str_replace('{PACKAGE}' , $package ,translate('ML_PACKAGE_NOT_CONFIRM')). '</p><ul><li>'. translate('ML_OBTAIN_NEW_PACKAGE') . '<li>' . translate('ML_RELAX_LOCAL'). '</ul></p><br>' . translate('ML_SUGAR_LOADING_POLICY') . ' <a href=" http://kb.sugarcrm.com/custom/module-loader-restrictions-for-sugar-open-cloud/">' . translate('ML_SUGAR_KB') . '</a>.'. '<br>' . translate('ML_AVAIL_RESTRICTION'). ' <a href=" http://developers.sugarcrm.com/wordpress/2009/08/14/module-loader-restrictions/">' . translate('ML_SUGAR_DZ') . '</a>.<br><br>'; foreach($this->issues as $type=>$issues){ echo '<div class="error"><h2>'. ucfirst($type) .' ' . translate('ML_ISSUES') . '</h2> </div>'; echo '<div id="details' . $type . '" >'; foreach($issues as $file=>$issue){ $file = str_replace($this->pathToModule . '/', '', $file); echo '<div style="position:relative;left:10px"><b>' . $file . '</b></div><div style="position:relative;left:20px">'; if(is_array($issue)){ foreach($issue as $i){ echo "$i<br>"; } }else{ echo "$issue<br>"; } echo "</div>"; } echo '</div>'; } echo "<br><input class='button' onclick='document.location.href=\"index.php?module=Administration&action=UpgradeWizard&view=module\"' type='button' value=\"" . translate('LBL_UW_BTN_BACK_TO_MOD_LOADER') . "\" />"; } } ?>
anuradha-iic/sugar
ModuleInstall/ModuleScanner.php
PHP
agpl-3.0
14,797
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 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". ********************************************************************************/ require_once('modules/DynamicFields/templates/Fields/TemplateField.php'); class TemplateId extends TemplateField{ var $type='id'; var $len = 36 ; } ?>
aldridged/gtg-sugar
modules/DynamicFields/templates/Fields/TemplateId.php
PHP
agpl-3.0
2,249
import rdflib from rdflib.graph import ConjunctiveGraph as Graph from rdflib import plugin from rdflib.store import Store, NO_STORE, VALID_STORE from rdflib.namespace import Namespace from rdflib.term import Literal from rdflib.term import URIRef from tempfile import mkdtemp from gstudio.models import * def rdf_description(name, notation='xml' ): """ Funtion takes title of node, and rdf notation. """ valid_formats = ["xml", "n3", "ntriples", "trix"] default_graph_uri = "http://gstudio.gnowledge.org/rdfstore" configString = "/var/tmp/rdfstore" # Get the Sleepycat plugin. store = plugin.get('IOMemory', Store)('rdfstore') # Open previously created store, or create it if it doesn't exist yet graph = Graph(store="IOMemory", identifier = URIRef(default_graph_uri)) path = mkdtemp() rt = graph.open(path, create=False) if rt == NO_STORE: #There is no underlying Sleepycat infrastructure, create it graph.open(path, create=True) else: assert rt == VALID_STORE, "The underlying store is corrupt" # Now we'll add some triples to the graph & commit the changes rdflib = Namespace('http://sbox.gnowledge.org/gstudio/') graph.bind("gstudio", "http://gnowledge.org/") exclusion_fields = ["id", "rght", "node_ptr_id", "image", "lft", "_state", "_altnames_cache", "_tags_cache", "nid_ptr_id", "_mptt_cached_fields"] node=NID.objects.get(title=name) node_dict=node.__dict__ subject=str(node_dict['id']) for key in node_dict: if key not in exclusion_fields: predicate=str(key) pobject=str(node_dict[predicate]) graph.add((rdflib[subject], rdflib[predicate], Literal(pobject))) graph.commit() print graph.serialize(format=notation) graph.close() i=0 p=NID.objects.all() for each in p: rdf_description(p[i]) i=i+1
gnowledge/ncert_nroer
gstudio/testloop.py
Python
agpl-3.0
1,908
import os import pathlib2 import logging import yaml import sys import networkx as nx from collections import namedtuple import argparse TRAVIS_BUILD_DIR = os.environ.get("TRAVIS_BUILD_DIR") DOCKER_PATH_ROOT = pathlib2.Path(TRAVIS_BUILD_DIR, "docker", "build") CONFIG_FILE_PATH = pathlib2.Path(TRAVIS_BUILD_DIR, "util", "parsefiles_config.yml") LOGGER = logging.getLogger(__name__) def build_graph(git_dir, roles_dirs, aws_play_dirs, docker_play_dirs): """ Builds a dependency graph that shows relationships between roles and playbooks. An edge [A, B], where A and B are roles, signifies that A depends on B. An edge [C, D], where C is a playbook and D is a role, signifies that C uses D. Input: git_dir: A path to the top-most directory in the local git repository tool is to be run in. roles_dirs: A list of relative paths to directories in which Ansible roles reside. aws_play_dirs: A list of relative paths to directories in which AWS Ansible playbooks reside. docker_play_dirs: A list of relative paths to directories in which Docker Ansible playbooks reside. """ graph = nx.DiGraph() _map_roles_to_roles(graph, roles_dirs, git_dir, "dependencies", "role", "role") _map_plays_to_roles(graph, aws_play_dirs, git_dir, "roles", "aws_playbook", "role") _map_plays_to_roles(graph, docker_play_dirs, git_dir, "roles", "docker_playbook", "role") return graph def _map_roles_to_roles(graph, dirs, git_dir, key, type_1, type_2): """ Maps roles to the roles that they depend on. Input: graph: A networkx digraph that is used to map Ansible dependencies. dirs: A list of relative paths to directories in which Ansible roles reside. git_dir: A path to the top-most directory in the local git repository tool is to be run in. key: The key in a role yaml file in dirs that maps to relevant role data. In this case, key is "dependencies", because a role's dependent roles is of interest. type_1: Given edges A-B, the type of node A. type_2: Given edges A-B, the type of node B. Since this function maps roles to their dependent roles, both type_1 and type_2 are "role". """ Node = namedtuple('Node', ['name', 'type']) # for each role directory for d in dirs: d = pathlib2.Path(git_dir, d) # for all files/sub-directories in directory for item in d.iterdir(): # attempts to find meta/*.yml file in item directory tree roles = [f for f in item.glob("meta/*.yml")] # if a meta/*.yml file(s) exists for a role if roles: # for each role for role in roles: yaml_file = _open_yaml_file(role) # if not an empty yaml file and key in file if yaml_file is not None and key in yaml_file: # for each dependent role; yaml_file["dependencies"] returns list of # dependent roles for dependent in yaml_file[key]: # get role name of each dependent role name = _get_role_name(dependent) # add node for type_1, typically role node_1 = Node(item.name, type_1) # add node for type_2, typically dependent role node_2 = Node(name, type_2) # add edge, typically role - dependent role graph.add_edge(node_1, node_2) def _map_plays_to_roles(graph, dirs, git_dir, key, type_1, type_2): """ Maps plays to the roles they use. Input: graph: A networkx digraph that is used to map Ansible dependencies. dirs: A list of relative paths to directories in which Ansible playbooks reside. git_dir: A path to the top-most directory in the local git repository tool is to be run in. key: The key in a playbook yaml file in dirs that maps to relevant playbook data. In this case, key is "roles", because the roles used by a playbook is of interest. type_1: Given edges A-B, the type of node A. type_2: Given edges A-B, the type of node B. Since this function maps plays to the roles they use, both type_1 is a type of playbook and type_2 is "role". """ Node = namedtuple('Node', ['name', 'type']) # for each play directory for d in dirs: d = pathlib2.Path(git_dir, d) # for all files/sub-directories in directory for item in d.iterdir(): # if item is a file ending in .yml if item.match("*.yml"): # open .yml file for playbook yaml_file = _open_yaml_file(item) # if not an empty yaml file if yaml_file is not None: # for each play in yaml file for play in yaml_file: # if specified key in yaml file (e.g. "roles") if key in play: # for each role for role in play[key]: # get role name name = _get_role_name(role) #add node for type_1, typically for playbook node_1 = Node(item.stem, type_1) # add node for type_2, typically for role node_2 = Node(name, type_2) # add edge, typically playbook - role it uses graph.add_edge(node_1, node_2) def _open_yaml_file(file_str): """ Opens yaml file. Input: file_str: The path to yaml file to be opened. """ with (file_str.open(mode='r')) as file: try: yaml_file = yaml.load(file) return yaml_file except yaml.YAMLError, exc: LOGGER.error("error in configuration file: %s" % str(exc)) sys.exit(1) def change_set_to_roles(files, git_dir, roles_dirs, playbooks_dirs, graph): """ Converts change set consisting of a number of files to the roles that they represent/contain. Input: files: A list of files modified by a commit range. git_dir: A path to the top-most directory in the local git repository tool is to be run in. roles_dirs: A list of relative paths to directories in which Ansible roles reside. playbook_dirs: A list of relative paths to directories in which Ansible playbooks reside. graph: A networkx digraph that is used to map Ansible dependencies. """ # set of roles items = set() # for all directories containing roles for role_dir in roles_dirs: role_dir_path = pathlib2.Path(git_dir, role_dir) # get all files in the directories containing roles (i.e. all the roles in that directory) candidate_files = (f for f in role_dir_path.glob("**/*")) # for all the files in the change set for f in files: file_path = pathlib2.Path(git_dir, f) # if the change set file is in the set of role files if file_path in candidate_files: # get name of role and add it to set of roles of the change set items.add(_get_resource_name(file_path, "roles")) # for all directories containing playbooks for play_dir in playbooks_dirs: play_dir_path = pathlib2.Path(git_dir, play_dir) # get all files in directory containing playbook that end with yml extension # (i.e. all playbooks in that directory) candidate_files = (f for f in play_dir_path.glob("*.yml")) # for all filse in the change set for f in files: file_path = pathlib2.Path(git_dir, f) # if the change set file is in teh set of playbook files if file_path in candidate_files: # gets first level of children of playbook in graph, which represents # all roles the playbook uses descendants = nx.all_neighbors(graph, (file_path.stem, "aws_playbook")) # adds all the roles that a playbook uses to set of roles of the change set items |= {desc.name for desc in descendants} return items def _get_resource_name(path, kind): """ Gets name of resource from the filepath, which is the directory following occurence of kind. Input: path: A path to the resource (e.g. a role or a playbook) kind: A description of the type of resource; this keyword precedes the name of a role or a playbook in a file path and allows for the separation of its name; e.g. for "configuration/playbooks/roles/discovery/...", kind = "roles" returns "discovery" as the role name """ # get individual parts of a file path dirs = path.parts # type of resource is the next part of the file path after kind (e.g. after "roles" or "playbooks") return dirs[dirs.index(kind)+1] def get_dependencies(roles, graph): """ Determines all roles dependent on set of roles and returns set containing both. Input: roles: A set of roles. graph: A networkx digraph that is used to map Ansible dependencies. """ items = set() for role in roles: # add the role itself items.add(role) # add all the roles that depend on the role dependents = nx.descendants(graph, (role, "role")) items |= {dependent.name for dependent in dependents} return items def get_docker_plays(roles, graph): """Gets all docker plays that contain at least role in common with roles.""" # dict to determine coverage of plays coverage = dict.fromkeys(roles, False) items = set() docker_plays = (node.name for node in graph.nodes() if node.type == "docker_playbook") for play in docker_plays: # all roles that are used by play roles_nodes = nx.all_neighbors(graph, (play, "docker_playbook")) docker_roles = {role.name for role in roles_nodes} # compares roles and docker roles common_roles = roles & docker_roles # if their intersection is non-empty, add the docker role if common_roles: items.add(play) # each aws role that was in common is marked as being covered by a docker play for role in common_roles: coverage[role] = True # check coverage of roles for role in coverage: if not coverage[role]: LOGGER.warning("role '%s' is not covered." % role) return items def filter_docker_plays(plays, repo_path): """Filters out docker plays that do not have a Dockerfile.""" items = set() for play in plays: dockerfile = pathlib2.Path(DOCKER_PATH_ROOT, play, "Dockerfile") if dockerfile.exists(): items.add(play) else: LOGGER.warning("covered playbook '%s' does not have Dockerfile." % play) return items def _get_role_name(role): """ Resolves a role name from either a simple declaration or a dictionary style declaration. A simple declaration would look like: - foo A dictionary style declaration would look like: - role: rbenv rbenv_user: "{{ forum_user }}" rbenv_dir: "{{ forum_app_dir }}" rbenv_ruby_version: "{{ forum_ruby_version }}" :param role: :return: """ if isinstance(role, dict): return role['role'] elif isinstance(role, basestring): return role else: LOGGER.warning("role %s could not be resolved to a role name." % role) return None def arg_parse(): parser = argparse.ArgumentParser(description = 'Given a commit range, analyze Ansible dependencies between roles and playbooks ' 'and output a list of Docker plays affected by this commit range via these dependencies.') parser.add_argument('--verbose', help="set warnings to be displayed", action="store_true") return parser.parse_args() if __name__ == '__main__': args = arg_parse() # configure logging logging.basicConfig() if not args.verbose: logging.disable(logging.WARNING) # set of modified files in the commit range change_set = set() # read from standard in for line in sys.stdin: change_set.add(line.rstrip()) # configuration file is expected to be in the following format: # # roles_paths: # - <all paths relative to configuration repository that contain Ansible roles> # aws_plays_paths: # - <all paths relative to configuration repository that contain aws Ansible playbooks> # docker_plays_paths: # - <all paths relative to configuration repositroy that contain Docker Ansible playbooks> # read config file config = _open_yaml_file(CONFIG_FILE_PATH) # build graph graph = build_graph(TRAVIS_BUILD_DIR, config["roles_paths"], config["aws_plays_paths"], config["docker_plays_paths"]) # transforms list of roles and plays into list of original roles and the roles contained in the plays roles = change_set_to_roles(change_set, TRAVIS_BUILD_DIR, config["roles_paths"], config["aws_plays_paths"], graph) # expands roles set to include roles that are dependent on existing roles dependent_roles = get_dependencies(roles, graph) # determine which docker plays cover at least one role docker_plays = get_docker_plays(dependent_roles, graph) # filter out docker plays without a Dockerfile docker_plays = filter_docker_plays(docker_plays, TRAVIS_BUILD_DIR) # prints Docker plays print " ".join(str(play) for play in docker_plays)
karimdamak123/configuration2
util/parsefiles.py
Python
agpl-3.0
13,776
/* * * (c) Copyright Ascensio System Limited 2010-2015 * * This program is freeware. You can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html). * In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that * Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights. * * THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html * * You can contact Ascensio System SIA by email at sales@onlyoffice.com * * The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display * Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3. * * Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains * relevant author attributions when distributing the software. If the display of the logo in its graphic * form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE" * in every copy of the program you distribute. * Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks. * */ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ASC.Web.Community.Bookmarking { public partial class UserBookmarks { /// <summary> /// BookmarkingPageContent control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder BookmarkingPageContent; /// <summary> /// BookmarkingSideHolder control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder BookmarkingSideHolder; } }
StepProgrammer/CommunityServer
web/studio/ASC.Web.Studio/Products/Community/Modules/Bookmarking/UserBookmarks.aspx.designer.cs
C#
agpl-3.0
2,639
=begin Camaleon CMS is a content management system Copyright (C) 2015 by Owen Peredo Diaz Email: owenperedo@gmail.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 (GPLv3) for more details. =end class CamaleonCms::Meta < ActiveRecord::Base self.table_name = "#{PluginRoutes.static_system_info["db_prefix"]}metas" attr_accessible :objectid, :key, :value, :object_class end
raulanatol/camaleon-cms
app/models/camaleon_cms/meta.rb
Ruby
agpl-3.0
818
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package upgrader import ( "github.com/juju/errors" "github.com/juju/loggo" "github.com/juju/names" "github.com/juju/juju/apiserver/common" "github.com/juju/juju/apiserver/params" "github.com/juju/juju/environs/config" "github.com/juju/juju/state" "github.com/juju/juju/state/watcher" "github.com/juju/juju/version" ) var logger = loggo.GetLogger("juju.apiserver.upgrader") func init() { common.RegisterStandardFacade("Upgrader", 0, upgraderFacade) } // upgraderFacade is a bit unique vs the other API Facades, as it has two // implementations that actually expose the same API and which one gets // returned depends on who is calling. // Both of them conform to the exact Upgrader API, so the actual calls that are // available do not depend on who is currently connected. func upgraderFacade(st *state.State, resources *common.Resources, auth common.Authorizer) (Upgrader, error) { // The type of upgrader we return depends on who is asking. // Machines get an UpgraderAPI, units get a UnitUpgraderAPI. // This is tested in the api/upgrader package since there // are currently no direct srvRoot tests. // TODO(dfc) this is redundant tag, err := names.ParseTag(auth.GetAuthTag().String()) if err != nil { return nil, common.ErrPerm } switch tag.(type) { case names.MachineTag: return NewUpgraderAPI(st, resources, auth) case names.UnitTag: return NewUnitUpgraderAPI(st, resources, auth) } // Not a machine or unit. return nil, common.ErrPerm } type Upgrader interface { WatchAPIVersion(args params.Entities) (params.NotifyWatchResults, error) DesiredVersion(args params.Entities) (params.VersionResults, error) Tools(args params.Entities) (params.ToolsResults, error) SetTools(args params.EntitiesVersion) (params.ErrorResults, error) } // UpgraderAPI provides access to the Upgrader API facade. type UpgraderAPI struct { *common.ToolsGetter *common.ToolsSetter st *state.State resources *common.Resources authorizer common.Authorizer } // NewUpgraderAPI creates a new server-side UpgraderAPI facade. func NewUpgraderAPI( st *state.State, resources *common.Resources, authorizer common.Authorizer, ) (*UpgraderAPI, error) { if !authorizer.AuthMachineAgent() { return nil, common.ErrPerm } getCanReadWrite := func() (common.AuthFunc, error) { return authorizer.AuthOwner, nil } env, err := st.Environment() if err != nil { return nil, err } urlGetter := common.NewToolsURLGetter(env.UUID(), st) return &UpgraderAPI{ ToolsGetter: common.NewToolsGetter(st, st, st, urlGetter, getCanReadWrite), ToolsSetter: common.NewToolsSetter(st, getCanReadWrite), st: st, resources: resources, authorizer: authorizer, }, nil } // WatchAPIVersion starts a watcher to track if there is a new version // of the API that we want to upgrade to func (u *UpgraderAPI) WatchAPIVersion(args params.Entities) (params.NotifyWatchResults, error) { result := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } for i, agent := range args.Entities { tag, err := names.ParseTag(agent.Tag) if err != nil { return params.NotifyWatchResults{}, errors.Trace(err) } err = common.ErrPerm if u.authorizer.AuthOwner(tag) { watch := u.st.WatchForEnvironConfigChanges() // Consume the initial event. Technically, API // calls to Watch 'transmit' the initial event // in the Watch response. But NotifyWatchers // have no state to transmit. if _, ok := <-watch.Changes(); ok { result.Results[i].NotifyWatcherId = u.resources.Register(watch) err = nil } else { err = watcher.EnsureErr(watch) } } result.Results[i].Error = common.ServerError(err) } return result, nil } func (u *UpgraderAPI) getGlobalAgentVersion() (version.Number, *config.Config, error) { // Get the Agent Version requested in the Environment Config cfg, err := u.st.EnvironConfig() if err != nil { return version.Number{}, nil, err } agentVersion, ok := cfg.AgentVersion() if !ok { return version.Number{}, nil, errors.New("agent version not set in environment config") } return agentVersion, cfg, nil } type hasIsManager interface { IsManager() bool } func (u *UpgraderAPI) entityIsManager(tag names.Tag) bool { entity, err := u.st.FindEntity(tag) if err != nil { return false } if m, ok := entity.(hasIsManager); !ok { return false } else { return m.IsManager() } } // DesiredVersion reports the Agent Version that we want that agent to be running func (u *UpgraderAPI) DesiredVersion(args params.Entities) (params.VersionResults, error) { results := make([]params.VersionResult, len(args.Entities)) if len(args.Entities) == 0 { return params.VersionResults{}, nil } agentVersion, _, err := u.getGlobalAgentVersion() if err != nil { return params.VersionResults{}, common.ServerError(err) } // Is the desired version greater than the current API server version? isNewerVersion := agentVersion.Compare(version.Current) > 0 for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { results[i].Error = common.ServerError(err) continue } err = common.ErrPerm if u.authorizer.AuthOwner(tag) { // Only return the globally desired agent version if the // asking entity is a machine agent with JobManageEnviron or // if this API server is running the globally desired agent // version. Otherwise report this API server's current // agent version. // // This ensures that state machine agents will upgrade // first - once they have restarted and are running the // new version other agents will start to see the new // agent version. if !isNewerVersion || u.entityIsManager(tag) { results[i].Version = &agentVersion } else { logger.Debugf("desired version is %s, but current version is %s and agent is not a manager node", agentVersion, version.Current) results[i].Version = &version.Current } err = nil } results[i].Error = common.ServerError(err) } return params.VersionResults{Results: results}, nil }
fwereade/juju
apiserver/upgrader/upgrader.go
GO
agpl-3.0
6,177
package info.nightscout.androidaps.watchfaces; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Shader; import android.os.Bundle; import android.os.PowerManager; import android.os.SystemClock; import android.preference.PreferenceManager; import androidx.core.content.ContextCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.support.wearable.view.WatchViewStub; import android.support.wearable.watchface.WatchFaceStyle; import android.text.format.DateFormat; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.WindowInsets; import android.view.WindowManager; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.gms.wearable.DataMap; import com.ustwo.clockwise.common.WatchFaceTime; import com.ustwo.clockwise.common.WatchMode; import com.ustwo.clockwise.common.WatchShape; import com.ustwo.clockwise.wearable.WatchFace; import java.util.ArrayList; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.BasalWatchData; import info.nightscout.androidaps.data.BgWatchData; import info.nightscout.androidaps.data.BolusWatchData; import info.nightscout.androidaps.data.ListenerService; import info.nightscout.androidaps.data.TempWatchData; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; import lecho.lib.hellocharts.view.LineChartView; /** * Created by adrianLxM. */ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener { public final static IntentFilter INTENT_FILTER; public static final int SCREENSIZE_SMALL = 280; public TextView mTime, mSgv, mTimestamp, mDelta, mAvgDelta; public RelativeLayout mRelativeLayout; public long sgvLevel = 0; public int batteryLevel = 1; public int ageLevel = 1; public int highColor = Color.YELLOW; public int lowColor = Color.RED; public int midColor = Color.WHITE; public int gridColour = Color.WHITE; public int basalBackgroundColor = Color.BLUE; public int basalCenterColor = Color.BLUE; public int bolusColor = Color.MAGENTA; public int carbsColor = Color.GREEN; public int pointSize = 2; public boolean lowResMode = false; public boolean layoutSet = false; public BgGraphBuilder bgGraphBuilder; public LineChartView chart; public long datetime; public ArrayList<BgWatchData> bgDataList = new ArrayList<>(); public ArrayList<TempWatchData> tempWatchDataList = new ArrayList<>(); public ArrayList<BasalWatchData> basalWatchDataList = new ArrayList<>(); public ArrayList<BolusWatchData> bolusWatchDataList = new ArrayList<>(); public ArrayList<BgWatchData> predictionList = new ArrayList<>(); public PowerManager.WakeLock wakeLock; public View layoutView; private final Point displaySize = new Point(); private int specW, specH; private int animationAngle = 0; private boolean isAnimated = false; private LocalBroadcastManager localBroadcastManager; private MessageReceiver messageReceiver; protected SharedPreferences sharedPrefs; private String rawString = "000 | 000 | 000"; private String batteryString = "--"; private String sgvString = "--"; private String externalStatusString = "no status"; private String cobString = ""; private TextView statusView; private long chartTapTime = 0l; private long sgvTapTime = 0l; @Override public void onCreate() { super.onCreate(); Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); display.getSize(displaySize); wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:BIGChart"); specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY); specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY); sharedPrefs = PreferenceManager .getDefaultSharedPreferences(this); sharedPrefs.registerOnSharedPreferenceChangeListener(this); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); DisplayMetrics metrics = getResources().getDisplayMetrics(); if(metrics.widthPixels < SCREENSIZE_SMALL || metrics.heightPixels < SCREENSIZE_SMALL){ layoutView = inflater.inflate(R.layout.activity_bigchart_small, null); } else { layoutView = inflater.inflate(R.layout.activity_bigchart, null); } performViewSetup(); } @Override protected void onLayout(WatchShape shape, Rect screenBounds, WindowInsets screenInsets) { super.onLayout(shape, screenBounds, screenInsets); layoutView.onApplyWindowInsets(screenInsets); } public void performViewSetup() { final WatchViewStub stub = (WatchViewStub) layoutView.findViewById(R.id.watch_view_stub); IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND); messageReceiver = new MessageReceiver(); localBroadcastManager = LocalBroadcastManager.getInstance(this); localBroadcastManager.registerReceiver(messageReceiver, messageFilter); stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() { @Override public void onLayoutInflated(WatchViewStub stub) { mTime = (TextView) stub.findViewById(R.id.watch_time); mSgv = (TextView) stub.findViewById(R.id.sgv); mTimestamp = (TextView) stub.findViewById(R.id.timestamp); mDelta = (TextView) stub.findViewById(R.id.delta); mAvgDelta = (TextView) stub.findViewById(R.id.avgdelta); mRelativeLayout = (RelativeLayout) stub.findViewById(R.id.main_layout); chart = (LineChartView) stub.findViewById(R.id.chart); statusView = (TextView) stub.findViewById(R.id.aps_status); layoutSet = true; showAgeAndStatus(); mRelativeLayout.measure(specW, specH); mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); } }); ListenerService.requestData(this); wakeLock.acquire(50); } @Override protected void onTapCommand(int tapType, int x, int y, long eventTime) { int extra = mSgv!=null?(mSgv.getRight() - mSgv.getLeft())/2:0; if (tapType == TAP_TYPE_TAP&& x >=chart.getLeft() && x <= chart.getRight()&& y >= chart.getTop() && y <= chart.getBottom()){ if (eventTime - chartTapTime < 800){ changeChartTimeframe(); } chartTapTime = eventTime; } else if (tapType == TAP_TYPE_TAP&& x + extra >=mSgv.getLeft() && x - extra <= mSgv.getRight()&& y >= mSgv.getTop() && y <= mSgv.getBottom()){ if (eventTime - sgvTapTime < 800){ Intent intent = new Intent(this, MainMenuActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } sgvTapTime = eventTime; } } private void changeChartTimeframe() { int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); timeframe = (timeframe%5) + 1; sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).commit(); } protected void onWatchModeChanged(WatchMode watchMode) { if(lowResMode ^ isLowRes(watchMode)){ //if there was a change in lowResMode lowResMode = isLowRes(watchMode); setColor(); } else if (! sharedPrefs.getBoolean("dark", true)){ //in bright mode: different colours if active: setColor(); } } private boolean isLowRes(WatchMode watchMode) { return (watchMode == WatchMode.LOW_BIT) || (watchMode == WatchMode.LOW_BIT_BURN_IN) || (watchMode == WatchMode.LOW_BIT_BURN_IN); } @Override protected WatchFaceStyle getWatchFaceStyle(){ return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); } public int ageLevel() { if(timeSince() <= (1000 * 60 * 12)) { return 1; } else { return 0; } } public double timeSince() { return System.currentTimeMillis() - datetime; } public String readingAge(boolean shortString) { if (datetime == 0) { return shortString?"--'":"-- Minute ago"; } int minutesAgo = (int) Math.floor(timeSince()/(1000*60)); if (minutesAgo == 1) { return minutesAgo + (shortString?"'":" Minute ago"); } return minutesAgo + (shortString?"'":" Minutes ago"); } @Override public void onDestroy() { if(localBroadcastManager != null && messageReceiver != null){ localBroadcastManager.unregisterReceiver(messageReceiver);} if (sharedPrefs != null){ sharedPrefs.unregisterOnSharedPreferenceChangeListener(this); } super.onDestroy(); } static { INTENT_FILTER = new IntentFilter(); INTENT_FILTER.addAction(Intent.ACTION_TIME_TICK); INTENT_FILTER.addAction(Intent.ACTION_TIMEZONE_CHANGED); INTENT_FILTER.addAction(Intent.ACTION_TIME_CHANGED); } @Override protected void onDraw(Canvas canvas) { if(layoutSet) { this.mRelativeLayout.draw(canvas); Log.d("onDraw", "draw"); } } @Override protected void onTimeChanged(WatchFaceTime oldTime, WatchFaceTime newTime) { if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { wakeLock.acquire(50); final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(BIGChart.this); mTime.setText(timeFormat.format(System.currentTimeMillis())); showAgeAndStatus(); if(ageLevel()<=0) { mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } else { mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); } missedReadingAlert(); mRelativeLayout.measure(specW, specH); mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); } } public class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getBundleExtra("data"); if (layoutSet && bundle !=null) { DataMap dataMap = DataMap.fromBundle(bundle); wakeLock.acquire(50); sgvLevel = dataMap.getLong("sgvLevel"); batteryLevel = dataMap.getInt("batteryLevel"); datetime = dataMap.getLong("timestamp"); rawString = dataMap.getString("rawString"); sgvString = dataMap.getString("sgvString"); batteryString = dataMap.getString("battery"); mSgv.setText(dataMap.getString("sgvString")); if(ageLevel()<=0) { mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } else { mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); } final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(BIGChart.this); mTime.setText(timeFormat.format(System.currentTimeMillis())); showAgeAndStatus(); String delta = dataMap.getString("delta"); if (delta.endsWith(" mg/dl")) { mDelta.setText(delta.substring(0, delta.length() - 6)); } else if (delta.endsWith(" mmol/l")||delta.endsWith(" mmol")) { mDelta.setText(delta.substring(0, delta.length() - 5)); } else { mDelta.setText(delta); } String avgDelta = dataMap.getString("avgDelta"); if (delta.endsWith(" mg/dl")) { mAvgDelta.setText(avgDelta.substring(0, avgDelta.length() - 6)); } else if (avgDelta.endsWith(" mmol/l")||avgDelta.endsWith(" mmol")) { mAvgDelta.setText(avgDelta.substring(0, avgDelta.length() - 5)); } else { mAvgDelta.setText(avgDelta); } if (chart != null) { addToWatchSet(dataMap); setupCharts(); } mRelativeLayout.measure(specW, specH); mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); invalidate(); setColor(); //start animation? // dataMap.getDataMapArrayList("entries") == null -> not on "resend data". if (!lowResMode && (sharedPrefs.getBoolean("animation", false) && dataMap.getDataMapArrayList("entries") == null && (sgvString.equals("100") || sgvString.equals("5.5") || sgvString.equals("5,5")))) { startAnimation(); } } //status bundle = intent.getBundleExtra("status"); if (layoutSet && bundle != null) { DataMap dataMap = DataMap.fromBundle(bundle); wakeLock.acquire(50); externalStatusString = dataMap.getString("externalStatusString"); cobString = dataMap.getString("cob"); showAgeAndStatus(); mRelativeLayout.measure(specW, specH); mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); invalidate(); setColor(); } //basals and temps bundle = intent.getBundleExtra("basals"); if (layoutSet && bundle != null) { DataMap dataMap = DataMap.fromBundle(bundle); wakeLock.acquire(500); loadBasalsAndTemps(dataMap); mRelativeLayout.measure(specW, specH); mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); invalidate(); setColor(); } } } private void loadBasalsAndTemps(DataMap dataMap) { ArrayList<DataMap> temps = dataMap.getDataMapArrayList("temps"); if (temps != null) { tempWatchDataList = new ArrayList<>(); for (DataMap temp : temps) { TempWatchData twd = new TempWatchData(); twd.startTime = temp.getLong("starttime"); twd.startBasal = temp.getDouble("startBasal"); twd.endTime = temp.getLong("endtime"); twd.endBasal = temp.getDouble("endbasal"); twd.amount = temp.getDouble("amount"); tempWatchDataList.add(twd); } } ArrayList<DataMap> basals = dataMap.getDataMapArrayList("basals"); if (basals != null) { basalWatchDataList = new ArrayList<>(); for (DataMap basal : basals) { BasalWatchData bwd = new BasalWatchData(); bwd.startTime = basal.getLong("starttime"); bwd.endTime = basal.getLong("endtime"); bwd.amount = basal.getDouble("amount"); basalWatchDataList.add(bwd); } } ArrayList<DataMap> boluses = dataMap.getDataMapArrayList("boluses"); if (boluses != null) { bolusWatchDataList = new ArrayList<>(); for (DataMap bolus : boluses) { BolusWatchData bwd = new BolusWatchData(); bwd.date = bolus.getLong("date"); bwd.bolus = bolus.getDouble("bolus"); bwd.carbs = bolus.getDouble("carbs"); bwd.isSMB = bolus.getBoolean("isSMB"); bwd.isValid = bolus.getBoolean("isValid"); bolusWatchDataList.add(bwd); } } ArrayList<DataMap> predictions = dataMap.getDataMapArrayList("predictions"); if (boluses != null) { predictionList = new ArrayList<>(); for (DataMap prediction : predictions) { BgWatchData bwd = new BgWatchData(); bwd.timestamp = prediction.getLong("timestamp"); bwd.sgv = prediction.getDouble("sgv"); bwd.color = prediction.getInt("color"); predictionList.add(bwd); } } } private void showAgeAndStatus() { if( mTimestamp != null){ mTimestamp.setText(readingAge(true)); } boolean showStatus = sharedPrefs.getBoolean("showExternalStatus", true); boolean showAvgDelta = sharedPrefs.getBoolean("showAvgDelta", true); if(showAvgDelta){ mAvgDelta.setVisibility(View.VISIBLE); } else { mAvgDelta.setVisibility(View.GONE); } if(showStatus){ String status = externalStatusString; if (sharedPrefs.getBoolean("show_cob", true)) { status = externalStatusString + " " + cobString; } statusView.setText(status); statusView.setVisibility(View.VISIBLE); } else { statusView.setVisibility(View.GONE); } } public void setColor() { if(lowResMode){ setColorLowRes(); } else if (sharedPrefs.getBoolean("dark", true)) { setColorDark(); } else { setColorBright(); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){ setColor(); if(layoutSet){ showAgeAndStatus(); mRelativeLayout.measure(specW, specH); mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); } invalidate(); } protected void updateRainbow() { animationAngle = (animationAngle + 1) % 360; //Animation matrix: int[] rainbow = {Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE , Color.CYAN}; Shader shader = new LinearGradient(0, 0, 0, 20, rainbow, null, Shader.TileMode.MIRROR); Matrix matrix = new Matrix(); matrix.setRotate(animationAngle); shader.setLocalMatrix(matrix); mSgv.getPaint().setShader(shader); invalidate(); } private synchronized boolean isAnimated() { return isAnimated; } private synchronized void setIsAnimated(boolean isAnimated) { this.isAnimated = isAnimated; } void startAnimation() { Log.d("CircleWatchface", "start startAnimation"); Thread animator = new Thread() { public void run() { setIsAnimated(true); for (int i = 0; i <= 8 * 1000 / 40; i++) { updateRainbow(); SystemClock.sleep(40); } mSgv.getPaint().setShader(null); setIsAnimated(false); invalidate(); setColor(); System.gc(); } }; animator.start(); } protected void setColorLowRes() { mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_statusView)); mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_Timestamp)); if (chart != null) { highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); gridColour = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark_lowres); basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light_lowres); pointSize = 2; setupCharts(); } } protected void setColorDark() { mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_statusView)); mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); if (sgvLevel == 1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); } else if (sgvLevel == 0) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); } else if (sgvLevel == -1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); } if (ageLevel == 1) { mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_Timestamp)); } else { mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); } if (chart != null) { highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor); lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor); midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); gridColour = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); pointSize = 2; setupCharts(); } } protected void setColorBright() { if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_bigchart_time)); statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_bigchart_status)); mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); if (sgvLevel == 1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); } else if (sgvLevel == 0) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); } else if (sgvLevel == -1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); } if (ageLevel == 1) { mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_mTimestamp1)); } else { mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_mTimestamp)); } if (chart != null) { highColor = ContextCompat.getColor(getApplicationContext(), R.color.light_highColor); lowColor = ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor); midColor = ContextCompat.getColor(getApplicationContext(), R.color.light_midColor); gridColour = ContextCompat.getColor(getApplicationContext(), R.color.light_gridColor); basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); pointSize = 2; setupCharts(); } } else { setColorDark(); } } public void missedReadingAlert() { int minutes_since = (int) Math.floor(timeSince()/(1000*60)); if(minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { ListenerService.requestData(this); // attempt endTime recover missing data } } public void addToWatchSet(DataMap dataMap) { ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries"); if (entries != null) { bgDataList = new ArrayList<BgWatchData>(); for (DataMap entry : entries) { double sgv = entry.getDouble("sgvDouble"); double high = entry.getDouble("high"); double low = entry.getDouble("low"); long timestamp = entry.getLong("timestamp"); int color = entry.getInt("color", 0); bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color)); } } else { double sgv = dataMap.getDouble("sgvDouble"); double high = dataMap.getDouble("high"); double low = dataMap.getDouble("low"); long timestamp = dataMap.getLong("timestamp"); int color = dataMap.getInt("color", 0); final int size = bgDataList.size(); if (size > 0) { if (bgDataList.get(size - 1).timestamp == timestamp) return; // Ignore duplicates. } bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color)); } for (int i = 0; i < bgDataList.size(); i++) { if (bgDataList.get(i).timestamp < (System.currentTimeMillis() - (1000 * 60 * 60 * 5))) { bgDataList.remove(i); //Get rid of anything more than 5 hours old break; } } } public void setupCharts() { if(bgDataList.size() > 0) { //Dont crash things just because we dont have values, people dont like crashy things int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); if (lowResMode) { bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, predictionList, tempWatchDataList, basalWatchDataList, bolusWatchDataList, pointSize, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); } else { bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, predictionList, tempWatchDataList, basalWatchDataList, bolusWatchDataList, pointSize, highColor, lowColor, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); } chart.setLineChartData(bgGraphBuilder.lineData()); chart.setViewportCalculationEnabled(true); chart.setMaximumViewport(chart.getMaximumViewport()); } else { ListenerService.requestData(this); } } }
PoweRGbg/AndroidAPS
wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java
Java
agpl-3.0
29,951
class ChangeGithubProjectRelationship < ActiveRecord::Migration def change remove_column :github_repositories, :project_id add_column :projects, :github_repository_id, :integer end end
samjacobclift/libraries.io
db/migrate/20150204004703_change_github_project_relationship.rb
Ruby
agpl-3.0
197
# This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from shuup.campaigns.models.catalog_filters import ( CategoryFilter, ProductFilter, ProductTypeFilter ) from ._base import BaseRuleModelForm class ProductTypeFilterForm(BaseRuleModelForm): class Meta(BaseRuleModelForm.Meta): model = ProductTypeFilter class ProductFilterForm(BaseRuleModelForm): class Meta(BaseRuleModelForm.Meta): model = ProductFilter class CategoryFilterForm(BaseRuleModelForm): class Meta(BaseRuleModelForm.Meta): model = CategoryFilter
suutari-ai/shoop
shuup/campaigns/admin_module/forms/_catalog_filters.py
Python
agpl-3.0
734
# frozen_string_literal: true module Decidim module Consultations # This query class filters all consultations given an organization. class OrganizationActiveConsultations < Rectify::Query def self.for(organization) new(organization).query end def initialize(organization) @organization = organization end def query Decidim::Consultation.where(organization: @organization).active end end end end
AjuntamentdeBarcelona/decidim
decidim-consultations/app/queries/decidim/consultations/organization_active_consultations.rb
Ruby
agpl-3.0
475
""" ACE message types for the calendar_sync module. """ from openedx.core.djangoapps.ace_common.message import BaseMessageType class CalendarSync(BaseMessageType): def __init__(self, *args, **kwargs): super(CalendarSync, self).__init__(*args, **kwargs) self.options['transactional'] = True
edx-solutions/edx-platform
openedx/features/calendar_sync/message_types.py
Python
agpl-3.0
315
/* * Async_DataObjectListener.java Version-1.4, 2002/11/22 09:26:10 -0800 (Fri) * ECTF S.410-R2 Source code distribution. * * Copyright (c) 2002, Enterprise Computer Telephony Forum (ECTF), * All Rights Reserved. * * Use and redistribution of this file is subject to a License. * For terms and conditions see: javax/telephony/media/LICENSE.HTML * * In short, you can use this source code if you keep and display * the ECTF Copyright and the License conditions. The code is supplied * "AS IS" and ECTF disclaims all warranties and liability. */ package javax.telephony.media.container.async; import javax.telephony.media.*; import javax.telephony.media.container.*; /** * Listener for DataObject completion events. * * @author Jeff Peck * @since JTAPI-1.4 */ public interface Async_DataObjectListener extends MediaListener { public void onDataObjectEventDone(DataObjectEvent event); }
kerr-huang/openss7
src/java/javax/telephony/media/container/async/Async_DataObjectListener.java
Java
agpl-3.0
913
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to the responsive locomotion way of traveling! # # LICENCE: 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/>. # # Stay tuned using # twitter @navitia # channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org # https://groups.google.com/d/forum/navitia # www.navitia.io from __future__ import with_statement from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata from flask import current_app config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) target_metadata = current_app.extensions['migrate'].db.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def exclude_tables_from_config(config_): tables_ = config_.get("tables", None) if tables_ is not None: tables = tables_.split(",") return tables exclude_tables = exclude_tables_from_config(config.get_section('alembic:exclude')) def include_object(object, name, type_, reflected, compare_to): if type_ == "table" and name in exclude_tables: return False else: return True def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ url = config.get_main_option("sqlalchemy.url") context.configure(url=url) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ engine = engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool ) connection = engine.connect() context.configure(connection=connection, target_metadata=target_metadata, include_object=include_object) try: with context.begin_transaction(): context.run_migrations() finally: connection.close() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
xlqian/navitia
source/tyr/migrations/env.py
Python
agpl-3.0
3,771
# frozen_string_literal: true require 'rails_helper' describe 'devise/mailer/confirmation_instructions.html.haml', type: "view" do context "logged in" do before do @resource = FactoryBot.create(:member) render end it 'has a confirmation link' do rendered.should have_content 'Confirm my account' end it 'has a link to the homepage' do rendered.should have_content root_url end end end
Br3nda/growstuff
spec/views/devise/mailer/confirmation_instructions_spec.rb
Ruby
agpl-3.0
441
/** * Copyright (c) 2012, 2013 Fraunhofer Institute FOKUS * * This file is part of Open Data Platform. * * Open Data Platform 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. * Open Data Plaform 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 Open Data Platform. If not, see <http://www.gnu.org/licenses/agpl-3.0>. */ /** * Provides the registry modelling intefaces * * @author sim * */ package de.fhg.fokus.odp.registry.model;
fraunhoferfokus/odp-opendataregistry-client
src/main/java/de/fhg/fokus/odp/registry/model/package-info.java
Java
agpl-3.0
919
/** * Copyright © MyCollab * <p> * 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. * <p> * 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. * <p> * 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.mycollab.module.project.view; import com.mycollab.common.i18n.GenericI18Enum; import com.mycollab.db.arguments.SetSearchField; import com.mycollab.db.arguments.StringSearchField; import com.mycollab.module.project.ProjectTypeConstants; import com.mycollab.module.project.domain.Project; import com.mycollab.module.project.domain.SimpleProject; import com.mycollab.module.project.domain.criteria.FollowingTicketSearchCriteria; import com.mycollab.module.project.i18n.BugI18nEnum; import com.mycollab.module.project.i18n.RiskI18nEnum; import com.mycollab.module.project.i18n.TaskI18nEnum; import com.mycollab.module.project.service.ProjectService; import com.mycollab.module.project.ui.ProjectAssetsManager; import com.mycollab.spring.AppContextUtil; import com.mycollab.vaadin.AppUI; import com.mycollab.vaadin.UserUIContext; import com.mycollab.vaadin.ui.HeaderWithIcon; import com.mycollab.vaadin.web.ui.BasicSearchLayout; import com.mycollab.vaadin.web.ui.DefaultGenericSearchPanel; import com.mycollab.vaadin.web.ui.SearchLayout; import com.mycollab.vaadin.web.ui.WebThemes; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.*; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.vaadin.viritin.button.MButton; import org.vaadin.viritin.layouts.MHorizontalLayout; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /** * @author MyCollab Ltd. * @since 4.0.0 */ public class FollowingTicketSearchPanel extends DefaultGenericSearchPanel<FollowingTicketSearchCriteria> { private static final long serialVersionUID = 1L; private FollowingTicketBasicSearchLayout basicSearchLayout; private List<SimpleProject> projects; @Override protected HeaderWithIcon buildSearchTitle() { return null; } @Override protected SearchLayout<FollowingTicketSearchCriteria> createBasicSearchLayout() { basicSearchLayout = new FollowingTicketBasicSearchLayout(); return basicSearchLayout; } @Override protected SearchLayout<FollowingTicketSearchCriteria> createAdvancedSearchLayout() { return null; } public void doSearch() { this.callSearchAction(); } private class FollowingTicketBasicSearchLayout extends BasicSearchLayout<FollowingTicketSearchCriteria> { private static final long serialVersionUID = 1L; private UserInvolvedProjectsListSelect projectField; private TextField summaryField; private CheckBox taskSelect, bugSelect, riskSelect; FollowingTicketBasicSearchLayout() { super(FollowingTicketSearchPanel.this); } @Override public ComponentContainer constructBody() { MHorizontalLayout basicSearchBody = new MHorizontalLayout().withMargin(true); GridLayout selectionLayout = new GridLayout(5, 2); selectionLayout.setSpacing(true); selectionLayout.setMargin(true); selectionLayout.setDefaultComponentAlignment(Alignment.TOP_RIGHT); basicSearchBody.addComponent(selectionLayout); Label summaryLb = new Label("Summary:"); summaryLb.setWidthUndefined(); selectionLayout.addComponent(summaryLb, 0, 0); summaryField = new TextField(); summaryField.setWidth("100%"); summaryField.setPlaceholder(UserUIContext.getMessage(GenericI18Enum.ACTION_QUERY_BY_TEXT)); selectionLayout.addComponent(summaryField, 1, 0); Label typeLb = new Label("Type:"); typeLb.setWidthUndefined(); selectionLayout.addComponent(typeLb, 0, 1); MHorizontalLayout typeSelectWrapper = new MHorizontalLayout().withMargin(new MarginInfo(false, true, false, false)); selectionLayout.addComponent(typeSelectWrapper, 1, 1); taskSelect = new CheckBox(UserUIContext.getMessage(TaskI18nEnum.SINGLE), true); taskSelect.setIcon(ProjectAssetsManager.getAsset(ProjectTypeConstants.TASK)); bugSelect = new CheckBox(UserUIContext.getMessage(BugI18nEnum.SINGLE), true); bugSelect.setIcon(ProjectAssetsManager.getAsset(ProjectTypeConstants.BUG)); riskSelect = new CheckBox(UserUIContext.getMessage(RiskI18nEnum.SINGLE), true); riskSelect.setIcon(ProjectAssetsManager.getAsset(ProjectTypeConstants.RISK)); typeSelectWrapper.with(taskSelect, bugSelect, riskSelect); Label projectLb = new Label("Project:"); projectLb.setWidthUndefined(); selectionLayout.addComponent(projectLb, 2, 0); projectField = new UserInvolvedProjectsListSelect(); projectField.setWidth("300px"); projectField.setRows(4); selectionLayout.addComponent(projectField, 3, 0, 3, 1); MButton queryBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_SUBMIT), clickEvent -> doSearch()) .withStyleName(WebThemes.BUTTON_ACTION); selectionLayout.addComponent(queryBtn, 4, 0); return basicSearchBody; } @Override protected FollowingTicketSearchCriteria fillUpSearchCriteria() { FollowingTicketSearchCriteria searchCriteria = new FollowingTicketSearchCriteria(); searchCriteria.setUser(StringSearchField.and(UserUIContext.getUsername())); List<String> types = new ArrayList<>(); if (taskSelect.getValue()) { types.add(ProjectTypeConstants.TASK); } if (bugSelect.getValue()) { types.add(ProjectTypeConstants.BUG); } if (riskSelect.getValue()) { types.add(ProjectTypeConstants.RISK); } if (types.size() > 0) { searchCriteria.setTypes(new SetSearchField<>(types.toArray(new String[types.size()]))); } else { searchCriteria.setTypes(null); } String summary = summaryField.getValue().trim(); searchCriteria.setName(StringSearchField.and(StringUtils.isEmpty(summary) ? "" : summary)); Collection<SimpleProject> selectedProjects = projectField.getValue(); if (CollectionUtils.isNotEmpty(selectedProjects)) { List<Integer> keys = selectedProjects.stream().map(Project::getId).collect(Collectors.toList()); searchCriteria.setExtraTypeIds(new SetSearchField<>(keys)); } else { List<Integer> keys = projects.stream().map(Project::getId).collect(Collectors.toList()); if (keys.size() > 0) { searchCriteria.setExtraTypeIds(new SetSearchField<>(keys.toArray(new Integer[keys.size()]))); } } return searchCriteria; } } private class UserInvolvedProjectsListSelect extends ListSelect<SimpleProject> { private static final long serialVersionUID = 1L; UserInvolvedProjectsListSelect() { projects = AppContextUtil.getSpringBean(ProjectService.class) .getProjectsUserInvolved(UserUIContext.getUsername(), AppUI.getAccountId()); setItems(projects); setItemCaptionGenerator((ItemCaptionGenerator<SimpleProject>) Project::getName); } } }
esofthead/mycollab
mycollab-web/src/main/java/com/mycollab/module/project/view/FollowingTicketSearchPanel.java
Java
agpl-3.0
8,167
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * 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. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ if (file_exists($this->DocPath() . 'config_' . $this->Environment() . '.php')) { $customConfig = $this->loadConfig($this->DocPath() . 'config_' . $this->Environment() . '.php'); } elseif (file_exists($this->DocPath() . 'config.php')) { $customConfig = $this->loadConfig($this->DocPath() . 'config.php'); } else { $customConfig = []; } if (!is_array($customConfig)) { throw new Enlight_Exception('The custom configuration file must return an array.'); } return array_replace_recursive([ 'custom' => [], 'trustedproxies' => [], 'cdn' => [ 'backend' => 'local', 'strategy' => 'md5', 'adapters' => [ 'local' => [ 'type' => 'local', 'mediaUrl' => '', 'permissions' => [ 'file' => [ 'public' => 0666 & ~umask(), 'private' => 0600 & ~umask(), ], 'dir' => [ 'public' => 0777 & ~umask(), 'private' => 0700 & ~umask(), ], ], 'path' => realpath(__DIR__ . '/../../../'), ], 'ftp' => [ 'type' => 'ftp', 'mediaUrl' => '', 'host' => '', 'username' => '', 'password' => '', 'port' => 21, 'root' => '/', 'passive' => true, 'ssl' => false, 'timeout' => 30, ], ], ], 'csrfProtection' => [ 'frontend' => true, 'backend' => true, ], 'snippet' => [ 'readFromDb' => true, 'writeToDb' => true, 'readFromIni' => false, 'writeToIni' => false, 'showSnippetPlaceholder' => false, ], 'errorHandler' => [ 'throwOnRecoverableError' => false, ], 'db' => [ 'username' => 'root', 'password' => '', 'dbname' => 'shopware', 'host' => 'localhost', 'charset' => 'utf8', 'adapter' => 'pdo_mysql', ], 'es' => [ 'prefix' => 'sw_shop', 'enabled' => false, 'write_backlog' => true, 'number_of_replicas' => null, 'number_of_shards' => null, 'wait_for_status' => 'green', 'client' => [ 'hosts' => [ 'localhost:9200', ], ], ], 'front' => [ 'noErrorHandler' => false, 'throwExceptions' => false, 'disableOutputBuffering' => false, 'showException' => false, 'charset' => 'utf-8', ], 'config' => [], 'store' => [ 'apiEndpoint' => 'https://api.shopware.com', ], 'plugin_directories' => [ 'Default' => $this->AppPath('Plugins_Default'), 'Local' => $this->AppPath('Plugins_Local'), 'Community' => $this->AppPath('Plugins_Community'), 'ShopwarePlugins' => $this->DocPath('custom_plugins'), ], 'template' => [ 'compileCheck' => true, 'compileLocking' => true, 'useSubDirs' => true, 'forceCompile' => false, 'useIncludePath' => true, 'charset' => 'utf-8', 'forceCache' => false, 'cacheDir' => $this->getCacheDir() . '/templates', 'compileDir' => $this->getCacheDir() . '/templates', ], 'mail' => [ 'charset' => 'utf-8', ], 'httpcache' => [ 'enabled' => true, 'lookup_optimization' => true, 'debug' => false, 'default_ttl' => 0, 'private_headers' => ['Authorization', 'Cookie'], 'allow_reload' => false, 'allow_revalidate' => false, 'stale_while_revalidate' => 2, 'stale_if_error' => false, 'cache_dir' => $this->getCacheDir() . '/html', 'cache_cookies' => ['shop', 'currency', 'x-cache-context-hash'], ], 'session' => [ 'cookie_lifetime' => 0, 'cookie_httponly' => 1, 'gc_probability' => 1, 'gc_divisor' => 200, 'save_handler' => 'db', 'use_trans_sid' => 0, 'locking' => true, ], 'phpsettings' => [ 'error_reporting' => E_ALL & ~E_USER_DEPRECATED, 'display_errors' => 0, 'date.timezone' => 'Europe/Berlin', ], 'cache' => [ 'frontendOptions' => [ 'automatic_serialization' => true, 'automatic_cleaning_factor' => 0, 'lifetime' => 3600, 'cache_id_prefix' => md5($this->getCacheDir()), ], 'backend' => 'auto', // e.G auto, apcu, xcache 'backendOptions' => [ 'hashed_directory_perm' => 0777 & ~umask(), 'cache_file_perm' => 0666 & ~umask(), 'hashed_directory_level' => 3, 'cache_dir' => $this->getCacheDir() . '/general', 'file_name_prefix' => 'shopware', ], ], 'hook' => [ 'proxyDir' => $this->getCacheDir() . '/proxies', 'proxyNamespace' => $this->App() . '_Proxies', ], 'model' => [ 'autoGenerateProxyClasses' => false, 'attributeDir' => $this->getCacheDir() . '/doctrine/attributes', 'proxyDir' => $this->getCacheDir() . '/doctrine/proxies', 'proxyNamespace' => $this->App() . '\Proxies', 'cacheProvider' => 'auto', // supports null, auto, Apcu, Array, Wincache and Xcache 'cacheNamespace' => null, // custom namespace for doctrine cache provider (optional; null = auto-generated namespace) ], 'backendsession' => [ 'name' => 'SHOPWAREBACKEND', 'cookie_lifetime' => 0, 'cookie_httponly' => 1, 'use_trans_sid' => 0, 'locking' => false, ], ], $customConfig);
JonidBendo/shopware
engine/Shopware/Configs/Default.php
PHP
agpl-3.0
6,707
<?php $CI = & get_instance(); ?> <?php $permissions = $auth->getPermissionType(); $clsWidth = 50; foreach ($this->colsCustom as $k => $v) { if ($k == 'action') { $matches = array(); preg_match_all('/<a[^>]*>([^<]*)<\/a>/iU', $this->colsCustom['action'], $matches); if (!in_array(2, $permissions)) { unset($matches[0][1]); } if (!in_array(3, $permissions)) { unset($matches[0][2]); } $clsWidth = $clsWidth* count($matches[0]); $this->colsCustom[$k] = implode(' ', $matches[0]); } } foreach ($this->colsWidth as $k => $v) { if ($k == 'action') { $this->colsWidth[$k] = $clsWidth; } } ?> <?php if (!empty($this->form)) { ?> </div> <div style="height: 52px;"> <div data-spy="affix" data-offset-top="94" style=" top: 54px; width: 100%; padding-top:5px; padding-bottom:5px; z-index: 100;"> <div class="container" style="border-bottom: 1px solid #CCC; padding-bottom:5px;padding-top:5px;"> <div style="text-align:right;width:100%;"> <div class="btn-group"> <a class="btn" onclick="searchModal();"><i class="icon-search"></i> Search</a> <?php $q = $this->queryString; if (isset($q['xtype'])) unset($q['xtype']); ?> <a class="btn" href="?<?php echo http_build_query($q, '', '&'); ?>"><i class="icon-remove-sign"></i></a> </div> <?php if (!empty($this->results)) { ?> <a class="btn" onclick="crudExport();"><i class="icon-download"></i> Export CSV</a> <?php } else { ?> <a class="btn disabled"><i class="icon-download"></i> Export CSV</a> <?php } ?> <a class="btn" onclick="crudExportAll();"><i class="icon-download"></i> Export CSV (All)</a> <?php if (in_array(1, $permissions)) { ?> <a type="button" class="btn btn-info" onclick="newRecord();"> <i class="icon-plus icon-white"></i> Add</a> <?php } ?> </div> </div> </div> </div> <div class="container"> <?php } ?> <div class='<?php echo $this->conf['color']; ?>'> <?php $q = $this->queryString; $q['src']['p'] = 1; $q['xtype'] = 'index'; if (isset($q['xid'])) unset($q['xid']); ?> <form method="post" action="?<?php echo http_build_query($q, '', '&'); ?>" id="table" class="form-horizontal"> <?php //require dirname(__FILE__) . '/search_form.php'; ?> <input type="hidden" name="src[page]" id="srcPage" value="<?php echo $this->pageIndex; ?>"/> <input type="hidden" name="src[limit]" id="srcLimit" value="<?php echo $this->limit; ?>"/> <input type="hidden" name="src[order_field]" id="srcOrder_field" value="<?php echo $this->orderField; ?>"/> <input type="hidden" name="src[order_type]" id="srcOrder_type" value="<?php echo $this->orderType; ?>"/> <?php require dirname(__FILE__) . '/paginate.php'; ?> <div style="overflow: auto;"> <table class="table table-bordered table-hover list table-condensed"> <thead> <tr> <?php foreach ($fields as $k => $field) { ?> <?php if (in_array($field, $this->fields)) { ?> <th onclick="order('<?php echo ($field) ?>');" style="cursor:pointer; text-align:center; color:#333333;text-shadow: 0 1px 0 #FFFFFF; background-color: #e6e6e6; <?php if (isset($this->colsWidth[$field])) { ?>width:<?php echo $this->colsWidth[$field]; ?>px; <?php } else if (isset($this->colsWidth[$k])) { ?>width:<?php echo $this->colsWidth[$k]; ?>px; <?php } ?>"> <?php echo htmlspecialchars((isset($this->fieldsAlias[$field])) ? $this->fieldsAlias[$field] : $field); ?> <?php if ($this->orderField == $field) { ?> <i class="arrow <?php echo $this->orderType; ?>"></i> <?php } ?> </th> <?php } else { ?> <th style="cursor:default; text-align:center; color:#333333;text-shadow: 0 1px 0 #FFFFFF; background-color: #e6e6e6; <?php if (isset($this->colsWidth[$field])) { ?>width:<?php echo $this->colsWidth[$field]; ?>px; <?php } else if (isset($this->colsWidth[$k])) { ?>width:<?php echo $this->colsWidth[$k]; ?>px; <?php } ?>"> <?php echo htmlspecialchars((isset($this->fieldsAlias[$field])) ? $this->fieldsAlias[$field] : $field); ?> </th> <?php } ?> <?php } ?> </tr> </thead> <tbody> <?php if (!empty($this->results)) { $s = array(); foreach ($this->fields as $field) { $s[] = '{' . $field . '}'; } $s[] = '{ppri}'; $s[] = '{no}'; $offset = ($this->pageIndex - 1) * $this->limit; ?> <?php foreach ($this->results as $result) { $r = array(); foreach ($this->fields as $k => $field) { $__value = ''; $__aryField = explode('.', $field); if (count($__aryField) > 1) { $__tmp = $result; foreach ($__aryField as $key => $value) { if (is_array($__tmp[$value])) { $__tmp = $__tmp[$value]; } else { $__value = $__tmp[$value]; } } } else if (count($__aryField) == 1) { $__value = $result[$field]; } if (isset($this->form[$field]) && isset($this->form[$field]['element'][0])) { switch (trim(strtolower($this->form[$field]['element'][0]))) { case 'radio': case 'autocomplete': case 'select': $e = $this->form[$field]['element']; $options = array(); $params = array(); if (isset($e[1]) && !empty($e[1])) { if (array_key_exists('option_table', $e[1])) { if (array_key_exists('option_key', $e[1]) && array_key_exists('option_value', $e[1])) { $_dao = new ScrudDao($e[1]['option_table'], $CI->db); $params['fields'] = array($e[1]['option_key'], $e[1]['option_value']); $rs = $_dao->find($params); if (!empty($rs)) { foreach ($rs as $v) { $options[$v[$e[1]['option_key']]] = $v[$e[1]['option_value']]; } } } } else { $options = $e[1]; } } $this->form[$field]['element'][1] = $options; if (isset($this->form[$field]['element'][1]) && !empty($this->form[$field]['element'][1]) && is_array($this->form[$field]['element'][1]) && !empty($this->form[$field]['element'][1][$__value]) ) { $r[] = htmlspecialchars($this->form[$field]['element'][1][$__value]); } else { $r[] = ''; } break; case 'editor': $r[] = $__value; break; case 'checkbox': $value = explode(',', $__value); if (!empty($value) && is_array($value) && count($value) > 0) { $tmp = array(); foreach ($value as $k1 => $v1) { if (isset($this->form[$field]['element'][1][$v1])) { $tmp[] = $this->form[$field]['element'][1][$v1]; } } $value = implode(', ', $tmp); } else { $value = ''; } $r[] = htmlspecialchars($value); break; case 'textarea': $r[] = nl2br(htmlspecialchars($__value)); break; default: $r[] = htmlspecialchars($__value); break; } } else { $r[] = htmlspecialchars($__value); } } $offset++; $ppri = ""; $_tmp = ""; foreach ($this->primaryKey as $f) { $__value = ''; $__aryField = explode('.', $f); if (count($__aryField) > 1) { $__tmp = $result; foreach ($__aryField as $key => $value) { if (is_array($__tmp[$value])) { $__tmp = $__tmp[$value]; } else { $__value = $__tmp[$value]; } } } else if (count($__aryField) == 1) { $__value = $result[$f]; } $ppri .= $_tmp . 'key[' . $f . ']=' . htmlspecialchars($__value); $_tmp = '&'; } $r[] = $ppri; $r[] = $offset; ?> <tr> <?php foreach ($fields as $field) { ?> <td style="<?php if (isset($this->colsAlign[$field])) { ?>text-align:<?php echo $this->colsAlign[$field]; ?>;<?php } ?>"> <?php if (isset($this->colsCustom[$field])) { ?> <?php echo str_replace($s, $r, $this->colsCustom[$field]); ?> <?php } else { ?> <?php $__value = ''; $__aryField = explode('.', $field); if (count($__aryField) > 1) { $__tmp = $result; foreach ($__aryField as $key => $value) { if (is_array($__tmp[$value])) { $__tmp = $__tmp[$value]; } else { $__value = $__tmp[$value]; } } } else if (count($__aryField) == 1) { $__value = $result[$field]; } if (isset($this->form[$field]) && isset($this->form[$field]['element'][0])) { switch (trim(strtolower($this->form[$field]['element'][0]))) { case 'radio': case 'autocomplete': case 'select': $e = $this->form[$field]['element']; $options = array(); $params = array(); if (isset($e[1]) && !empty($e[1])) { if (array_key_exists('option_table', $e[1])) { if (array_key_exists('option_key', $e[1]) && array_key_exists('option_value', $e[1])) { $_dao = new ScrudDao($e[1]['option_table'], $CI->db); $params['fields'] = array($e[1]['option_key'], $e[1]['option_value']); $rs = $_dao->find($params); if (!empty($rs)) { $rs = $rs[$e[1]['option_table']]; foreach ($rs as $v) { $options[$v[$e[1]['option_key']]] = $v[$e[1]['option_value']]; } } } } else { $options = $e[1]; } } $this->form[$field]['element'][1] = $options; if (isset($e[2]) && array_key_exists('multiple', $e[2]) && !is_array($__value)){ $tmp = explode(',', $__value); $__value = array(); foreach ($tmp as $mv){ if (!empty($mv)){ $__value[] = $mv; } } } if (!is_array($__value)){ if (isset($this->form[$field]['element'][1]) && !empty($this->form[$field]['element'][1]) && is_array($this->form[$field]['element'][1]) && !empty($this->form[$field]['element'][1][$__value])) { echo nl2br(htmlspecialchars($this->form[$field]['element'][1][$__value])); } }else{ $sp = ''; foreach ($__value as $vv){ if (isset($this->form[$field]['element'][1]) && !empty($this->form[$field]['element'][1]) && is_array($this->form[$field]['element'][1]) && !empty($this->form[$field]['element'][1][$vv])) { echo $sp.nl2br(htmlspecialchars($this->form[$field]['element'][1][$vv])); $sp = ','; } } } break; case 'editor': echo $__value; break; case 'checkbox': $value = explode(',', $__value); if (!empty($value) && is_array($value) && count($value) > 0) { $tmp = array(); foreach ($value as $k1 => $v1) { if (isset($this->form[$field]['element'][1][$v1])) { $tmp[] = $this->form[$field]['element'][1][$v1]; } } $value = implode(', ', $tmp); } else { $value = ''; } echo htmlspecialchars($value); break; case 'textarea': echo nl2br(htmlspecialchars($__value)); break; case 'file': if (file_exists(FCPATH . '/media/files/' . $__value)) { echo '<a href="' . base_url() . 'index.php/admin/download?file=' . $__value . '">' . $__value . '</a>'; } else { echo $__value; } break; case 'image': if (file_exists(__IMAGE_UPLOAD_REAL_PATH__ . 'thumbnail_' . $__value)) { echo "<img src='" . __MEDIA_PATH__ . "images/thumbnail_" . $__value . "' />"; } else if (file_exists(__IMAGE_UPLOAD_REAL_PATH__ . 'mini_thumbnail_' . $__value)) { echo "<img src='" . __MEDIA_PATH__ . "images/mini_thumbnail_" . $__value . "' />"; } else { echo ''; } break; default: echo nl2br(htmlspecialchars($__value)); break; } } else { echo nl2br(htmlspecialchars($__value)); } ?> <?php } ?> </td> <?php } ?> </tr> <?php } ?> <?php } else { ?> <tr> <td colspan="<?php echo count($fields); ?>">No results found.</td> </tr> <?php } ?> </tbody> </table> </div> <?php require dirname(__FILE__) . '/paginate.php'; ?> </form> </div> <iframe src="" id="crudIframe" height="0" width="0" style="width: 0px; height: 0px; border: 0px; padding: 0px; margin: 0px;"></iframe> <script> function crudSearch(){ document.getElementById('srcPage').value = 1; document.getElementById('table').submit(); } function crudExport(){ $('#crudIframe').attr({src:'<?php echo base_url(); ?>index.php/admin/scrud/exportcsv?table=<?php echo $this->table; ?>&xtype=exportcsv'}); } function crudExportAll() { $('#crudIframe').attr({src: '<?php echo base_url(); ?>index.php/admin/scrud/exportcsv?table=<?php echo $this->table; ?>&xtype=exportcsvall'}); } </script> <script> function searchModal() { $.sModal({ header:'Search box', animate: 'fadeDown', content:'<div id="scrud_model_search"><center><img src="<?php echo base_url(); ?>media/icons/loading.gif" /></center></div>', onShow: function(id){ <?php $q = $this->queryString; $q['xtype'] = 'modalform'; if (isset($q['key'])) unset($q['key']); ?> $('#' + id).find('#scrud_model_search').load('?<?php echo http_build_query($q, '', '&'); ?>'); setTimeout(function(){ $('#' + id).removeClass('fadeInDown'); },1000); }, buttons: [ { text: ' <i class="icon-search icon-white"></i> Search ', addClass: 'btn-primary', click: function(id, data) { crudSearch(); $.sModal('close', id); } }, { text: ' Cancel ', click: function(id, data) { $.sModal('close', id); } } ] }); } function newRecord(){ <?php $q = $this->queryString; $q['xtype'] = 'form'; if (isset($q['key'])) unset($q['key']); ?> window.location = "?<?php echo http_build_query($q, '', '&'); ?>"; } function __view(id){ <?php $q = $this->queryString; $q['xtype'] = 'view'; if (isset($q['key'])) unset($q['key']); ?> window.location = "?<?php echo http_build_query($q, '', '&'); ?>&"+id; } function __edit(id){ <?php $q = $this->queryString; $q['xtype'] = 'form'; if (isset($q['key'])) unset($q['key']); ?> window.location = "?<?php echo http_build_query($q, '', '&'); ?>&"+id; } function __delete(id){ <?php $q = $this->queryString; $q['xtype'] = 'delconfirm'; if (isset($q['key'])) unset($q['key']); ?> window.location = "?<?php echo http_build_query($q, '', '&'); ?>&"+id; } function order(field){ var oldField = document.getElementById('srcOrder_field').value; var oldType = document.getElementById('srcOrder_type').value; <?php $q = $this->queryString; $q['xtype'] = 'index'; if (isset($q['key'])) unset($q['key']); if (isset($q['src']['o'])) unset($q['src']['o']); if (isset($q['src']['t'])) unset($q['src']['t']); ?> var url = "?<?php echo http_build_query($q, '', '&'); ?>"; url += "&src[o]="+field; if (field == oldField){ if (oldType == 'asc'){ url += "&src[t]=desc" }else{ url += "&src[t]=asc" } }else{ url += "&src[t]=asc" } window.location = url; } $(document).ready(function(){ $('title').html('<?php echo $this->title; ?>'); //$('table > tbody > tr').each(function(){ //$($(this).find('td:last > input').get(0)).hide(); //$($(this).find('td:last > input').get(1)).hide(); //$($(this).find('td:last > input').get(2)).hide(); //}); }); </script>
nin9creative/magrocket-backend
source/application/third_party/scrud/templates/index.php
PHP
agpl-3.0
26,148
'use strict'; var minilog = require('minilog') , log = minilog('traverson') , abortTraversal = require('./abort_traversal') , applyTransforms = require('./transforms/apply_transforms') , httpRequests = require('./http_requests') , isContinuation = require('./is_continuation') , walker = require('./walker'); var checkHttpStatus = require('./transforms/check_http_status') , continuationToDoc = require('./transforms/continuation_to_doc') , continuationToResponse = require('./transforms/continuation_to_response') , convertEmbeddedDocToResponse = require('./transforms/convert_embedded_doc_to_response') , extractDoc = require('./transforms/extract_doc') , extractResponse = require('./transforms/extract_response') , extractUrl = require('./transforms/extract_url') , fetchLastResource = require('./transforms/fetch_last_resource') , executeLastHttpRequest = require('./transforms/execute_last_http_request') , executeHttpRequest = require('./transforms/execute_http_request') , parse = require('./transforms/parse') , parseLinkHeader = require('./transforms/parse_link_header'); /** * Starts the link traversal process and end it with an HTTP get. */ exports.get = function(t, callback) { var transformsAfterLastStep; if (t.convertResponseToObject) { transformsAfterLastStep = [ continuationToDoc, fetchLastResource, checkHttpStatus, parse, parseLinkHeader, extractDoc, ]; } else { transformsAfterLastStep = [ continuationToResponse, fetchLastResource, convertEmbeddedDocToResponse, extractResponse, ]; } walker.walk(t, transformsAfterLastStep, callback); return createTraversalHandle(t); }; /** * Special variant of get() that does not execute the last request but instead * yields the last URL to the callback. */ exports.getUrl = function(t, callback) { walker.walk(t, [ extractUrl ], callback); return createTraversalHandle(t); }; /** * Starts the link traversal process and sends an HTTP POST request with the * given body to the last URL. Passes the HTTP response of the POST request to * the callback. */ exports.post = function(t, callback) { walkAndExecute(t, t.requestModuleInstance, t.requestModuleInstance.post, callback); return createTraversalHandle(t); }; /** * Starts the link traversal process and sends an HTTP PUT request with the * given body to the last URL. Passes the HTTP response of the PUT request to * the callback. */ exports.put = function(t, callback) { walkAndExecute(t, t.requestModuleInstance, t.requestModuleInstance.put, callback); return createTraversalHandle(t); }; /** * Starts the link traversal process and sends an HTTP PATCH request with the * given body to the last URL. Passes the HTTP response of the PATCH request to * the callback. */ exports.patch = function(t, callback) { walkAndExecute(t, t.requestModuleInstance, t.requestModuleInstance.patch, callback); return createTraversalHandle(t); }; /** * Starts the link traversal process and sends an HTTP DELETE request to the * last URL. Passes the HTTP response of the DELETE request to the callback. */ exports.delete = function(t, callback) { walkAndExecute(t, t.requestModuleInstance, t.requestModuleInstance.del, callback); return createTraversalHandle(t); }; function walkAndExecute(t, request, method, callback) { var transformsAfterLastStep; if (t.convertResponseToObject) { transformsAfterLastStep = [ executeHttpRequest, checkHttpStatus, parse, parseLinkHeader, extractDoc, ]; } else { transformsAfterLastStep = [ executeLastHttpRequest, ]; } t.lastMethod = method; walker.walk(t, transformsAfterLastStep, callback); } function createTraversalHandle(t) { return { abort: t.abortTraversal }; }
cgi-eoss/fstep
fs-tep-portal/src/main/resources/app/scripts/vendor/traverson/lib/actions.js
JavaScript
agpl-3.0
3,942
// Copyright (c) 2015-2021 MinIO, Inc. // // This file is part of MinIO Object Storage stack // // 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 cmd import ( "context" "strings" "time" "github.com/fatih/color" "github.com/minio/cli" "github.com/minio/mc/pkg/probe" minio "github.com/minio/minio-go/v7" "github.com/minio/pkg/console" ) var retentionSetFlags = []cli.Flag{ cli.BoolFlag{ Name: "recursive, r", Usage: "apply retention recursively", }, cli.BoolFlag{ Name: "bypass", Usage: "bypass governance", }, cli.StringFlag{ Name: "version-id, vid", Usage: "apply retention to a specific object version", }, cli.StringFlag{ Name: "rewind", Usage: "roll back object(s) to current version at specified time", }, cli.BoolFlag{ Name: "versions", Usage: "apply retention object(s) and all its versions", }, cli.BoolFlag{ Name: "default", Usage: "set bucket default retention mode", }, } var retentionSetCmd = cli.Command{ Name: "set", Usage: "set retention for object(s)", Action: mainRetentionSet, OnUsageError: onUsageError, Before: setGlobalsFromContext, Flags: append(retentionSetFlags, globalFlags...), CustomHelpTemplate: `NAME: {{.HelpName}} - {{.Usage}} USAGE: {{.HelpName}} [FLAGS] [governance | compliance] VALIDITY TARGET FLAGS: {{range .VisibleFlags}}{{.}} {{end}} VALIDITY: This argument must be formatted like Nd or Ny where 'd' denotes days and 'y' denotes years e.g. 10d, 3y. EXAMPLES: 1. Set object retention for a specific object $ {{.HelpName}} compliance 30d myminio/mybucket/prefix/obj.csv 2. Set object retention for recursively for all objects at a given prefix $ {{.HelpName}} governance 30d myminio/mybucket/prefix --recursive 3. Set object retention to a specific version of a specific object $ {{.HelpName}} governance 30d myminio/mybucket/prefix/obj.csv --version-id "3Jr2x6fqlBUsVzbvPihBO3HgNpgZgAnp" 4. Set object retention for recursively for all versions of all objects $ {{.HelpName}} governance 30d myminio/mybucket/prefix --recursive --versions 5. Set default lock retention configuration for a bucket $ {{.HelpName}} --default governance 30d myminio/mybucket/ `, } func parseSetRetentionArgs(cliCtx *cli.Context) (target, versionID string, recursive bool, timeRef time.Time, withVersions bool, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, bypass, bucketMode bool) { args := cliCtx.Args() if len(args) != 3 { cli.ShowCommandHelpAndExit(cliCtx, "set", 1) } mode = minio.RetentionMode(strings.ToUpper(args[0])) if !mode.IsValid() { fatalIf(errInvalidArgument().Trace(args...), "invalid retention mode '%v'", mode) } var err *probe.Error validity, unit, err = parseRetentionValidity(args[1]) fatalIf(err.Trace(args[1]), "invalid validity argument") target = args[2] if target == "" { fatalIf(errInvalidArgument().Trace(), "invalid target url '%v'", target) } versionID = cliCtx.String("version-id") timeRef = parseRewindFlag(cliCtx.String("rewind")) withVersions = cliCtx.Bool("versions") recursive = cliCtx.Bool("recursive") bypass = cliCtx.Bool("bypass") bucketMode = cliCtx.Bool("default") if bucketMode && (versionID != "" || !timeRef.IsZero() || withVersions || recursive || bypass) { fatalIf(errDummy(), "--default cannot be specified with any of --version-id, --rewind, --versions, --recursive, --bypass.") } return } // Set Retention for one object/version or many objects within a given prefix. func setRetention(ctx context.Context, target, versionID string, timeRef time.Time, withOlderVersions, isRecursive bool, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, bypassGovernance bool) error { return applyRetention(ctx, lockOpSet, target, versionID, timeRef, withOlderVersions, isRecursive, mode, validity, unit, bypassGovernance) } func setBucketLock(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) error { return applyBucketLock(lockOpSet, urlStr, mode, validity, unit) } // main for retention set command. func mainRetentionSet(cliCtx *cli.Context) error { ctx, cancelSetRetention := context.WithCancel(globalContext) defer cancelSetRetention() console.SetColor("RetentionSuccess", color.New(color.FgGreen, color.Bold)) console.SetColor("RetentionFailure", color.New(color.FgYellow)) target, versionID, recursive, rewind, withVersions, mode, validity, unit, bypass, bucketMode := parseSetRetentionArgs(cliCtx) checkObjectLockSupport(ctx, target) if bucketMode { return setBucketLock(target, mode, validity, unit) } if withVersions && rewind.IsZero() { rewind = time.Now().UTC() } return setRetention(ctx, target, versionID, rewind, withVersions, recursive, mode, validity, unit, bypass) }
krisis/mc
cmd/retention-set.go
GO
agpl-3.0
5,444
<?php /** The goal of the Open Affiliate Report Aggregator (OARA) is to develop a set of PHP classes that can download affiliate reports from a number of affiliate networks, and store the data in a common format. Copyright (C) 2014 Fubra 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 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/>. Contact ------------ Fubra Limited <support@fubra.com> , +44 (0)1252 367 200 **/ /** * Export Class * * @author Carlos Morillo Merino * @category Oara_Network_Publisher_PayMode * @copyright Fubra Limited * @version Release: 01.00 * */ class Oara_Network_Publisher_PayMode extends Oara_Network { /** * Export Transaction Parameters * @var array */ private $_exportTransactionParameters = null; /** * Export Payment Parameters * @var array */ private $_exportPaymentParameters = null; /** * * Payment Transactions Parameters * @var unknown_type */ private $_exportPaymentTransactionParameters = null; /** * Client * @var unknown_type */ private $_client = null; /** * AgentNumber * @var unknown_type */ private $_agent = null; /** * Constructor and Login * @param $credentials * @return Oara_Network_Publisher_Daisycon */ public function __construct($credentials) { $user = $credentials['user']; $password = $credentials['password']; $valuesLogin = array( new Oara_Curl_Parameter('username', $user), new Oara_Curl_Parameter('password', $password), new Oara_Curl_Parameter('Enter', 'Enter') ); $loginUrl = 'https://secure.paymode.com/paymode/do-login.jsp?'; $this->_client = new Oara_Curl_Access($loginUrl, $valuesLogin, $credentials); $this->_exportTransactionParameters = array(new Oara_Curl_Parameter('isDetailReport', 'true'), new Oara_Curl_Parameter('method', 'ALL'), new Oara_Curl_Parameter('currency', 'ALL_CURRENCIES'), new Oara_Curl_Parameter('amount', ''), new Oara_Curl_Parameter('disburserName', ''), new Oara_Curl_Parameter('remitType', 'CAR'), new Oara_Curl_Parameter('CAR_customerName', ''), new Oara_Curl_Parameter('CAR_confirmationNumber', ''), new Oara_Curl_Parameter('CAR_franchiseNumber', ''), new Oara_Curl_Parameter('CAR_remitStartDate', ''), new Oara_Curl_Parameter('CAR_remitEndDate', ''), new Oara_Curl_Parameter('CAR_rentalLocation', ''), new Oara_Curl_Parameter('CAR_agreementNumber', ''), new Oara_Curl_Parameter('CAR_commissionAmount', ''), new Oara_Curl_Parameter('CAR_sortBy', 'CUSTOMER_NAME'), new Oara_Curl_Parameter('submit1', 'Submit'), new Oara_Curl_Parameter('AIR_customerName', ''), new Oara_Curl_Parameter('AIR_confirmationNumber', ''), new Oara_Curl_Parameter('AIR_agreementNumber', ''), new Oara_Curl_Parameter('AIR_issueDate', ''), new Oara_Curl_Parameter('AIR_sortBy', 'CUSTOMER_NAME'), new Oara_Curl_Parameter('CRUISE_vesselName', ''), new Oara_Curl_Parameter('CRUISE_customerName', ''), new Oara_Curl_Parameter('CRUISE_confirmationNumber', ''), new Oara_Curl_Parameter('CRUISE_remitStartDate', ''), new Oara_Curl_Parameter('CRUISE_duration', ''), new Oara_Curl_Parameter('CRUISE_commissionAmount', ''), new Oara_Curl_Parameter('CRUISE_sortBy', 'FACILITY_NAME'), new Oara_Curl_Parameter('HOTEL_hotelName', ''), new Oara_Curl_Parameter('HOTEL_customerName', ''), new Oara_Curl_Parameter('HOTEL_confirmationNumber', ''), new Oara_Curl_Parameter('HOTEL_remitStartDate', ''), new Oara_Curl_Parameter('HOTEL_duration', ''), new Oara_Curl_Parameter('HOTEL_commissionAmount', ''), new Oara_Curl_Parameter('HOTEL_sortBy', 'FACILITY_NAME') ); $this->_exportPaymentParameters = array( new Oara_Curl_Parameter('isDetailReport', 'false'), new Oara_Curl_Parameter('method', 'ALL'), new Oara_Curl_Parameter('currency', 'ALL_CURRENCIES'), new Oara_Curl_Parameter('amount', ''), new Oara_Curl_Parameter('disburserName', ''), new Oara_Curl_Parameter('submit1', 'Submit') ); $this->_exportPaymentTransactionParameters = array( new Oara_Curl_Parameter('fromNonMigrated', 'false'), new Oara_Curl_Parameter('returnPage', ''), new Oara_Curl_Parameter('mode', ''), new Oara_Curl_Parameter('siteid', ''), new Oara_Curl_Parameter('ssid', '') ); } /** * Check the connection */ public function checkConnection() { //If not login properly the construct launch an exception $connection = false; $urls = array(); $urls[] = new Oara_Curl_Request('https://secure.paymode.com/paymode/home.jsp?', array()); $exportReport = $this->_client->get($urls); if (preg_match('/paymode\/logout\.jsp/', $exportReport[0], $matches)) { $urls = array(); $urls[] = new Oara_Curl_Request('https://secure.paymode.com/paymode/reports-pre_commission_history.jsp?', array()); $exportReport = $this->_client->get($urls); $dom = new Zend_Dom_Query($exportReport[0]); $results = $dom->query('input[type="checkbox"]'); $agentNumber = array(); foreach ($results as $result) { $agentNumber[] = $result->getAttribute("id"); } $this->_agentNumber = $agentNumber; $connection = true; } return $connection; } /** * (non-PHPdoc) * @see library/Oara/Network/Oara_Network_Publisher_Interface#getMerchantList() */ public function getMerchantList() { $merchants = array(); $obj = array(); $obj['cid'] = 1; $obj['name'] = "Sixt"; $merchants[] = $obj; return $merchants; } /** * (non-PHPdoc) * @see library/Oara/Network/Oara_Network_Publisher_Interface#getTransactionList($aMerchantIds, $dStartDate, $dEndDate, $sTransactionStatus) */ public function getTransactionList($merchantList = null, Zend_Date $dStartDate = null, Zend_Date $dEndDate = null, $merchantMap = null) { $totalTransactions = array(); $filter = new Zend_Filter_LocalizedToNormalized(array('precision' => 2)); $valuesFromExport = array(); $urls = array(); $urls[] = new Oara_Curl_Request('https://secure.paymode.com/paymode/reports-baiv2.jsp?', array()); $exportReport = $this->_client->get($urls); $dom = new Zend_Dom_Query($exportReport[0]); $results = $dom->query('input[type="hidden"]'); foreach ($results as $hidden) { $name = $hidden->getAttribute("name"); $value = $hidden->getAttribute("value"); $valuesFromExport[] = new Oara_Curl_Parameter($name, $value); } $valuesFromExport[] = new Oara_Curl_Parameter('dataSource', '1'); $valuesFromExport[] = new Oara_Curl_Parameter('RA:reports-baiv2.jspCHOOSE', '620541800'); $valuesFromExport[] = new Oara_Curl_Parameter('reportFormat', 'csv'); $valuesFromExport[] = new Oara_Curl_Parameter('includeCurrencyCodeColumn', 'on'); $valuesFromExport[] = new Oara_Curl_Parameter('remitTypeCode', ''); $valuesFromExport[] = new Oara_Curl_Parameter('PAYMENT_CURRENCY_TYPE', 'CREDIT'); $valuesFromExport[] = new Oara_Curl_Parameter('PAYMENT_CURRENCY_TYPE', 'INSTRUCTION'); $valuesFromExport[] = new Oara_Curl_Parameter('subSiteExtID', ''); $valuesFromExport[] = new Oara_Curl_Parameter('ediProvider835Version', '5010'); $valuesFromExport[] = new Oara_Curl_Parameter('tooManyRowsCheck', 'true'); $urls = array(); $dateList = Oara_Utilities::daysOfDifference($dStartDate, $dEndDate); foreach ($dateList as $date) { $valuesFromExportTemp = Oara_Utilities::cloneArray($valuesFromExport); $valuesFromExportTemp[] = new Oara_Curl_Parameter('date', $date->toString("MM/dd/yyyy")); $urls[] = new Oara_Curl_Request('https://secure.paymode.com/paymode/reports-do_csv.jsp?closeJQS=true?', $valuesFromExportTemp); } $exportReport = $this->_client->get($urls); $transactionCounter = 0; $valueCounter = 0; $commissionCounter = 0; $j = 0; foreach ($exportReport as $report){ $reportParameters = $urls[$j]->getParameters(); $reportDate = $reportParameters[count($reportParameters) -1]->getValue(); $transactionDate = new Zend_Date($reportDate, 'MM/dd/yyyy', 'en'); if (!preg_match("/logout.jsp/", $report)){ $exportReportData = str_getcsv($report, "\n"); $num = count($exportReportData); for ($i = 1; $i < $num; $i++) { $transactionArray = str_getcsv($exportReportData[$i], ","); if (count($transactionArray) == 30 && $transactionArray[0] == 'D' && $transactionArray[1] == null){ $transactionCounter++; $valueCounter += $filter->filter($transactionArray[24]); $commissionCounter += $filter->filter($transactionArray[28]); } } } $j++; } if ($transactionCounter > 0){ for ($i = 0; $i < count($dateList); $i++){ $transaction = array(); $transaction['merchantId'] = 1; $transaction['status'] = Oara_Utilities::STATUS_PAID; $transaction['date'] = $dateList[$i]->toString("yyyy-MM-dd HH:mm:ss"); $transaction['amount'] = $valueCounter/count($dateList); $transaction['commission'] = $commissionCounter/count($dateList); $totalTransactions[] = $transaction; } } return $totalTransactions; } /** * (non-PHPdoc) * @see Oara/Network/Oara_Network_Publisher_Base#getPaymentHistory() */ public function getPaymentHistory() { $paymentHistory = array(); $filter = new Zend_Filter_LocalizedToNormalized(array('precision' => 2)); $startDate = new Zend_Date("01-01-2012", "dd-MM-yyyy"); $endDate = new Zend_Date(); $dateList = Oara_Utilities::monthsOfDifference($startDate, $endDate); foreach ($dateList as $date) { $monthStartDate = clone $date; $monthEndDate = null; $monthEndDate = clone $date; $monthEndDate->setDay(1); $monthEndDate->addMonth(1); $monthEndDate->subDay(1); $monthEndDate->setHour(23); $monthEndDate->setMinute(59); $monthEndDate->setSecond(59); $valuesFromExport = array(); $valuesFromExport[] = new Oara_Curl_Parameter('Begin_Date', $monthStartDate->toString("MM/dd/yyyy")); $valuesFromExport[] = new Oara_Curl_Parameter('End_Date', $monthEndDate->toString("MM/dd/yyyy")); $valuesFromExport[] = new Oara_Curl_Parameter('cd', "c"); $valuesFromExport[] = new Oara_Curl_Parameter('disb', "false"); $valuesFromExport[] = new Oara_Curl_Parameter('coll', "true"); $valuesFromExport[] = new Oara_Curl_Parameter('transactionID', ""); $valuesFromExport[] = new Oara_Curl_Parameter('Begin_DatePN', ""); $valuesFromExport[] = new Oara_Curl_Parameter('Begin_DateCN', ""); $valuesFromExport[] = new Oara_Curl_Parameter('End_DatePN', ""); $valuesFromExport[] = new Oara_Curl_Parameter('End_DateCN', ""); $valuesFromExport[] = new Oara_Curl_Parameter('disbAcctIDRef', ""); $valuesFromExport[] = new Oara_Curl_Parameter('checkNumberID', ""); $valuesFromExport[] = new Oara_Curl_Parameter('paymentNum', ""); $valuesFromExport[] = new Oara_Curl_Parameter('sel_type', "OTH"); $valuesFromExport[] = new Oara_Curl_Parameter('payStatusCat', "ALL_STATUSES"); $valuesFromExport[] = new Oara_Curl_Parameter('amount', ""); $valuesFromExport[] = new Oara_Curl_Parameter('aggregatedCreditAmount', ""); $valuesFromExport[] = new Oara_Curl_Parameter('disbSiteIDManual', ""); $valuesFromExport[] = new Oara_Curl_Parameter('collSiteIDManual', ""); $valuesFromExport[] = new Oara_Curl_Parameter('agencyid', ""); $valuesFromExport[] = new Oara_Curl_Parameter('collbankAccount', ""); $valuesFromExport[] = new Oara_Curl_Parameter('remitInvoice', ""); $valuesFromExport[] = new Oara_Curl_Parameter('remitAccount', ""); $valuesFromExport[] = new Oara_Curl_Parameter('remitCustAccount', ""); $valuesFromExport[] = new Oara_Curl_Parameter('remitCustName', ""); $valuesFromExport[] = new Oara_Curl_Parameter('remitVendorNumber', ""); $valuesFromExport[] = new Oara_Curl_Parameter('remitVendorName', ""); $urls = array(); $urls[] = new Oara_Curl_Request('https://secure.paymode.com/paymode/payment-DB-search.jsp?dataSource=1', $valuesFromExport); $exportReport = $this->_client->post($urls); if (!preg_match("/No payments were found/",$exportReport[0])){ $dom = new Zend_Dom_Query($exportReport[0]); $results = $dom->query('form[name="transform"] table'); if (count($results) > 0){ $tableCsv = self::htmlToCsv(self::DOMinnerHTML($results->current())); $payment = Array(); $paymentArray = str_getcsv($tableCsv[4], ";"); $payment['pid'] = $paymentArray[1]; $dateResult = $dom->query('form[name="collForm"] table'); if (count($dateResult) > 0){ $dateCsv = self::htmlToCsv(self::DOMinnerHTML($dateResult->current())); $dateArray = str_getcsv($dateCsv[2], ";"); $paymentDate = new Zend_Date($dateArray[1], 'dd-MMM-yyyy', 'en'); $payment['date'] = $paymentDate->toString("yyyy-MM-dd HH:mm:ss"); $paymentArray = str_getcsv($tableCsv[3], ";"); $payment['value'] = Oara_Utilities::parseDouble(preg_replace('/[^0-9\.,]/', "", $paymentArray[3])); $payment['method'] = "BACS"; $paymentHistory[] = $payment; } } else { $results = $dom->query('table[cellpadding="2"]'); foreach ($results as $table) { $tableCsv = self::htmlToCsv(self::DOMinnerHTML($table)); $num = count($tableCsv); for ($i = 1; $i < $num; $i++) { $payment = Array(); $paymentArray = str_getcsv($tableCsv[$i], ";"); $payment['pid'] = $paymentArray[0]; $paymentDate = new Zend_Date($paymentArray[3], 'MM/dd/yyyy', 'en'); $payment['date'] = $paymentDate->toString("yyyy-MM-dd HH:mm:ss"); $payment['value'] = Oara_Utilities::parseDouble($paymentArray[9]); $payment['method'] = "BACS"; $paymentHistory[] = $payment; } } } } } return $paymentHistory; } /** * * Function that returns the inner HTML code * @param unknown_type $element */ private function DOMinnerHTML($element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $tmp_dom = new DOMDocument(); $tmp_dom->appendChild($tmp_dom->importNode($child, true)); $innerHTML .= trim($tmp_dom->saveHTML()); } return $innerHTML; } /** * * Function that Convert from a table to Csv * @param unknown_type $html */ private function htmlToCsv($html) { $html = str_replace(array("\t", "\r", "\n"), "", $html); $csv = ""; $dom = new Zend_Dom_Query($html); $results = $dom->query('tr'); $count = count($results); // get number of matches: 4 foreach ($results as $result) { $tdList = $result->childNodes; $tdNumber = $tdList->length; if ($tdNumber > 0) { for ($i = 0; $i < $tdNumber; $i++) { $value = $tdList->item($i)->nodeValue; if ($i != $tdNumber - 1) { $csv .= trim($value).";"; } else { $csv .= trim($value); } } $csv .= "\n"; } } $exportData = str_getcsv($csv, "\n"); return $exportData; } }
actioussan/php-oara
Oara/Network/Publisher/PayMode.php
PHP
agpl-3.0
15,229
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PerlXmlLibxml(PerlPackage): """This module is an interface to libxml2, providing XML and HTML parsers with DOM, SAX and XMLReader interfaces, a large subset of DOM Layer 3 interface and a XML::XPath-like interface to XPath API of libxml2. The module is split into several packages which are not described in this section; unless stated otherwise, you only need to use XML::LibXML; in your programs.""" homepage = "https://metacpan.org/pod/XML::LibXML" url = "https://cpan.metacpan.org/authors/id/S/SH/SHLOMIF/XML-LibXML-2.0201.tar.gz" version('2.0201', sha256='e008700732502b3f1f0890696ec6e2dc70abf526cd710efd9ab7675cae199bc2') depends_on('libxml2') depends_on('perl-xml-namespacesupport', type=('build', 'run')) depends_on('perl-xml-sax', type=('build', 'run')) depends_on('perl-xml-sax-base', type=('build', 'run')) depends_on('perl-alien-libxml2', type='build')
iulian787/spack
var/spack/repos/builtin/packages/perl-xml-libxml/package.py
Python
lgpl-2.1
1,155
// BufferedReaderTest.java // submitted by Dalibor Topic <robilad@yahoo.com> import java.io.*; public class BufferedReaderTest { static class PseudoReader extends Reader { public void close() { } public int read(char buf[], int offset, int count) { System.out.println("count = " + count); return (count); } } static class PseudoReader2 extends Reader { public int closeCounter = 0; public void close() { closeCounter++; } public int read(char buf[], int offset, int count) { return (-1); } } static class PseudoReader3 extends Reader { boolean called; boolean calledAgain; public void close () { } /* This version of read returns a string of characters without EOL on the first call, then 0 characters on the second. If its caller is blocking, the caller will try again, otherwise it will have enough. If it tries again, and calls read for the third time, an IOException is thrown. */ public int read(char[] buf2, int offset, int count) throws IOException { if (calledAgain) { throw (new IOException("you keep trying ...")); } if (called) { calledAgain = true; return (0); } else { called = true; String s = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); s.getChars(0, count, buf2, offset); return (count); } } } public static void main(String [] args) throws Exception { // This test shows that the default buffersize for // a BufferedReader is 8192 characters. final int defaultsize = 8 * 1024; BufferedReader br = new BufferedReader(new PseudoReader()); try { // Mark br, to make sure the data is copied into // the buffer. br.mark(0); // This should call the read method of PseudoReader // only once if the default buffersize of // a buffered reader is 8192. br.read(new char[defaultsize], 0, defaultsize); // And now call it to get one character, and // it should refill its buffer br.read(new char[1], 0, 1); } catch (IOException e) { e.printStackTrace(); } // Let's try to set a mark with // a negative read ahead, // this should throw an IllegalArgumentException StringReader sr = new StringReader("sr"); br = new BufferedReader(sr); try { br.mark(-1); } catch (Exception e) { System.out.println(e.toString()); } // This is a simple test of BufferedReader // functionality. sr = new StringReader("1234567"); br = new BufferedReader(sr); try { char [] buf = new char[3]; if (br.read(buf) == 3) { System.out.println(buf); } else { System.out.println("Couldn't read 3 characters"); } br.mark(4); buf = new char[4]; if (br.read(buf) == 4) { System.out.println(buf); } else { System.out.println("Couldn't read 4 characters"); } br.reset(); if (br.read(buf) == 4) { System.out.println(buf); } else { System.out.println("Couldn't re-read 4 characters"); } } catch (IOException e) { e.printStackTrace(); } /* Trying to create a BufferedReader with input Reader = null should not result in an IllegalArgumentException being thrown, instead a NullPointerException should be thrown when the Reader is accessed. */ sr = new StringReader("1234567"); br = new BufferedReader(sr); try { br = new BufferedReader(null); } catch (NullPointerException e) { System.out.println(e.toString()); } try { br.read(); } catch (Exception e) { System.out.println(e.toString()); } sr = new StringReader("1234567"); /* Trying to create a BufferedReader with buffer size <= 0 should result in an IllegalArgumentException being thrown. */ try { br = new BufferedReader(sr, 0); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } /* A call to close a BufferedReader that has already been closed should do nothing. So the expected result should be "1" */ PseudoReader2 pr2 = new PseudoReader2(); br = new BufferedReader(pr2); try { br.close(); br.close(); } catch (IOException e) { System.out.println(e.toString()); } System.out.println(pr2.closeCounter); /* Trying to read from a BufferedReader that has already been closed should generate an IOException. */ try { br.close(); } catch (IOException e) { System.out.println(e.toString()); } try { br.mark(1); } catch (IOException e) { System.out.println(e.toString()); } try { br.read(); } catch (IOException e) { System.out.println(e.toString()); } try { br.read(new char[1]); } catch (IOException e) { System.out.println(e.toString()); } try { br.read(new char[1], 0, 1); } catch (IOException e) { System.out.println(e.toString()); } try { br.readLine(); } catch (IOException e) { System.out.println(e.toString()); } try { br.ready(); } catch (IOException e) { System.out.println(e.toString()); } try { br.reset(); } catch (IOException e) { System.out.println(e.toString()); } try { br.skip(1); } catch (IOException e) { System.out.println(e.toString()); } int bufferSize = 1000000; sr = new StringReader("a"); // Allocate a really huge buffer br = new BufferedReader(sr, bufferSize); /* A closed BufferReader should free its buffer */ // close buffered reader try { long before = Runtime.getRuntime().freeMemory(); br.close(); // Call garbage collector and hope he does his work System.gc(); long after = Runtime.getRuntime().freeMemory(); // System.out.println(before + " " + after); // If garbage collector was successful, and close() did // let go the buffer, we expect to see some dramatic // change in the amount of free memory. if (after - before >= bufferSize) { // System.out.println("SUCCESS"); } else { // System.out.println("FAILURE"); } } catch (IOException e) { e.printStackTrace(); } /* Test to see what happens when we try to skip a negative number of characters */ sr = new StringReader("0123456789"); br = new BufferedReader(sr,1); try { System.out.println(br.skip(5)); System.out.println(br.skip(-5)); System.out.println((char) br.read()); } catch (Exception e) { System.out.println(e.toString()); } /* Testing the reset method */ sr = new StringReader("ABCDEFGH"); br = new BufferedReader(sr,1); /* Trying to reset an unmarked reader should result in an Exception being thrown */ System.out.println("Reset unmarked"); try { br.reset(); } catch (Exception e) { System.out.println(e.toString()); } /* Now we try something slightly different. We try to invalidate the mark by reading further than the read ahead value passed as the parameter when mark was called. If we try to reset the buffer afterwards, we should receive a nice Exception. */ System.out.println("Reset invalidated"); try { br.mark(1); System.out.println(br.read()); System.out.println(br.read()); br.reset(); } catch (Exception e) { System.out.println(e.toString()); } // let's see what happens when I skip over // marked read ahead buffer. System.out.println("Skipping over marked buffer"); try { br.mark(1); br.skip(2); System.out.println(br.read()); // According to JDK 1.1.8 behaviour, // this should invalidate the // mark, for this buffer size at least. br.reset(); System.out.println(br.read()); } catch (Exception e) { System.out.println(e.toString()); } /* And now to something completely different: BufferedReader.read (char [], int, int). Here is a small test to check whether all int arguments are checked against their constraints (Java Class Lib. Vol. 1, 2nd Ed.) This test should generate a lot of Exceptions. */ sr = new StringReader("sr"); br = new BufferedReader(sr); char [] buf = new char[1]; System.out.println("Null pointer"); try { br.read(null, 0, 1); } catch (Exception e) { System.out.println(e.toString()); } System.out.println("offset >= buf.length"); try { br.read(buf, 1, 1); } catch (Exception e) { System.out.println(e.toString()); } System.out.println("offset >= buf.length"); try { /* The funny thing is that this one *doesn't* generate an exception in JDK1.1.8, although the offset parameter is out of bounds, since there is no buf[1]. */ br.read(buf, 1, 0); } catch (Exception e) { System.out.println(e.toString()); } System.out.println("offset >= buf.length"); try { br.read(buf, 5, 1); } catch (Exception e) { System.out.println(e.toString()); } System.out.println("count > buf.length - offset"); try { br.read(buf, 0, 5); } catch (Exception e) { System.out.println(e.toString()); } System.out.println("offset < 0"); try { br.read(buf, -1, 1); } catch (Exception e) { System.out.println(e.toString()); } System.out.println("count < 0"); try { br.read(buf, 0, -1); } catch (Exception e) { System.out.println(e.toString()); } /* Test whether readLine is blocking or not */ PseudoReader3 pr3 = new PseudoReader3(); br = new BufferedReader(pr3, 10); try { /* Java Class Libraries Vol 1 2nd Edition says that readLine is blocking. JDK 1.1.8 behaves that way. */ System.out.println(br.readLine()); } catch (Exception e) { System.out.println(e.toString()); } } } /* Expected Output: count = 8192 count = 8192 java.lang.IllegalArgumentException: Read-ahead limit is negative 123 4567 4567 java.lang.NullPointerException java.lang.IllegalArgumentException: Illegal buffer size: 0 1 java.io.IOException: Stream closed java.io.IOException: Stream closed java.io.IOException: Stream closed java.io.IOException: Stream closed java.io.IOException: Stream closed java.io.IOException: Stream closed java.io.IOException: Stream closed java.io.IOException: Stream closed 5 java.lang.IllegalArgumentException: skip value is negative Reset unmarked java.io.IOException: mark never set or invalidated Reset invalidated 65 66 java.io.IOException: mark never set or invalidated Skipping over marked buffer 69 java.io.IOException: mark never set or invalidated Null pointer java.lang.NullPointerException offset >= buf.length java.lang.IndexOutOfBoundsException offset >= buf.length offset >= buf.length java.lang.IndexOutOfBoundsException count > buf.length - offset java.lang.IndexOutOfBoundsException offset < 0 java.lang.IndexOutOfBoundsException count < 0 java.lang.IndexOutOfBoundsException java.io.IOException: you keep trying ... */
02N/kaffe
test/regression/BufferedReaderTest.java
Java
lgpl-2.1
10,954
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore> #include <qaccelerometer.h> QTM_USE_NAMESPACE namespace arrows{ static const QString ARROW_UP="^", ARROW_DOWN="v", ARROW_LEFT="<",ARROW_RIGHT=">"; } namespace orientation{ static const QString LANDSCAPE="landscape", PORTRAIT="portrait"; } class AccelerometerFilter : public QAccelerometerFilter { public: bool filter(QAccelerometerReading *reading) { QString arrow = getArrowKey(reading->x(), reading->y()); if (arrow!=exArrow){ qDebug() << "direction:" << arrow; exArrow = arrow; } return false; // don't store the reading in the sensor } private: QString exArrow; QString getArrowKey(qreal x, qreal y){ // axis_x: LEFT or RIGHT if (abs(x)>abs(y)) return x>0?(arrows::ARROW_LEFT):(arrows::ARROW_RIGHT); // axis_y: UP or DOWN return y>0?(arrows::ARROW_DOWN):(arrows::ARROW_UP); } static qreal abs(qreal value) {return value<0?-value:value;} }; int main(int argc, char **argv) { QCoreApplication app(argc, argv); QAccelerometer sensor; if (!sensor.connectToBackend()) { qWarning("No Accelerometer available!"); return EXIT_FAILURE; } const char* alwaysOn = "alwaysOn"; sensor.setProperty(alwaysOn, true); AccelerometerFilter filter; sensor.addFilter(&filter); qrangelist datarates = sensor.availableDataRates(); int i = datarates.size(); if (i>0) sensor.setDataRate(datarates.at(i-1).second); sensor.start(); return app.exec(); }
KDE/android-qt-mobility
examples/sensors/arrowkeys/main.cpp
C++
lgpl-2.1
3,604
/* * (C) Copyright 2011 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * 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 * Lesser General Public License for more details. * * Contributors: * Olivier Grisel * * $Id$ */ package org.nuxeo.ecm.platform.annotations.repository.listener; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.event.DocumentEventTypes; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventListener; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; import org.nuxeo.ecm.core.schema.FacetNames; import org.nuxeo.ecm.platform.annotations.repository.service.AnnotatedDocumentEventListener; import org.nuxeo.ecm.platform.annotations.repository.service.AnnotationsFulltextInjector; import org.nuxeo.ecm.platform.annotations.repository.service.AnnotationsRepositoryComponent; /** * Extract the text of the body of the annotation to register it as a related * text resource on the document for full-text indexing by the repository. */ public class AnnotationFulltextEventListener implements EventListener { @Override public void handleEvent(Event event) throws ClientException { AnnotationsFulltextInjector injector = AnnotationsRepositoryComponent.instance.getFulltextInjector(); if (!(event.getContext() instanceof DocumentEventContext)) { return; } DocumentEventContext context = (DocumentEventContext) event.getContext(); CoreSession session = context.getCoreSession(); DocumentModel doc = context.getSourceDocument(); if (doc == null) { // no need to update a deleted document return; } if (!doc.hasFacet(FacetNames.HAS_RELATED_TEXT)) { // no full-text indexing of annotation for this document type return; } String annotationId = (String) context.getProperty(AnnotatedDocumentEventListener.ANNOTATION_ID); String annotationBody = (String) context.getProperty(AnnotatedDocumentEventListener.ANNOTATION_BODY); if (AnnotatedDocumentEventListener.ANNOTATION_CREATED.equals(event.getName())) { injector.setAnnotationText(doc, annotationId, annotationBody); session.saveDocument(doc); } else if (AnnotatedDocumentEventListener.ANNOTATION_DELETED.equals(event.getName())) { if (injector.removeAnnotationText(doc, annotationId)) { session.saveDocument(doc); } } else if (AnnotatedDocumentEventListener.ANNOTATION_UPDATED.equals(event.getName())) { injector.removeAnnotationText(doc, annotationId); injector.setAnnotationText(doc, annotationId, annotationBody); session.saveDocument(doc); } else if (DocumentEventTypes.DOCUMENT_CHECKEDIN.equals(event.getName())) { // clean all annotation text before check-in: checked-in versions // handle their own annotations independently of the live version DocumentRef versionRef = (DocumentRef) context.getProperty("checkedInVersionRef"); DocumentModel version = session.getDocument(versionRef); if (injector.removeAnnotationText(version, null)) { session.saveDocument(version); } } else { return; } } }
deadcyclo/nuxeo-features
annot/nuxeo-annot-repo/src/main/java/org/nuxeo/ecm/platform/annotations/repository/listener/AnnotationFulltextEventListener.java
Java
lgpl-2.1
3,907
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyUrllib3(PythonPackage): """HTTP library with thread-safe connection pooling, file post, and more.""" homepage = "https://urllib3.readthedocs.io/" url = "https://pypi.io/packages/source/u/urllib3/urllib3-1.25.6.tar.gz" version('1.25.6', sha256='9a107b99a5393caf59c7aa3c1249c16e6879447533d0887f4336dde834c7be86') version('1.25.3', sha256='dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232') version('1.21.1', sha256='b14486978518ca0901a76ba973d7821047409d7f726f22156b24e83fd71382a5') version('1.20', sha256='97ef2b6e2878d84c0126b9f4e608e37a951ca7848e4855a7f7f4437d5c34a72f') version('1.14', sha256='dd4fb13a4ce50b18338c7e4d665b21fd38632c5d4b1d9f1a1379276bd3c08d37') depends_on('python@2.7:2.8,3.4:', type=('build', 'run')) depends_on('py-setuptools', type='build') depends_on('py-pytest', type='test') depends_on('py-mock', type='test') depends_on('py-tornado', type='test') variant('secure', default=False, description='Add SSL/TLS support') depends_on('py-pyopenssl@0.14:', when='+secure') depends_on('py-cryptography@1.3.4:', when='+secure') depends_on('py-idna@2:', when='+secure') depends_on('py-certifi', when='+secure') depends_on('py-ipaddress', when='+secure ^python@2.7:2.8') variant('socks', default=False, description='SOCKS and HTTP proxy support') depends_on('py-pysocks@1.5.6,1.5.8:1.999', when='+socks')
iulian787/spack
var/spack/repos/builtin/packages/py-urllib3/package.py
Python
lgpl-2.1
1,658
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="hu" sourcelanguage="en"> <context> <name>CmdApproxPlane</name> <message> <location filename="../../Command.cpp" line="+93"/> <source>Reverse Engineering</source> <translation>Fordított tervezés</translation> </message> <message> <location line="+1"/> <source>Approximate plane...</source> <translation>Hozzávetőleges sík ...</translation> </message> <message> <location line="+1"/> <source>Approximate a plane</source> <translation>Sík megbecsülése</translation> </message> </context> <context> <name>CmdApproxSurface</name> <message> <location line="-37"/> <source>Reverse Engineering</source> <translation>Fordított tervezés</translation> </message> <message> <location line="+1"/> <source>Approximate B-Spline surface...</source> <translation>Hozzávetőleges B-görbe felület...</translation> </message> <message> <source>Approximate surface...</source> <translation type="obsolete">Hozzávetőleges felület...</translation> </message> <message> <location line="+1"/> <source>Approximate a B-Spline surface</source> <translation>Hozzávetőleges B-Spline felület</translation> </message> </context> <context> <name>CmdPoissonReconstruction</name> <message> <location line="+134"/> <source>Reverse Engineering</source> <translation>Fordított tervezés</translation> </message> <message> <location line="+1"/> <source>Poisson...</source> <translation>Poisson eloszlás...</translation> </message> <message> <location line="+1"/> <source>Poisson surface reconstruction</source> <translation>Poisson felszín újrapítése</translation> </message> </context> <context> <name>CmdViewTriangulation</name> <message> <location line="+32"/> <source>Reverse Engineering</source> <translation>Fordított tervezés</translation> </message> <message> <location line="+1"/> <source>Structured point clouds</source> <translation>Strukturált pontfelhők</translation> </message> <message> <location line="+1"/> <location line="+1"/> <source>Triangulation of structured point clouds</source> <translation>Pont strukturált felhők háromszögelése</translation> </message> <message> <source>View triangulation</source> <translation type="obsolete">View triangulation</translation> </message> </context> <context> <name>ReenGui::FitBSplineSurface</name> <message> <location filename="../../FitBSplineSurface.ui" line="+14"/> <source>Fit B-Spline surface</source> <translation>B-görbe felület ilesztése</translation> </message> <message> <location line="+6"/> <source>u-Direction</source> <translation>u-Irány</translation> </message> <message> <location line="+6"/> <location line="+67"/> <source>Degree</source> <translation>Fok</translation> </message> <message> <location line="-38"/> <location line="+67"/> <source>Control points</source> <translation>Ellenőrzési pontok</translation> </message> <message> <location line="-35"/> <source>v-Direction</source> <translation>v-Irány</translation> </message> <message> <location line="+67"/> <source>Settings</source> <translation>Beállítások</translation> </message> <message> <location line="+6"/> <source>Iterations</source> <translation>Lépésszám</translation> </message> <message> <location line="+29"/> <source>Size factor</source> <translation>Méret tényező</translation> </message> <message> <location line="+29"/> <source>Smoothing</source> <translation>Simítás</translation> </message> <message> <location line="+9"/> <source>Total Weight</source> <translation>Összsúly</translation> </message> <message> <location line="+29"/> <source>Length of gradient</source> <translation>Dőlés hossza</translation> </message> <message> <location line="+29"/> <source>Bending energy</source> <translation>Hajlítási energia</translation> </message> <message> <location line="+29"/> <source>Curvature variation</source> <translation>Görbület variáció</translation> </message> <message> <location line="+32"/> <source>User-defined u/v directions</source> <translation>Felhasználó által definiált u/v irányba</translation> </message> </context> <context> <name>ReenGui::FitBSplineSurfaceWidget</name> <message> <location filename="../../FitBSplineSurface.cpp" line="+146"/> <source>Wrong selection</source> <translation>Rossz kijelölés</translation> </message> <message> <location line="+1"/> <source>Please select a single placement object to get local orientation.</source> <translation>Kérjük, válasszon egy önállóan elhelyezett tárgyat a hely meghatározásához.</translation> </message> <message> <location line="+28"/> <source>Input error</source> <translation>Bemeneti hiba</translation> </message> </context> <context> <name>ReenGui::PoissonWidget</name> <message> <location filename="../../Poisson.ui" line="+14"/> <source>Poisson</source> <translation>Poisson eloszlás</translation> </message> <message> <location line="+6"/> <source>Parameters</source> <translation>Paraméterek</translation> </message> <message> <location line="+6"/> <source>Octree depth</source> <translation>Octree fastruktúra mélysége</translation> </message> <message> <location line="+20"/> <source>Solver divide</source> <translation>Szétosztó megoldó</translation> </message> <message> <location line="+20"/> <source>Samples per node</source> <translation>Csomópontonkénti minta</translation> </message> <message> <location filename="../../Poisson.cpp" line="+109"/> <source>Input error</source> <translation>Bemeneti hiba</translation> </message> </context> <context> <name>Reen_ApproxSurface</name> <message> <location filename="../../Command.cpp" line="-159"/> <location line="+135"/> <source>Wrong selection</source> <translation>Rossz kijelölés</translation> </message> <message> <location line="-134"/> <location line="+135"/> <source>Please select a single point cloud.</source> <translation>Kérjük, válasszon egy pontú felhőt.</translation> </message> </context> <context> <name>Reen_ViewTriangulation</name> <message> <location line="+55"/> <source>View triangulation failed</source> <translation>Háromtényezős nézet nem sikerült</translation> </message> </context> <context> <name>Workbench</name> <message> <location filename="../../Workbench.cpp" line="+37"/> <source>Reverse Engineering</source> <translation>Fordított tervezés</translation> </message> </context> </TS>
usakhelo/FreeCAD
src/Mod/ReverseEngineering/Gui/Resources/translations/ReverseEngineering_hu.ts
TypeScript
lgpl-2.1
7,738
/* LanguageTool, a natural language style checker * Copyright (C) 2010 Marcin Miłkowski (www.languagetool.org) * * This library 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.patterns.bitext; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.rules.patterns.AbstractPatternRule; import org.languagetool.rules.patterns.FalseFriendRuleLoader; import org.xml.sax.SAXException; /** * Loads the false friend rules as bitext pattern rules. Note that the resulting * rules have suggestions that are not really customizable, in contradistinction * to the 'real' bitext pattern rules. * * @author Marcin Miłkowski */ public class FalseFriendsAsBitextLoader { public List<BitextPatternRule> getFalseFriendsAsBitext( String filename, Language motherTongue, Language language) throws ParserConfigurationException, SAXException, IOException { FalseFriendRuleLoader ruleLoader = new FalseFriendRuleLoader(motherTongue); List<BitextPatternRule> bRules = new ArrayList<>(); List<AbstractPatternRule> rules1 = ruleLoader.getRules( JLanguageTool.getDataBroker().getFromRulesDirAsStream(filename), motherTongue, language); List<AbstractPatternRule> rules2 = ruleLoader.getRules( JLanguageTool.getDataBroker().getFromRulesDirAsStream(filename), language, motherTongue); Map<String, AbstractPatternRule> srcRules = new HashMap<>(); for (AbstractPatternRule rule : rules1) { srcRules.put(rule.getId(), rule); } for (AbstractPatternRule rule : rules2) { if (srcRules.containsKey(rule.getId())) { BitextPatternRule bRule = new BitextPatternRule( srcRules.get(rule.getId()), rule); bRule.setSourceLanguage(motherTongue); bRule.setCategory(rule.getCategory()); bRules.add(bRule); } } return bRules; } }
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/patterns/bitext/FalseFriendsAsBitextLoader.java
Java
lgpl-2.1
2,825
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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 * Lesser General Public License for more details. * */ package org.kurento.test.services; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.List; import org.apache.commons.io.FileUtils; import org.kurento.test.Shell; import org.kurento.test.grid.GridNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Audio recorder using FFMPEG and audio quality assessment with PESQ. * * @author Boni Garcia (bgarcia@gsyc.es) * @since 4.2.11 * @see <a href="https://www.ffmpeg.org/">FFMPEG</a> * @see <a href="http://en.wikipedia.org/wiki/PESQ">PESQ</a> */ public class Recorder { private static Logger log = LoggerFactory.getLogger(Recorder.class); private static final String HTTP_TEST_FILES = "http://files.kurento.org"; private static final String PESQ_RESULTS = "pesq_results.txt"; private static final String RECORDED_WAV = KurentoMediaServerManager .getWorkspace() + "recorded.wav"; public static void recordRemote(GridNode node, int seconds, int sampleRate, AudioChannel audioChannel) { try { node.getSshConnection().execCommand("ffmpeg", "-y", "-t", String.valueOf(seconds), "-f", "alsa", "-i", "pulse", "-q:a", "0", "-ac", audioChannel.toString(), "-ar", String.valueOf(sampleRate), RECORDED_WAV); } catch (IOException e) { log.error("IOException recording audio in remote node " + node.getHost()); } } public static void record(int seconds, int sampleRate, AudioChannel audioChannel) { Shell.run("sh", "-c", "ffmpeg -y -t " + seconds + " -f alsa -i pulse -q:a 0 -ac " + audioChannel + " -ar " + sampleRate + " " + RECORDED_WAV); } public static float getRemotePesqMos(GridNode node, String audio, int sampleRate) { node.getSshConnection().getFile(RECORDED_WAV, RECORDED_WAV); return getPesqMos(audio, sampleRate); } public static float getPesqMos(String audio, int sampleRate) { float pesqmos = 0; try { String pesq = KurentoServicesTestHelper.getTestFilesPath() + "/bin/pesq/PESQ"; String origWav = ""; if (audio.startsWith(HTTP_TEST_FILES)) { origWav = KurentoServicesTestHelper.getTestFilesPath() + audio.replace(HTTP_TEST_FILES, ""); } else { // Download URL origWav = KurentoMediaServerManager.getWorkspace() + "/downloaded.wav"; URL url = new URL(audio); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(origWav); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); } Shell.runAndWait(pesq, "+" + sampleRate, origWav, RECORDED_WAV); List<String> lines = FileUtils.readLines(new File(PESQ_RESULTS), "utf-8"); pesqmos = Float.parseFloat(lines.get(1).split("\t")[2].trim()); log.info("PESQMOS " + pesqmos); Shell.runAndWait("rm", PESQ_RESULTS); } catch (IOException e) { log.error("Exception recording local audio", e); } return pesqmos; } }
bawn92/kurento-java
kurento-integration-tests/kurento-test/src/main/java/org/kurento/test/services/Recorder.java
Java
lgpl-2.1
3,609
/* This example is for quasi-conformal minimization */ /* mu controls the beltrami coefficient */ #include "FemusInit.hpp" #include "MultiLevelSolution.hpp" #include "MultiLevelProblem.hpp" #include "NumericVector.hpp" #include "VTKWriter.hpp" #include "GMVWriter.hpp" #include "NonLinearImplicitSystem.hpp" #include "TransientSystem.hpp" #include "adept.h" #include <cstdlib> #include "petsc.h" #include "petscmat.h" #include "PetscMatrix.hpp" bool stopIterate = false; using namespace femus; // Comment back in for working code //const double mu[2] = {0.8, 0.}; void UpdateMu(MultiLevelSolution& mlSol); void AssembleConformalMinimization(MultiLevelProblem& ml_prob); //stable and not bad void AssembleShearMinimization(MultiLevelProblem& ml_prob); // IBVs. No boundary, and IVs set to sphere (just need something). bool SetBoundaryCondition(const std::vector < double >& x, const char solName[], double& value, const int faceName, const double time) { bool dirichlet = true; value = 0.; if(!strcmp(solName, "Dx1")) { if(1 == faceName || 3 == faceName) { dirichlet = false; } if(4 == faceName) { //value = 0.04 * sin (4*(x[1] / 0.5 * acos (-1.))); value = 0.75 * sin(x[1] / 0.5 * M_PI); //dirichlet = false; } } else if(!strcmp(solName, "Dx2")) { if(2 == faceName) { dirichlet = false; } } return dirichlet; } // Main program starts here. int main(int argc, char** args) { // init Petsc-MPI communicator FemusInit mpinit(argc, args, MPI_COMM_WORLD); // define multilevel mesh unsigned maxNumberOfMeshes; MultiLevelMesh mlMsh; // Read coarse level mesh and generate finer level meshes. double scalingFactor = 1.; //mlMsh.GenerateCoarseBoxMesh(32, 32, 0, -0.5, 0.5, -0.5, 0.5, 0., 0., QUAD9, "seventh"); //mlMsh.ReadCoarseMesh ("../input/squareTri.neu", "seventh", scalingFactor); mlMsh.ReadCoarseMesh ("../input/square.neu", "seventh", scalingFactor); unsigned numberOfUniformLevels = 5; unsigned numberOfSelectiveLevels = 0; mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL); // Erase all the coarse mesh levels. mlMsh.EraseCoarseLevels(numberOfUniformLevels - 1); // print mesh info mlMsh.PrintInfo(); const unsigned dim = mlMsh.GetDimension(); // Define the multilevel solution and attach the mlMsh object to it. MultiLevelSolution mlSol(&mlMsh); // Add variables X,Y,W to mlSol. FEOrder feOrder = FIRST; mlSol.AddSolution("Dx1", LAGRANGE, feOrder, 0); mlSol.AddSolution("Dx2", LAGRANGE, feOrder, 0); mlSol.AddSolution("mu1", DISCONTINUOUS_POLYNOMIAL, ZERO, 0, false); mlSol.AddSolution("mu2", DISCONTINUOUS_POLYNOMIAL, ZERO, 0, false); mlSol.AddSolution("muN1", DISCONTINUOUS_POLYNOMIAL, ZERO, 0, false); mlSol.AddSolution("weight1", DISCONTINUOUS_POLYNOMIAL, ZERO, 0, false); mlSol.AddSolution("muN2", LAGRANGE, feOrder, 0, false); mlSol.AddSolution("weight2", LAGRANGE, feOrder, 0, false); mlSol.AddSolution("theta1", DISCONTINUOUS_POLYNOMIAL, ZERO, 0, false); mlSol.AddSolution("theta2", LAGRANGE, feOrder, 0, false); mlSol.AddSolution("phi1", DISCONTINUOUS_POLYNOMIAL, ZERO, 0, false); mlSol.AddSolution("phi2", LAGRANGE, feOrder, 0, false); // Initialize the variables and attach boundary conditions. mlSol.Initialize("All"); mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition); mlSol.GenerateBdc("All"); MultiLevelProblem mlProb(&mlSol); // Add system Conformal or Shear Minimization in mlProb. NonLinearImplicitSystem& system = mlProb.add_system < NonLinearImplicitSystem > ("conformal"); //for conformal // Add solutions newDX, Lambda1 to system. system.AddSolutionToSystemPDE("Dx1"); system.AddSolutionToSystemPDE("Dx2"); // Parameters for convergence and # of iterations. system.SetMaxNumberOfNonLinearIterations(100); system.SetNonLinearConvergenceTolerance(1.e-10); system.init(); mlSol.SetWriter(VTK); std::vector<std::string> mov_vars; mov_vars.push_back("Dx1"); mov_vars.push_back("Dx2"); mlSol.GetWriter()->SetMovingMesh(mov_vars); // and this? std::vector < std::string > variablesToBePrinted; variablesToBePrinted.push_back("All"); mlSol.GetWriter()->SetDebugOutput(true); //mlSol.GetWriter()->Write (DEFAULT_OUTPUTDIR, "linear", variablesToBePrinted, 0); mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted, 0); // Attach the assembling function to system and initialize. system.SetAssembleFunction(AssembleShearMinimization); //system.SetAssembleFunction (AssembleConformalMinimization); system.MGsolve(); mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted, 1); system.SetAssembleFunction(AssembleConformalMinimization); system.MGsolve(); mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted, 2); return 0; } unsigned counter = 0; // Building the Conformal Minimization system. void AssembleConformalMinimization(MultiLevelProblem& ml_prob) { // ml_prob is the global object from/to where get/set all the data // level is the level of the PDE system to be assembled // call the adept stack object adept::Stack& s = FemusInit::_adeptStack; // Extract pointers to the several objects that we are going to use. NonLinearImplicitSystem* mlPdeSys = &ml_prob.get_system< NonLinearImplicitSystem> ("conformal"); // pointer to the linear implicit system named "Poisson" const unsigned level = mlPdeSys->GetLevelToAssemble(); // Pointers to the mesh (level) object and elem object in mesh (level). Mesh *msh = ml_prob._ml_msh->GetLevel(level); elem *el = msh->el; // Pointers to the multilevel solution, solution (level) and equation (level). MultiLevelSolution *mlSol = ml_prob._ml_sol; if(counter > 0 && !stopIterate) { UpdateMu(*mlSol); } Solution *sol = ml_prob._ml_sol->GetSolutionLevel(level); LinearEquationSolver *pdeSys = mlPdeSys->_LinSolver[level]; // Pointers to global stiffness matrix and residual vector in pdeSys (level). SparseMatrix *KK = pdeSys->_KK; NumericVector *RES = pdeSys->_RES; // Convenience variables to keep track of the dimension. const unsigned dim = msh->GetDimension(); const unsigned DIM = 2; // Get the process_id (for parallel computation). unsigned iproc = msh->processor_id(); std::vector < double > phi; // local test function for velocity std::vector < double > phi_x; // local test function first order partial derivatives double weight; // gauss point weight // Setting the reference elements to be equilateral triangles. // std::vector < std::vector < double > > xT (2); // xT[0].resize (7); // xT[0][0] = -0.5; // xT[0][1] = 0.5; // xT[0][2] = 0.; // xT[0][3] = 0.; // xT[0][4] = 0.25; // xT[0][5] = -0.25; // xT[0][6] = 0.; // // xT[1].resize (7); // xT[1][0] = 0.; // xT[1][1] = 0.; // xT[1][2] = sqrt (3.) / 2.; // xT[1][3] = 0.; // xT[1][4] = sqrt (3.) / 4.; // xT[1][5] = sqrt (3.) / 4.; // xT[1][6] = sqrt (3.) / 6.; // // std::vector< double > phi_uv0; // std::vector< double > phi_uv1; // std::vector< double > stdVectorPhi; // std::vector< double > stdVectorPhi_uv; // Extract positions of Dx in ml_sol object. std::vector < unsigned > solDxIndex(DIM); solDxIndex[0] = mlSol->GetIndex("Dx1"); solDxIndex[1] = mlSol->GetIndex("Dx2"); std::vector < unsigned > solMuIndex(DIM); solMuIndex[0] = mlSol->GetIndex("mu1"); solMuIndex[1] = mlSol->GetIndex("mu2"); unsigned solType1 = mlSol->GetSolutionType(solMuIndex[0]); // Extract finite element type for the solution. unsigned solType; solType = mlSol->GetSolutionType(solDxIndex[0]); // Get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC). unsigned xType = 2; // Get the positions of Y in the pdeSys object. std::vector < unsigned > solDxPdeIndex(dim); solDxPdeIndex[0] = mlPdeSys->GetSolPdeIndex("Dx1"); solDxPdeIndex[1] = mlPdeSys->GetSolPdeIndex("Dx2"); // Local solution vectors for Nx and NDx. std::vector < std::vector < adept::adouble > > solDx(DIM); std::vector < std::vector < adept::adouble > > solx(DIM); std::vector < std::vector < double > > xHat(DIM); std::vector < std::vector < double > > solMu(DIM); // Local-to-global pdeSys dofs. std::vector < int > SYSDOF; // Local residual vectors. vector< double > Res; std::vector < std::vector< adept::adouble > > aResDx(dim); // Local Jacobian matrix (ordered by column). vector < double > Jac; KK->zero(); // Zero all the entries of the Global Matrix RES->zero(); // Zero all the entries of the Global Residual // ELEMENT LOOP: each process loops only on the elements that it owns. for(int iel = msh->_elementOffset[iproc]; iel < msh->_elementOffset[iproc + 1]; iel++) { // Numer of solution element dofs. short unsigned ielGeom = msh->GetElementType(iel); unsigned nxDofs = msh->GetElementDofNumber(iel, solType); unsigned nDofs1 = msh->GetElementDofNumber(iel, solType1); // Resize local arrays. for(unsigned K = 0; K < DIM; K++) { solDx[K].resize(nxDofs); solx[K].resize(nxDofs); xHat[K].resize(nxDofs); solMu[K].resize(nDofs1); } // Resize local arrays SYSDOF.resize(dim * nxDofs); Res.resize(dim * nxDofs); for(unsigned k = 0; k < dim; k++) { aResDx[k].assign(nxDofs, 0.); } // local storage of global mapping and solution for(unsigned i = 0; i < nxDofs; i++) { // Global-to-local mapping between X solution node and solution dof. unsigned iDDof = msh->GetSolutionDof(i, iel, solType); for(unsigned K = 0; K < DIM; K++) { solDx[K][i] = (*sol->_Sol[solDxIndex[K]])(iDDof); // Global-to-global mapping between NDx solution node and pdeSys dof. if(K < dim) { SYSDOF[ K * nxDofs + i] = pdeSys->GetSystemDof(solDxIndex[K], solDxPdeIndex[K], i, iel); } } } for(unsigned i = 0; i < nDofs1; i++) { unsigned iDof = msh->GetSolutionDof(i, iel, solType1); for(unsigned K = 0; K < DIM; K++) { solMu[K][i] = (*sol->_Sol[solMuIndex[K]])(iDof); } } // start a new recording of all the operations involving adept variables. s.new_recording(); for(unsigned i = 0; i < nxDofs; i++) { unsigned iXDof = msh->GetSolutionDof(i, iel, xType); for(unsigned K = 0; K < DIM; K++) { xHat[K][i] = (*msh->_topology->_Sol[K])(iXDof); solx[K][i] = xHat[K][i] + solDx[K][i]; } } // *** Gauss point loop *** for(unsigned ig = 0; ig < msh->_finiteElement[ielGeom][solType]->GetGaussPointNumber(); ig++) { // const double *phix; // local test function // const double *phi1; // local test function // const double *phix_uv[dim]; // local test function first order partial derivatives // // double weight; // gauss point weight // // // Get Gauss point weight, test function, and first order derivatives. // if (ielGeom == QUAD) { // phix = msh->_finiteElement[ielGeom][solType]->GetPhi (ig); // // phix_uv[0] = msh->_finiteElement[ielGeom][solType]->GetDPhiDXi (ig); // phix_uv[1] = msh->_finiteElement[ielGeom][solType]->GetDPhiDEta (ig); // // weight = msh->_finiteElement[ielGeom][solType]->GetGaussWeight (ig); // } // // // Special adjustments for triangles. // else { // msh->_finiteElement[ielGeom][solType]->Jacobian (xT, ig, weight, stdVectorPhi, stdVectorPhi_uv); // phix = &stdVectorPhi[0]; // phi_uv0.resize (nxDofs); // phi_uv1.resize (nxDofs); // for (unsigned i = 0; i < nxDofs; i++) { // phi_uv0[i] = stdVectorPhi_uv[i * dim]; // phi_uv1[i] = stdVectorPhi_uv[i * dim + 1]; // } // phix_uv[0] = &phi_uv0[0]; // phix_uv[1] = &phi_uv1[0]; // } msh->_finiteElement[ielGeom][solType]->Jacobian(xHat, ig, weight, phi, phi_x); std::vector < std::vector < adept::adouble > > gradSolx(dim); for(unsigned k = 0; k < dim; k++) { gradSolx[k].assign(dim, 0.); } for(unsigned i = 0; i < nxDofs; i++) { for(unsigned j = 0; j < dim; j++) { for(unsigned k = 0; k < dim; k++) { gradSolx[k][j] += solx[k][i] * phi_x[i * dim + j]; } } } double *phi1 = msh->_finiteElement[ielGeom][solType1]->GetPhi(ig); // // Initialize and compute values of x, Dx, NDx, x_uv at the Gauss points. // double xHatg[DIM] = {0., 0.}; // adept::adouble solx_uv[2][2] = {{0., 0.}, {0., 0.}}; // for (unsigned K = 0; K < DIM; K++) { // for (unsigned i = 0; i < nxDofs; i++) { // xHatg[K] += phix[i] * xHat[K][i]; // } // for (int j = 0; j < dim; j++) { // for (unsigned i = 0; i < nxDofs; i++) { // solx_uv[K][j] += phix_uv[j][i] * solx[K][i]; // } // } // // for (unsigned i = 0; i < nxDofs; i++) { // // solx_z[K] += // // solx_zBar[K] += // // } // } // // // Compute the metric, metric determinant, and area element. // std::vector < std::vector < adept::adouble > > g (dim); // for (unsigned i = 0; i < dim; i++) g[i].assign (dim, 0.); // // for (unsigned i = 0; i < dim; i++) { // for (unsigned j = 0; j < dim; j++) { // for (unsigned K = 0; K < DIM; K++) { // g[i][j] += solx_uv[K][i] * solx_uv[K][j]; // } // } // } // // adept::adouble detg = g[0][0] * g[1][1] - g[0][1] * g[1][0]; // adept::adouble Area = weight * sqrt (detg); // adept::adouble Area2 = weight;// Trick to give equal weight to each element. // adept::adouble norm2Xz = (1. / 4.) * (pow ( (solx_uv[0][0] + solx_uv[1][1]), 2) + pow ( (solx_uv[1][0] - solx_uv[0][1]), 2)); // // // Discretize the equation \delta CD = 0 on the basis d/du, d/dv. // adept::adouble XzBarXz_Bar[DIM]; // // // Comment out for working code // // // XzBarXz_Bar[0] = (1. / 4.) * (pow (solx_uv[0][0], 2) + pow (solx_uv[1][0], 2) - pow (solx_uv[0][1], 2) - pow (solx_uv[1][1], 2)); // XzBarXz_Bar[1] = (1. / 2.) * (solx_uv[0][0] * solx_uv[0][1] + solx_uv[1][0] * solx_uv[1][1]); // // // Comment out for working code double mu[2] = {0., 0.}; for(unsigned i = 0; i < nDofs1; i++) { for(unsigned K = 0; K < DIM; K++) { mu[K] += phi1[i] * solMu[K][i]; } } // std::cout << mu[0] <<" ";//<<mu[1]<<" "; // if (counter == 0) mu[0] = 0.8; // // for (unsigned K = 0; K < DIM; K++) { // if (counter > 0 && norm2Xz.value() > 0.) { // mu[K] += (1. / norm2Xz.value()) * XzBarXz_Bar[K].value(); // } // //if(counter % 2 == 0) mu[K]*=1.01; // //else mu[K]/=1.01; // } //std::cout << mu[0] <<" "<< mu[1]<<" "; adept::adouble V[DIM]; V[0] = (1 - mu[0]) * gradSolx[0][0] - (1 + mu[0]) * gradSolx[1][1] + mu[1] * (gradSolx[1][0] - gradSolx[0][1]); V[1] = (1 - mu[0]) * gradSolx[1][0] + (1 + mu[0]) * gradSolx[0][1] - mu[1] * (gradSolx[0][0] + gradSolx[1][1]); adept::adouble M[DIM][dim]; M[0][0] = (1 - mu[0]) * V[0] - mu[1] * V[1]; M[1][0] = (1 - mu[0]) * V[1] + mu[1] * V[0]; //M[0][0] = (1 - mu1) * V[0] - mu2 * V[1]; //M[1][0] = (1 - mu1) * V[1] + mu2 * V[0]; M[0][1] = (1 + mu[0]) * V[1] - mu[1] * V[0]; M[1][1] = - (1 + mu[0]) * V[0] - mu[1] * V[1]; //M[0][1] = (1 + mu1) * V[1] - mu2 * V[0]; //M[1][1]= -(1 + mu1) * V[0] - mu2 * V[1]; // Implement the Conformal Minimization equations. for(unsigned k = 0; k < dim; k++) { for(unsigned i = 0; i < nxDofs; i++) { adept::adouble term1 = 0.; for(unsigned j = 0; j < dim; j++) { term1 += 2 * M[k][j] * phi_x[i * dim + j]; } // Conformal energy equation (with trick). aResDx[k][i] += term1 * weight; } } } // end GAUSS POINT LOOP //------------------------------------------------------------------------ // Add the local Matrix/Vector into the global Matrix/Vector //copy the value of the adept::adoube aRes in double Res and store for(int k = 0; k < dim; k++) { for(int i = 0; i < nxDofs; i++) { Res[ k * nxDofs + i] = -aResDx[k][i].value(); } } RES->add_vector_blocked(Res, SYSDOF); // Resize Jacobian. Jac.resize((dim * nxDofs) * (dim * nxDofs)); // Define the dependent variables. for(int k = 0; k < dim; k++) { s.dependent(&aResDx[k][0], nxDofs); } // Define the independent variables. for(int k = 0; k < dim; k++) { s.independent(&solDx[k][0], nxDofs); } // Get the jacobian matrix (ordered by row). s.jacobian(&Jac[0], true); KK->add_matrix_blocked(Jac, SYSDOF, SYSDOF); s.clear_independents(); s.clear_dependents(); } //end ELEMENT LOOP for each process. RES->close(); KK->close(); counter++; } // end AssembleConformalMinimization. void UpdateMu(MultiLevelSolution& mlSol) { //MultiLevelSolution* mlSol = ml_prob._ml_sol; unsigned level = mlSol._mlMesh->GetNumberOfLevels() - 1u; Solution* sol = mlSol.GetSolutionLevel(level); Mesh* msh = mlSol._mlMesh->GetLevel(level); elem* el = msh->el; unsigned dim = msh->GetDimension(); std::vector < unsigned > indexDx(dim); indexDx[0] = mlSol.GetIndex("Dx1"); indexDx[1] = mlSol.GetIndex("Dx2"); unsigned solTypeDx = mlSol.GetSolutionType(indexDx[0]); std::vector < unsigned > indexMu(dim); indexMu[0] = mlSol.GetIndex("mu1"); indexMu[1] = mlSol.GetIndex("mu2"); unsigned indexMuN1 = mlSol.GetIndex("muN1"); //piecewice linear discontinuous unsigned indexW1 = mlSol.GetIndex("weight1"); unsigned solType1 = mlSol.GetSolutionType(indexMu[0]); unsigned indexTheta1 = mlSol.GetIndex("theta1"); unsigned indexTheta2 = mlSol.GetIndex("theta2"); unsigned indexPhi1 = mlSol.GetIndex("phi1"); unsigned indexPhi2 = mlSol.GetIndex("phi2"); std::vector< double > dof1; std::vector < std::vector < double > > solx(dim); std::vector < std::vector < double > > xHat(dim); for(unsigned k = 0; k < dim; k++) { sol->_Sol[indexMu[k]]->zero(); } sol->_Sol[indexW1]->zero(); std::vector < double > phi; // local test function for velocity std::vector < double > phi_x; // local test function first order partial derivatives double weight; // gauss point weight unsigned iproc = msh->processor_id(); unsigned nprocs = msh->n_processors(); for(int iel = msh->_elementOffset[iproc]; iel < msh->_elementOffset[iproc + 1]; iel++) { short unsigned ielGeom = msh->GetElementType(iel); unsigned nDofs1 = msh->GetElementDofNumber(iel, solType1); unsigned nDofsDx = msh->GetElementDofNumber(iel, solTypeDx); dof1.resize(nDofs1); for(int k = 0; k < dim; k++) { xHat[k].resize(nDofsDx); solx[k].resize(nDofsDx); } // local storage of global mapping and solution for(unsigned i = 0; i < nDofs1; i++) { dof1[i] = msh->GetSolutionDof(i, iel, solType1); } // local storage of coordinates for(unsigned i = 0; i < nDofsDx; i++) { unsigned idof = msh->GetSolutionDof(i, iel, solTypeDx); unsigned xDof = msh->GetSolutionDof(i, iel, 2); for(unsigned k = 0; k < dim; k++) { xHat[k][i] = (*msh->_topology->_Sol[k])(xDof); solx[k][i] = xHat[k][i] + (*sol->_Sol[indexDx[k]])(idof); } } for(unsigned ig = 0; ig < msh->_finiteElement[ielGeom][solTypeDx]->GetGaussPointNumber(); ig++) { msh->_finiteElement[ielGeom][solTypeDx]->Jacobian(xHat, ig, weight, phi, phi_x); std::vector < std::vector < double > > gradSolx(dim); for(unsigned k = 0; k < dim; k++) { gradSolx[k].assign(dim, 0.); } for(unsigned i = 0; i < nDofsDx; i++) { for(unsigned j = 0; j < dim; j++) { for(unsigned k = 0; k < dim; k++) { gradSolx[k][j] += solx[k][i] * phi_x[i * dim + j]; } } } double *phi1 = msh->_finiteElement[ielGeom][solType1]->GetPhi(ig); double norm2Xz = (1. / 4.) * (pow((gradSolx[0][0] + gradSolx[1][1]), 2) + pow((gradSolx[1][0] - gradSolx[0][1]), 2)); double XzBarXz_Bar[2]; XzBarXz_Bar[0] = (1. / 4.) * (pow(gradSolx[0][0], 2) + pow(gradSolx[1][0], 2) - pow(gradSolx[0][1], 2) - pow(gradSolx[1][1], 2)); XzBarXz_Bar[1] = (1. / 2.) * (gradSolx[0][0] * gradSolx[0][1] + gradSolx[1][0] * gradSolx[1][1]); // Comment out for working code double mu[2] = {0., 0.}; for(unsigned k = 0; k < 2; k++) { if(norm2Xz > 0.) { mu[k] += (1. / norm2Xz) * XzBarXz_Bar[k]; } } for(unsigned i = 0; i < nDofs1; i++) { sol->_Sol[indexW1]->add(dof1[i], phi1[i] * weight); for(unsigned k = 0; k < dim; k++) { sol->_Sol[indexMu[k]]->add(dof1[i], mu[k] * phi1[i] * weight); } } // end phi_i loop } // end gauss point loop } //end element loop for each process*/ for(unsigned k = 0; k < dim; k++) { sol->_Sol[indexMu[k]]->close(); } sol->_Sol[indexW1]->close(); sol->_Sol[indexTheta1]->zero(); sol->_Sol[indexPhi1]->zero(); for(unsigned i = msh->_dofOffset[solType1][iproc]; i < msh->_dofOffset[solType1][iproc + 1]; i++) { double weight = (*sol->_Sol[indexW1])(i); double mu[2]; for(unsigned k = 0; k < dim; k++) { mu[k] = (*sol->_Sol[indexMu[k]])(i); sol->_Sol[indexMu[k]]->set(i, mu[k] / weight); } sol->_Sol[indexMuN1]->set(i, sqrt(mu[0] * mu[0] + mu[1] * mu[1]) / weight); sol->_Sol[indexTheta1]->set(i, atan2(mu[1] / weight, fabs(mu[0]) / weight)); sol->_Sol[indexPhi1]->set(i, atan2(mu[0] / weight, fabs(mu[1]) / weight)); } for(unsigned k = 0; k < dim; k++) { sol->_Sol[indexMu[k]]->close(); } sol->_Sol[indexMuN1]->close(); sol->_Sol[indexTheta1]->close(); sol->_Sol[indexPhi1]->close(); double norm = sol->_Sol[indexMuN1]->linfty_norm(); std::cout << norm << std::endl; if(norm < 0.5) stopIterate = true; //BEGIN Iterative smoothing element -> nodes -> element for(unsigned smooth = 0; smooth < 1; smooth++) { unsigned indexW2 = mlSol.GetIndex("weight2"); unsigned indexMuN2 = mlSol.GetIndex("muN2"); //smooth ni norm unsigned solType2 = mlSol.GetSolutionType(indexMuN2); std::vector< double > dof2; std::vector< double > sol1; std::vector< double > solTheta1; std::vector< double > solPhi1; sol->_Sol[indexMuN2]->zero(); sol->_Sol[indexW2]->zero(); sol->_Sol[indexTheta2]->zero(); sol->_Sol[indexPhi2]->zero(); std::vector < double > phi2; // local test function for velocity std::vector < double > phi2_x; // local test function first order partial derivatives double weight2; // gauss point weight for(int iel = msh->_elementOffset[iproc]; iel < msh->_elementOffset[iproc + 1]; iel++) { short unsigned ielGeom = msh->GetElementType(iel); unsigned nDofs1 = msh->GetElementDofNumber(iel, solType1); unsigned nDofs2 = msh->GetElementDofNumber(iel, solType2); sol1.resize(nDofs1); solTheta1.resize(nDofs1); solPhi1.resize(nDofs1); dof2.resize(nDofs2); for(int k = 0; k < dim; k++) { xHat[k].resize(nDofs2); } for(unsigned i = 0; i < nDofs1; i++) { unsigned idof = msh->GetSolutionDof(i, iel, solType1); sol1[i] = (*sol->_Sol[indexMuN1])(idof); solTheta1[i] = (*sol->_Sol[indexTheta1])(idof); solPhi1[i] = (*sol->_Sol[indexPhi1])(idof); } // local storage of global mapping and solution for(unsigned i = 0; i < nDofs2; i++) { dof2[i] = msh->GetSolutionDof(i, iel, solType2); } // local storage of coordinates for(unsigned i = 0; i < nDofs2; i++) { unsigned xDof = msh->GetSolutionDof(i, iel, 2); for(unsigned k = 0; k < dim; k++) { xHat[k][i] = (*msh->_topology->_Sol[k])(xDof); } } for(unsigned ig = 0; ig < msh->_finiteElement[ielGeom][solType2]->GetGaussPointNumber(); ig++) { msh->_finiteElement[ielGeom][solType2]->Jacobian(xHat, ig, weight2, phi2, phi2_x); double *phi1 = msh->_finiteElement[ielGeom][solType1]->GetPhi(ig); double sol1g = 0.; double solTheta1g = 0.; double solPhi1g = 0.; for(unsigned i = 0; i < nDofs1; i++) { sol1g += phi1[i] * sol1[i]; solTheta1g += phi1[i] * solTheta1[i]; solPhi1g += phi1[i] * solPhi1[i]; } // *** phi_i loop *** for(unsigned i = 0; i < nDofs2; i++) { sol->_Sol[indexW2]->add(dof2[i], phi2[i] * weight2); sol->_Sol[indexMuN2]->add(dof2[i], sol1g * phi2[i] * weight2); sol->_Sol[indexTheta2]->add(dof2[i], solTheta1g * phi2[i] * weight2); sol->_Sol[indexPhi2]->add(dof2[i], solPhi1g * phi2[i] * weight2); } // end phi_i loop } // end gauss point loop } //end element loop for each process*/ sol->_Sol[indexW2]->close(); sol->_Sol[indexMuN2]->close(); sol->_Sol[indexTheta2]->close(); sol->_Sol[indexPhi2]->close(); for(unsigned i = msh->_dofOffset[solType2][iproc]; i < msh->_dofOffset[solType2][iproc + 1]; i++) { double weight = (*sol->_Sol[indexW2])(i); double value = (*sol->_Sol[indexMuN2])(i); sol->_Sol[indexMuN2]->set(i, value / weight); value = (*sol->_Sol[indexTheta2])(i); sol->_Sol[indexTheta2]->set(i, value / weight); value = (*sol->_Sol[indexPhi2])(i); sol->_Sol[indexPhi2]->set(i, value / weight); } sol->_Sol[indexMuN2]->close(); sol->_Sol[indexTheta2]->close(); sol->_Sol[indexPhi2]->close(); sol->_Sol[indexMuN1]->zero(); sol->_Sol[indexTheta1]->zero(); sol->_Sol[indexPhi1]->zero(); std::vector< double > sol2; std::vector< double > solTheta2; std::vector< double > solPhi2; for(int iel = msh->_elementOffset[iproc]; iel < msh->_elementOffset[iproc + 1]; iel++) { short unsigned ielGeom = msh->GetElementType(iel); unsigned nDofs1 = msh->GetElementDofNumber(iel, solType1); unsigned nDofs2 = msh->GetElementDofNumber(iel, solType2); dof1.resize(nDofs1); for(int k = 0; k < dim; k++) { xHat[k].resize(nDofs2); sol2.resize(nDofs2); solTheta2.resize(nDofs2); solPhi2.resize(nDofs2); } // local storage of global mapping and solution for(unsigned i = 0; i < nDofs1; i++) { dof1[i] = msh->GetSolutionDof(i, iel, solType1); } // local storage of coordinates for(unsigned i = 0; i < nDofs2; i++) { unsigned idof = msh->GetSolutionDof(i, iel, solType2); unsigned xDof = msh->GetSolutionDof(i, iel, 2); for(unsigned k = 0; k < dim; k++) { xHat[k][i] = (*msh->_topology->_Sol[k])(xDof); } sol2[i] = (*sol->_Sol[indexMuN2])(idof); solTheta2[i] = (*sol->_Sol[indexTheta2])(idof); solPhi2[i] = (*sol->_Sol[indexPhi2])(idof); } for(unsigned ig = 0; ig < msh->_finiteElement[ielGeom][solTypeDx]->GetGaussPointNumber(); ig++) { msh->_finiteElement[ielGeom][solTypeDx]->Jacobian(xHat, ig, weight, phi, phi_x); double sol2g = 0; double solTheta2g = 0; double solPhi2g = 0; for(unsigned i = 0; i < nDofs2; i++) { sol2g += sol2[i] * phi[i]; solTheta2g += solTheta2[i] * phi[i]; solPhi2g += solPhi2[i] * phi[i]; } double *phi1 = msh->_finiteElement[ielGeom][solType1]->GetPhi(ig); for(unsigned i = 0; i < nDofs1; i++) { sol->_Sol[indexMuN1]->add(dof1[i], sol2g * phi1[i] * weight); sol->_Sol[indexTheta1]->add(dof1[i], solTheta2g * phi1[i] * weight); sol->_Sol[indexPhi1]->add(dof1[i], solPhi2g * phi1[i] * weight); } // end phi_i loop } // end gauss point loop } //end element loop for each process*/ sol->_Sol[indexMuN1]->close(); sol->_Sol[indexTheta1]->close(); sol->_Sol[indexPhi1]->close(); for(unsigned i = msh->_dofOffset[solType1][iproc]; i < msh->_dofOffset[solType1][iproc + 1]; i++) { double weight = (*sol->_Sol[indexW1])(i); double radius = (*sol->_Sol[indexMuN1])(i) / weight; sol->_Sol[indexMuN1]->set(i, radius); double theta = (*sol->_Sol[indexTheta1])(i) / weight; sol->_Sol[indexTheta1]->set(i, theta); double phi = (*sol->_Sol[indexPhi1])(i) / weight; sol->_Sol[indexPhi1]->set(i, phi); double mu[2]; for(unsigned k = 0; k < dim; k++) { mu[k] = (*sol->_Sol[indexMu[k]])(i); } // if(fabs(theta) < fabs(phi)) { // if(mu[0] < 0) { // if(mu[1] < 0) theta = -theta - M_PI; // else theta = M_PI - theta; // } // } // else { // if(mu[1] < 0) { // theta = -M_PI / 2 + phi; // } // else { // theta = M_PI / 2 - phi; // } // } // sol->_Sol[indexMu[0]]->set(i, radius * cos(theta)); // sol->_Sol[indexMu[1]]->set(i, radius * sin(theta)); } sol->_Sol[indexMuN1]->close(); sol->_Sol[indexTheta1]->close(); sol->_Sol[indexPhi1]->close(); // for(unsigned k = 0; k < dim; k++) { // sol->_Sol[indexMu[k]]->close(); // } } //END Iterative smoothing element -> nodes -> element //BEGIN mu update double MuNormLocalSum = 0.; for(unsigned i = msh->_dofOffset[solType1][iproc]; i < msh->_dofOffset[solType1][iproc + 1]; i++) { MuNormLocalSum += (*sol->_Sol[indexMuN1])(i); } double MuNormAverage; MPI_Allreduce(&MuNormLocalSum, &MuNormAverage, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); MuNormAverage /= msh->_dofOffset[solType1][nprocs]; for(unsigned i = msh->_dofOffset[solType1][iproc]; i < msh->_dofOffset[solType1][iproc + 1]; i++) { double theta = (*sol->_Sol[indexTheta1])(i); double phi = (*sol->_Sol[indexPhi1])(i); double mu[2]; for(unsigned k = 0; k < dim; k++) { mu[k] = (*sol->_Sol[indexMu[k]])(i); } if(fabs(theta) < fabs(phi)) { if(mu[0] < 0) { if(mu[1] < 0) theta = -theta - M_PI; else theta = M_PI - theta; } } else { if(mu[1] < 0) { theta = -M_PI / 2 + phi; } else { theta = M_PI / 2 - phi; } } sol->_Sol[indexMu[0]]->set(i, MuNormAverage * cos(theta)); sol->_Sol[indexMu[1]]->set(i, MuNormAverage * sin(theta)); //sol->_Sol[indexTheta1]->set(i, theta); } for(unsigned k = 0; k < dim; k++) { sol->_Sol[indexMu[k]]->close(); } //sol->_Sol[indexTheta1]->close(); //END mu update } void AssembleShearMinimization(MultiLevelProblem& ml_prob) { // ml_prob is the global object from/to where get/set all the data // level is the level of the PDE system to be assembled // levelMax is the Maximum level of the MultiLevelProblem // assembleMatrix is a flag that tells if only the residual or also the matrix should be assembled // call the adept stack object adept::Stack& s = FemusInit::_adeptStack; // extract pointers to the several objects that we are going to use LinearImplicitSystem* mlPdeSys = &ml_prob.get_system< LinearImplicitSystem> ("conformal"); // pointer to the linear implicit system named "Poisson" const unsigned level = mlPdeSys->GetLevelToAssemble(); Mesh *msh = ml_prob._ml_msh->GetLevel(level); // pointer to the mesh (level) object elem *el = msh->el; // pointer to the elem object in msh (level) MultiLevelSolution *mlSol = ml_prob._ml_sol; // pointer to the multilevel solution object Solution *sol = ml_prob._ml_sol->GetSolutionLevel(level); // pointer to the solution (level) object LinearEquationSolver *pdeSys = mlPdeSys->_LinSolver[level]; // pointer to the equation (level) object SparseMatrix *KK = pdeSys->_KK; // pointer to the global stiffness matrix object in pdeSys (level) NumericVector *RES = pdeSys->_RES; // pointer to the global residual vector object in pdeSys (level) const unsigned dim = msh->GetDimension(); std::vector < double > phi; // local test function for velocity std::vector <adept::adouble> phi_x; // local test function first order partial derivatives adept::adouble weight; // gauss point weight unsigned iproc = msh->processor_id(); // get the process_id (for parallel computation) //solution variable std::vector < unsigned > solDxIndex(dim); solDxIndex[0] = mlSol->GetIndex("Dx1"); // get the position of "DX" in the ml_sol object solDxIndex[1] = mlSol->GetIndex("Dx2"); // get the position of "DY" in the ml_sol object if(dim == 3) solDxIndex[2] = mlSol->GetIndex("Dx3"); // get the position of "DY" in the ml_sol object unsigned solType; solType = mlSol->GetSolutionType(solDxIndex[0]); // get the finite element type for "U" unsigned xType = 2; // get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC) std::vector < unsigned > solDxPdeIndex(dim); solDxPdeIndex[0] = mlPdeSys->GetSolPdeIndex("Dx1"); // get the position of "Dx1" in the pdeSys object solDxPdeIndex[1] = mlPdeSys->GetSolPdeIndex("Dx2"); // get the position of "Dx2" in the pdeSys object if(dim == 3) solDxPdeIndex[2] = mlPdeSys->GetSolPdeIndex("Dx3"); // get the position of "Dx3" in the pdeSys object std::vector < std::vector < adept::adouble > > solDx(dim); // local Y solution std::vector < std::vector < adept::adouble > > x(dim); std::vector< int > SYSDOF; // local to global pdeSys dofs vector< double > Res; // local redidual vector std::vector< adept::adouble > aResDx[dim]; // local redidual vector vector < double > Jac; // local Jacobian matrix (ordered by column, adept) KK->zero(); // Set to zero all the entries of the Global Matrix RES->zero(); // Set to zero all the entries of the Global Residual // element loop: each process loops only on the elements that owns for(int iel = msh->_elementOffset[iproc]; iel < msh->_elementOffset[iproc + 1]; iel++) { short unsigned ielGeom = msh->GetElementType(iel); unsigned nxDofs = msh->GetElementDofNumber(iel, solType); // number of solution element dofs for(unsigned k = 0; k < dim; k++) { solDx[k].resize(nxDofs); x[k].resize(nxDofs); } // resize local arrays SYSDOF.resize(dim * nxDofs); Res.resize(dim * nxDofs); //resize for(unsigned k = 0; k < dim; k++) { aResDx[k].assign(nxDofs, 0.); //resize and zet to zero } // local storage of global mapping and solution for(unsigned i = 0; i < nxDofs; i++) { // Global-to-local mapping between X solution node and solution dof. unsigned iDDof = msh->GetSolutionDof(i, iel, solType); for(unsigned k = 0; k < dim; k++) { solDx[k][i] = (*sol->_Sol[solDxIndex[k]])(iDDof); // Global-to-global mapping between NDx solution node and pdeSys dof. SYSDOF[ k * nxDofs + i] = pdeSys->GetSystemDof(solDxIndex[k], solDxPdeIndex[k], i, iel); } } // start a new recording of all the operations involving adept variables. s.new_recording(); for(unsigned i = 0; i < nxDofs; i++) { unsigned iXDof = msh->GetSolutionDof(i, iel, xType); for(unsigned k = 0; k < dim; k++) { x[k][i] = (*msh->_topology->_Sol[k])(iXDof); } } // *** Gauss point loop *** for(unsigned ig = 0; ig < msh->_finiteElement[ielGeom][solType]->GetGaussPointNumber(); ig++) { msh->_finiteElement[ielGeom][solType]->Jacobian(x, ig, weight, phi, phi_x); std::vector < std::vector < adept::adouble > > gradSolDx(dim); for(unsigned k = 0; k < dim; k++) { gradSolDx[k].assign(dim, 0.); } for(unsigned i = 0; i < nxDofs; i++) { for(unsigned j = 0; j < dim; j++) { for(unsigned k = 0; k < dim; k++) { gradSolDx[k][j] += (x[k][i] + solDx[k][i]) * phi_x[i * dim + j]; } } } for(unsigned i = 0; i < nxDofs; i++) { for(unsigned k = 0; k < dim; k++) { adept::adouble term = 0.; term += phi_x[i * dim + k] * (gradSolDx[k][k]); aResDx[k][i] += term * weight; } } } // end gauss point loop //-------------------------------------------------------------------------------------------------------- // Add the local Matrix/Vector into the global Matrix/Vector //copy the value of the adept::adoube aRes in double Res and store for(int k = 0; k < dim; k++) { for(int i = 0; i < nxDofs; i++) { Res[ k * nxDofs + i] = -aResDx[k][i].value(); } } RES->add_vector_blocked(Res, SYSDOF); Jac.resize((dim * nxDofs) * (dim * nxDofs)); // define the dependent variables for(int k = 0; k < dim; k++) { s.dependent(&aResDx[k][0], nxDofs); } // define the dependent variables for(int k = 0; k < dim; k++) { s.independent(&solDx[k][0], nxDofs); } // get the jacobian matrix (ordered by row) s.jacobian(&Jac[0], true); KK->add_matrix_blocked(Jac, SYSDOF, SYSDOF); s.clear_independents(); s.clear_dependents(); } //end element loop for each process RES->close(); KK->close(); counter++; // ***************** END ASSEMBLY ******************* }
saikanth88/femus
applications/Conformal/ex7/ex7.cpp
C++
lgpl-2.1
37,597
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Assistant of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qhelpdatainterface_p.h" QT_BEGIN_NAMESPACE /*! \internal \class QHelpDataContentItem \since 4.4 \brief The QHelpDataContentItem class provides an item which represents a topic or section of the contents. Every item holds several pieces of information, most notably the title which can later be displayed in a contents overview. The reference is used to store a relative file link to the corresponding section in the documentation. */ /*! Constructs a new content item with \a parent as parent item. The constucted item has the title \a title and links to the location specified by \a reference. */ QHelpDataContentItem::QHelpDataContentItem(QHelpDataContentItem *parent, const QString &title, const QString &reference) : m_title(title), m_reference(reference) { if (parent) parent->m_children.append(this); } /*! Destructs the item and its children. */ QHelpDataContentItem::~QHelpDataContentItem() { qDeleteAll(m_children); } /*! Returns the title of the item. */ QString QHelpDataContentItem::title() const { return m_title; } /*! Returns the file reference of the item. */ QString QHelpDataContentItem::reference() const { return m_reference; } /*! Returns a list of all its child items. */ QList<QHelpDataContentItem*> QHelpDataContentItem::children() const { return m_children; } bool QHelpDataIndexItem::operator==(const QHelpDataIndexItem & other) const { return (other.name == name) && (other.reference == reference); } /*! \internal \class QHelpDataFilterSection \since 4.4 */ /*! Constructs a help data filter section. */ QHelpDataFilterSection::QHelpDataFilterSection() { d = new QHelpDataFilterSectionData(); } /*! Adds the filter attribute \a filter to the filter attributes of this section. */ void QHelpDataFilterSection::addFilterAttribute(const QString &filter) { d->filterAttributes.append(filter); } /*! Returns a list of all filter attributes defined for this section. */ QStringList QHelpDataFilterSection::filterAttributes() const { return d->filterAttributes; } /*! Adds the index item \a index to the list of indices. */ void QHelpDataFilterSection::addIndex(const QHelpDataIndexItem &index) { d->indices.append(index); } /*! Sets the filter sections list of indices to \a indices. */ void QHelpDataFilterSection::setIndices(const QList<QHelpDataIndexItem> &indices) { d->indices = indices; } /*! Returns the list of indices. */ QList<QHelpDataIndexItem> QHelpDataFilterSection::indices() const { return d->indices; } /*! Adds the top level content item \a content to the filter section. */ void QHelpDataFilterSection::addContent(QHelpDataContentItem *content) { d->contents.append(content); } /*! Sets the list of top level content items of the filter section to \a contents. */ void QHelpDataFilterSection::setContents(const QList<QHelpDataContentItem*> &contents) { qDeleteAll(d->contents); d->contents = contents; } /*! Returns a list of top level content items. */ QList<QHelpDataContentItem*> QHelpDataFilterSection::contents() const { return d->contents; } /*! Adds the file \a file to the filter section. */ void QHelpDataFilterSection::addFile(const QString &file) { d->files.append(file); } /*! Set the list of files to \a files. */ void QHelpDataFilterSection::setFiles(const QStringList &files) { d->files = files; } /*! Returns the list of files. */ QStringList QHelpDataFilterSection::files() const { return d->files; } /*! \internal \class QHelpDataInterface \since 4.4 */ /*! \fn QHelpDataInterface::QHelpDataInterface() Constructs a new help data interface. */ /*! \fn QHelpDataInterface::~QHelpDataInterface() Destroys the help data interface. */ /*! \fn QString QHelpDataInterface::namespaceName() const = 0 Returns the namespace name of the help data set. */ /*! \fn QString QHelpDataInterface::virtualFolder() const = 0 Returns the virtual folder of the help data set. */ /*! \fn QList<QHelpDataCustomFilter> QHelpDataInterface::customFilters () const = 0 Returns a list of custom filters. Defining custom filters is optional. */ /*! \fn QList<QHelpDataFilterSection> QHelpDataInterface::filterSections() const = 0 Returns a list of filter sections. */ /*! \fn QMap<QString, QVariant> QHelpDataInterface::metaData() const = 0 Returns a map of meta data. A meta data item can hold almost any data and is identified by its name. */ /*! \fn QString QHelpDataInterface::rootPath() const = 0 Returns the root file path of the documentation data. All referenced file path or links of content items are relative to this path. */ QT_END_NAMESPACE
RLovelett/qt
tools/assistant/lib/qhelpdatainterface.cpp
C++
lgpl-2.1
6,865
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PyQtawesome(PythonPackage): """FontAwesome icons in PyQt and PySide applications""" homepage = "https://github.com/spyder-ide/qtawesome" url = "https://pypi.io/packages/source/Q/QtAwesome/QtAwesome-0.4.1.tar.gz" version('0.4.1', 'bf93df612a31f3b501d751fc994c1b05') version('0.3.3', '830677aa6ca4e7014e228147475183d3') depends_on('py-setuptools', type='build') depends_on('py-qtpy', type=('build', 'run')) depends_on('py-six', type=('build', 'run'))
TheTimmy/spack
var/spack/repos/builtin/packages/py-qtawesome/package.py
Python
lgpl-2.1
1,759
/* * Copyright (C) 2003 Tommi Maekitalo * * This library 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <iostream> #include <cxxtools/directory.h> #include <cxxtools/fileinfo.h> #include <cxxtools/arg.h> #include <iterator> int main(int argc, char* argv[]) { try { cxxtools::Arg<bool> longdir(argc, argv, 'l'); cxxtools::Arg<bool> showHidden(argc, argv, 'h'); for (int a = 1; a < argc; ++a) { std::cout << "directory content of \"" << argv[a] << "\":\n"; cxxtools::Directory d(argv[a]); for (cxxtools::Directory::const_iterator it = d.begin(!showHidden); it != d.end(); ++it) { if (longdir) { cxxtools::FileInfo fi(it); switch (fi.type()) { case cxxtools::FileInfo::Directory: std::cout << 'D'; break; case cxxtools::FileInfo::File: std::cout << '-'; break; case cxxtools::FileInfo::Chardev: std::cout << 'C'; break; case cxxtools::FileInfo::Blockdev: std::cout << 'B'; break; case cxxtools::FileInfo::Fifo: std::cout << 'F'; break; case cxxtools::FileInfo::Symlink: std::cout << 'S'; break; default: std::cout << '?'; break; } std::cout << '\t' << fi.size() << '\t' << fi.name() << '\n'; } else { std::cout << *it << '\n'; } } } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }
OlafRadicke/cxxtools
demo/dir.cpp
C++
lgpl-2.1
2,778
/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. 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 net.gleamynode.apiviz.d; /** * @apiviz.category checkNonconfigredCategory4 * @author bsneade */ public class CheckNonconfiguredCategory4 { }
pub-burrito/apiviz-doclava
src/test/java/net/gleamynode/apiviz/d/CheckNonconfiguredCategory4.java
Java
lgpl-2.1
1,170
package railo.commons.io.res; import java.io.IOException; import java.io.Serializable; import java.util.Map; /** * Interface for resource provider, loaded by "Resources", * classes that implement a provider that produce resources, that match given path. * */ public interface ResourceProvider extends Serializable { /** * this class is called by the "Resources" at startup * @param scheme of the provider (can be "null") * @param arguments initals argument (can be "null") */ public ResourceProvider init(String scheme, Map arguments); /** * return a resource that match given path * @param path * @return matching resource to path */ public Resource getResource(String path); /** * returns the scheme of the resource * @return scheme */ public String getScheme(); /** * returns the arguments defined for this resource * @return scheme */ public Map<String,String> getArguments(); public void setResources(Resources resources); public void unlock(Resource res); public void lock(Resource res) throws IOException; public void read(Resource res) throws IOException; /** * returns if the resources of the provider are case-sensitive or not * @return is resource case-sensitive or not */ public boolean isCaseSensitive(); /** * returns if the resource support mode for his resources * @return is mode supported or not */ public boolean isModeSupported(); /** * returns if the resource support attributes for his resources * @return is attributes supported or not */ public boolean isAttributesSupported(); }
modius/railo
railo-java/railo-loader/src/railo/commons/io/res/ResourceProvider.java
Java
lgpl-2.1
1,709
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library 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 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 * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser 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 */ package org.opencms.ade.sitemap.shared; import com.google.gwt.user.client.rpc.IsSerializable; /** * A data class which is used to transfer information about sub-sitemaps which have * been created.<p> * * @since 8.0.0 */ public class CmsSubSitemapInfo implements IsSerializable { /** The path of the newly created sitemap. */ private CmsClientSitemapEntry m_entry; /** The 'last modified' time of the parent sitemap. */ private long m_timestamp; /** * Constructor.<p> * * @param entry the entry of the newly created sub sitemap * @param timestamp the 'last modified' time of the parent sitemap */ public CmsSubSitemapInfo(CmsClientSitemapEntry entry, long timestamp) { m_timestamp = timestamp; m_entry = entry; } /** * Hidden default constructor.<p> */ protected CmsSubSitemapInfo() { // hidden default constructor } /** * Returns the entry of the newly created sitemap.<p> * * @return the entry of the newly created sitemap */ public CmsClientSitemapEntry getEntry() { return m_entry; } /** * Returns the last modification time of the parent sitemap.<p> * * @return the last modification time of the parent sitemap */ public long getParentTimestamp() { return m_timestamp; } }
ggiudetti/opencms-core
src/org/opencms/ade/sitemap/shared/CmsSubSitemapInfo.java
Java
lgpl-2.1
2,493
/** * Copyright (c) 2014, the Railo Company Ltd. * Copyright (c) 2015, Lucee Assosication Switzerland * * This library 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ package lucee.runtime.gateway; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import lucee.loader.engine.CFMLEngine; import lucee.loader.engine.CFMLEngineFactory; import lucee.runtime.exp.PageException; import lucee.runtime.type.Struct; import lucee.runtime.util.Cast; import lucee.runtime.util.Creation; public class SocketGateway implements Gateway { private GatewayEngine engine; private int port; private String welcomeMessage="Welcome to the Lucee Socket Gateway"; private String id; private CFMLEngine cfmlEngine; private Cast caster; private Creation creator; private List<SocketServerThread> sockets=new ArrayList<SocketServerThread>(); private ServerSocket serverSocket; protected int state=STOPPED; private String cfcPath; @Override public void init(GatewayEngine engine, String id, String cfcPath, Map config)throws GatewayException { this.engine=engine; cfmlEngine=CFMLEngineFactory.getInstance(); caster=cfmlEngine.getCastUtil(); creator = cfmlEngine.getCreationUtil(); this.cfcPath=cfcPath; this.id=id; // config Object oPort=config.get("port"); port=caster.toIntValue(oPort, 1225); Object oWM=config.get("welcomeMessage"); String strWM=caster.toString(oWM,"").trim(); if(strWM.length()>0)welcomeMessage=strWM; } @Override public void doStart() { state = STARTING; try { createServerSocket(); state = RUNNING; do { try { SocketServerThread sst = new SocketServerThread(serverSocket.accept()); sst.start(); sockets.add(sst); } catch (Throwable t) { error("Failed to listen on Socket ["+id+"] on port ["+port+"]: " + t.getMessage()); } } while (getState()==RUNNING || getState()==STARTING); close(serverSocket); serverSocket = null; } catch (Throwable e) { state=FAILED; error("Error in Socet Gateway ["+id+"]: " + e.getMessage()); e.printStackTrace(); //throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(e); } } @Override public void doStop() { state = STOPPING; try{ // close all open connections Iterator<SocketServerThread> it = sockets.iterator(); while (it.hasNext()) { close(it.next().socket); } // close server socket close(serverSocket); serverSocket = null; state = STOPPED; } catch(Throwable e){ state=FAILED; error("Error in Socket Gateway ["+id+"]: " + e.getMessage()); e.printStackTrace(); //throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(e); } } private void createServerSocket() throws PageException, RuntimeException { try { serverSocket = new ServerSocket(port); } catch (Throwable t) { error("Failed to start Socket Gateway ["+id+"] on port ["+port+"] " +t.getMessage()); throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(t); } } private void invokeListener(String line, String originatorID) { Struct data=creator.createStruct(); data.setEL(creator.createKey("message"), line); Struct event=creator.createStruct(); event.setEL(creator.createKey("data"), data); event.setEL(creator.createKey("originatorID"), originatorID); event.setEL(creator.createKey("cfcMethod"), "onIncomingMessage"); event.setEL(creator.createKey("cfcTimeout"), new Double(10)); event.setEL(creator.createKey("cfcPath"), cfcPath); event.setEL(creator.createKey("gatewayType"), "Socket"); event.setEL(creator.createKey("gatewayId"), id); if (engine.invokeListener(this, "onIncomingMessage", event)) info("Socket Gateway Listener ["+id+"] invoked."); else error("Failed to call Socket Gateway Listener ["+id+"]"); } private class SocketServerThread extends Thread { private Socket socket; private PrintWriter out; private String _id; public SocketServerThread(Socket socket) throws IOException { this.socket = socket; out = new PrintWriter(socket.getOutputStream(), true); this._id=String.valueOf(hashCode()); } @Override public void run() { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println(welcomeMessage); out.print("> "); String line; while ((line = in.readLine()) != null) { if (line.trim().equals("exit")) break; invokeListener(line,_id); } //socketRegistry.remove(this.getName()); } catch (Throwable t) { error("Failed to read from Socket Gateway ["+id+"]: " + t.getMessage()); } finally{ close(out); out=null; close(in); close(socket); sockets.remove(this); } } public void writeOutput(String str) { out.println(str); out.print("> "); } } @Override public String sendMessage(Map _data) { Struct data=caster.toStruct(_data, null, false); String msg = (String) data.get("message",null); String originatorID=(String) data.get("originatorID",null); String status="OK"; if (msg!=null ) { Iterator<SocketServerThread> it = sockets.iterator(); SocketServerThread sst; try { boolean hasSend=false; while(it.hasNext()){ sst=it.next(); if(originatorID!=null && !sst._id.equalsIgnoreCase(originatorID)) continue; sst.writeOutput(msg); hasSend=true; } if(!hasSend) { if(sockets.size()==0) { error("There is no connection"); status = "EXCEPTION"; } else { it = sockets.iterator(); StringBuilder sb=new StringBuilder(); while(it.hasNext()){ if(sb.length()>0) sb.append(", "); sb.append(it.next()._id); } error("There is no connection with originatorID ["+originatorID+"], available originatorIDs are ["+sb+"]"); status = "EXCEPTION"; } } } catch (Exception e) { e.printStackTrace(); error("Failed to send message with exception: " + e.toString()); status = "EXCEPTION"; } } return status; } @Override public void doRestart() { doStop(); doStart(); } @Override public String getId() { return id; } @Override public int getState() { return state; } @Override public Object getHelper() { return null; } public void info(String msg) { engine.log(this,GatewayEngine.LOGLEVEL_INFO,msg); } public void error(String msg) { engine.log(this,GatewayEngine.LOGLEVEL_ERROR,msg); } private void close(Writer writer) { if(writer==null) return; try{ writer.close(); } catch(Throwable t){} } private void close(Reader reader) { if(reader==null) return; try{ reader.close(); } catch(Throwable t){} } private void close(Socket socket) { if(socket==null) return; try{ socket.close(); } catch(Throwable t){} } private void close(ServerSocket socket) { if(socket==null) return; try{ socket.close(); } catch(Throwable t){} } }
lucee/unoffical-Lucee-no-jre
source/java/core/src/lucee/runtime/gateway/SocketGateway.java
Java
lgpl-2.1
8,962
/******************************************************************************* * Copyright (c) 2005, Kobrix Software, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Borislav Iordanov - initial API and implementation * Murilo Saraiva de Queiroz - initial API and implementation ******************************************************************************/ package disko; public class ParagraphAnn extends BaseAnn { private static final long serialVersionUID = -5576127475742461696L; private String paragraph; public ParagraphAnn() { } public ParagraphAnn(int start, int end) { super(start, end); } public ParagraphAnn(int start, int end, String paragraph) { super(start, end); this.paragraph = paragraph; } public String getParagraph() { return paragraph; } public void setParagraph(String paragraph) { this.paragraph = paragraph; } public String toString() { int max = Math.min(getParagraph().length(), 50); String s = getParagraph().substring(0, max); if (getParagraph().length() > max) s += "..."; return super.toString() + ": " + s; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((paragraph == null) ? 0 : paragraph.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final ParagraphAnn other = (ParagraphAnn) obj; if (paragraph == null) { if (other.paragraph != null) return false; } else if (!paragraph.equals(other.paragraph)) return false; return true; } }
elaatifi/disko
src/java/disko/ParagraphAnn.java
Java
lgpl-2.1
2,235
/* * Created on 02-dic-2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package org.herac.tuxguitar.app.view.menu.impl; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.herac.tuxguitar.app.TuxGuitar; import org.herac.tuxguitar.app.action.impl.transport.TGTransportCountDownAction; import org.herac.tuxguitar.app.action.impl.transport.TGTransportMetronomeAction; import org.herac.tuxguitar.app.action.impl.transport.TGOpenTransportModeDialogAction; import org.herac.tuxguitar.app.action.impl.transport.TGTransportPlayAction; import org.herac.tuxguitar.app.action.impl.transport.TGTransportSetLoopEHeaderAction; import org.herac.tuxguitar.app.action.impl.transport.TGTransportSetLoopSHeaderAction; import org.herac.tuxguitar.app.action.impl.transport.TGTransportStopAction; import org.herac.tuxguitar.app.view.menu.TGMenuItem; import org.herac.tuxguitar.player.base.MidiPlayerMode; import org.herac.tuxguitar.song.models.TGMeasure; /** * @author julian * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class TransportMenuItem extends TGMenuItem{ private static final int STATUS_STOPPED = 1; private static final int STATUS_PAUSED = 2; private static final int STATUS_RUNNING = 3; private MenuItem transportMenuItem; private Menu menu; private MenuItem play; private MenuItem stop; private MenuItem metronome; private MenuItem countDown; private MenuItem mode; private MenuItem loopSHeader; private MenuItem loopEHeader; private int status; public TransportMenuItem(Shell shell,Menu parent, int style) { this.transportMenuItem = new MenuItem(parent, style); this.menu = new Menu(shell, SWT.DROP_DOWN); } public void showItems(){ this.play = new MenuItem(this.menu,SWT.PUSH); this.play.addSelectionListener(this.createActionProcessor(TGTransportPlayAction.NAME)); this.stop = new MenuItem(this.menu, SWT.PUSH); this.stop.addSelectionListener(this.createActionProcessor(TGTransportStopAction.NAME)); //--SEPARATOR-- new MenuItem(this.menu, SWT.SEPARATOR); this.metronome = new MenuItem(this.menu, SWT.CHECK); this.metronome.addSelectionListener(this.createActionProcessor(TGTransportMetronomeAction.NAME)); this.countDown = new MenuItem(this.menu, SWT.CHECK); this.countDown.addSelectionListener(this.createActionProcessor(TGTransportCountDownAction.NAME)); this.mode = new MenuItem(this.menu, SWT.PUSH); this.mode.addSelectionListener(this.createActionProcessor(TGOpenTransportModeDialogAction.NAME)); //--SEPARATOR-- new MenuItem(this.menu, SWT.SEPARATOR); this.loopSHeader = new MenuItem(this.menu, SWT.CHECK); this.loopSHeader.addSelectionListener(this.createActionProcessor(TGTransportSetLoopSHeaderAction.NAME)); this.loopEHeader = new MenuItem(this.menu, SWT.CHECK); this.loopEHeader.addSelectionListener(this.createActionProcessor(TGTransportSetLoopEHeaderAction.NAME)); this.transportMenuItem.setMenu(this.menu); this.status = STATUS_STOPPED; this.loadIcons(); this.loadProperties(); } public void update(){ TGMeasure measure = TuxGuitar.getInstance().getTablatureEditor().getTablature().getCaret().getMeasure(); MidiPlayerMode pm = TuxGuitar.getInstance().getPlayer().getMode(); this.metronome.setSelection(TuxGuitar.getInstance().getPlayer().isMetronomeEnabled()); this.countDown.setSelection(TuxGuitar.getInstance().getPlayer().getCountDown().isEnabled()); this.loopSHeader.setEnabled( pm.isLoop() ); this.loopSHeader.setSelection( measure != null && measure.getNumber() == pm.getLoopSHeader() ); this.loopEHeader.setEnabled( pm.isLoop() ); this.loopEHeader.setSelection( measure != null && measure.getNumber() == pm.getLoopEHeader() ); this.loadIcons(false); } public void loadProperties(){ setMenuItemTextAndAccelerator(this.transportMenuItem, "transport", null); setMenuItemTextAndAccelerator(this.play, "transport.start", TGTransportPlayAction.NAME); setMenuItemTextAndAccelerator(this.stop, "transport.stop", TGTransportStopAction.NAME); setMenuItemTextAndAccelerator(this.mode, "transport.mode", TGOpenTransportModeDialogAction.NAME); setMenuItemTextAndAccelerator(this.metronome, "transport.metronome", TGTransportMetronomeAction.NAME); setMenuItemTextAndAccelerator(this.countDown, "transport.count-down", TGTransportCountDownAction.NAME); setMenuItemTextAndAccelerator(this.loopSHeader, "transport.set-loop-start", TGTransportSetLoopSHeaderAction.NAME); setMenuItemTextAndAccelerator(this.loopEHeader, "transport.set-loop-end", TGTransportSetLoopEHeaderAction.NAME); } public void loadIcons(){ this.loadIcons(true); this.mode.setImage(TuxGuitar.getInstance().getIconManager().getTransportMode()); this.metronome.setImage(TuxGuitar.getInstance().getIconManager().getTransportMetronome()); } public void loadIcons(boolean force){ int lastStatus = this.status; if(TuxGuitar.getInstance().getPlayer().isRunning()){ this.status = STATUS_RUNNING; }else if(TuxGuitar.getInstance().getPlayer().isPaused()){ this.status = STATUS_PAUSED; }else{ this.status = STATUS_STOPPED; } if(force || lastStatus != this.status){ if(this.status == STATUS_RUNNING){ this.stop.setImage(TuxGuitar.getInstance().getIconManager().getTransportIconStop2()); this.play.setImage(TuxGuitar.getInstance().getIconManager().getTransportIconPause()); }else if(this.status == STATUS_PAUSED){ this.stop.setImage(TuxGuitar.getInstance().getIconManager().getTransportIconStop2()); this.play.setImage(TuxGuitar.getInstance().getIconManager().getTransportIconPlay2()); }else if(this.status == STATUS_STOPPED){ this.stop.setImage(TuxGuitar.getInstance().getIconManager().getTransportIconStop1()); this.play.setImage(TuxGuitar.getInstance().getIconManager().getTransportIconPlay1()); } } } }
bluenote10/TuxguitarParser
tuxguitar-src/TuxGuitar/src/org/herac/tuxguitar/app/view/menu/impl/TransportMenuItem.java
Java
lgpl-2.1
6,077
//----------------------------------------------------------- // // Copyright (C) 2015 by the deal2lkit authors // // This file is part of the deal2lkit library. // // The deal2lkit library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal2lkit distribution. // //----------------------------------------------------------- #include "../tests.h" #include <deal2lkit/error_handler.h> #include <deal2lkit/parsed_grid_generator.h> #include <deal.II/base/function_lib.h> #include <deal.II/base/conditional_ostream.h> #include <deal.II/fe/fe_q.h> #include <deal.II/dofs/dof_handler.h> using namespace deal2lkit; int main () { initlog(); ParsedGridGenerator<2> gg; ErrorHandler<> eh; // Only one table ParameterAcceptor::initialize(); auto tria = gg.serial(); FE_Q<2> fe(1); DoFHandler<2> dh(*tria); for (unsigned int i=0; i<5; ++i) { tria->refine_global(1); dh.distribute_dofs(fe); Vector<double> sol(dh.n_dofs()); VectorTools::interpolate(dh, Functions::CosineFunction<2>(1), sol); eh.error_from_exact(dh, sol, Functions::CosineFunction<2>(1)); } ConditionalOStream pout1(deallog.get_file_stream(), true); ConditionalOStream pout2(deallog.get_file_stream(), false); deallog.get_file_stream() << " CONDITION: True" << std::endl; eh.output_table(pout1); deallog.get_file_stream() << " CONDITION: False" << std::endl; eh.output_table(pout2); }
asartori86/dealii-sak
tests/error_handler/error_handler_02.cc
C++
lgpl-2.1
1,741
/************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "todooutputtreeviewdelegate.h" #include "constants.h" namespace Todo { namespace Internal { TodoOutputTreeViewDelegate::TodoOutputTreeViewDelegate(QObject *parent) : QStyledItemDelegate(parent) { } void TodoOutputTreeViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem newOption = option; newOption.textElideMode = index.column() == Constants::OUTPUT_COLUMN_FILE ? Qt::ElideLeft : Qt::ElideRight; QStyledItemDelegate::paint(painter, newOption, index); } } // namespace Internal } // namespace Todo
martyone/sailfish-qtcreator
src/plugins/todo/todooutputtreeviewdelegate.cpp
C++
lgpl-2.1
2,123
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "QSofaMainWindow.h" #include "QSofaViewer.h" #include <QMessageBox> #include <QAction> #include <QMenu> #include <QMenuBar> #include <QToolBar> #include <QStyle> #include <QFileDialog> #include <QString> #include <iostream> #include <QSpinBox> #include <QDockWidget> #include "oneTetra.h" using std::cout; using std::endl; QSofaMainWindow::QSofaMainWindow(QWidget *parent) : QMainWindow(parent) { setFocusPolicy(Qt::ClickFocus); mainViewer = new QSofaViewer(&sofaScene,NULL,this); setCentralWidget(mainViewer); QToolBar* toolbar = addToolBar(tr("Controls")); QMenu* fileMenu = menuBar()->addMenu(tr("&File")); QMenu* simulationMenu = menuBar()->addMenu(tr("&Simulation")); QMenu* viewMenu = menuBar()->addMenu(tr("&View")); // find icons at https://www.iconfinder.com/search // start/stop { _playPauseAct = new QAction(QIcon(":/icons/start.svg"), tr("&Play..."), this); _playPauseAct->setIcon(this->style()->standardIcon(QStyle::SP_MediaPlay)); _playPauseAct->setShortcut(QKeySequence(Qt::Key_Space)); _playPauseAct->setToolTip(tr("Play/Pause simulation")); connect(_playPauseAct, SIGNAL(triggered()), &sofaScene, SLOT(playpause())); connect(&sofaScene, SIGNAL(sigPlaying(bool)), this, SLOT(isPlaying(bool)) ); this->addAction(_playPauseAct); simulationMenu->addAction(_playPauseAct); toolbar->addAction(_playPauseAct); } // reset { QAction* resetAct = new QAction(QIcon(":/icons/reset.svg"), tr("&Reset..."), this); resetAct->setIcon(this->style()->standardIcon(QStyle::SP_MediaSkipBackward)); resetAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_R)); resetAct->setToolTip(tr("Restart from the beginning, without reloading")); connect(resetAct, SIGNAL(triggered()), &sofaScene, SLOT(reset())); this->addAction(resetAct); simulationMenu->addAction(resetAct); toolbar->addAction(resetAct); } // open { QAction* openAct = new QAction(QIcon(":/icons/reset.svg"), tr("&Open..."), this); openAct->setIcon(this->style()->standardIcon(QStyle::SP_FileIcon)); openAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_O)); openAct->setToolTip(tr("Open new scene")); openAct->setStatusTip(tr("Opening scene…")); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); this->addAction(openAct); fileMenu->addAction(openAct); toolbar->addAction(openAct); } // time step { QSpinBox* spinBox = new QSpinBox(this); toolbar->addWidget(spinBox); spinBox->setValue(40); spinBox->setMaximum(40000); spinBox->setToolTip(tr("Simulation time step (ms)")); connect(spinBox,SIGNAL(valueChanged(int)), this, SLOT(setDt(int))); } // reload { QAction* reloadAct = new QAction(QIcon(":/icons/reload.svg"), tr("&Reload..."), this); reloadAct->setIcon(this->style()->standardIcon(QStyle::SP_BrowserReload)); reloadAct->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_R)); reloadAct->setStatusTip(tr("Reloading scene…")); reloadAct->setToolTip(tr("Reload file and restart from the beginning")); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); this->addAction(reloadAct); fileMenu->addAction(reloadAct); // toolbar->addAction(reloadAct); } // viewAll { QAction* viewAllAct = new QAction(QIcon(":/icons/eye.svg"), tr("&ViewAll..."), this); viewAllAct->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_V)); viewAllAct->setToolTip(tr("Adjust camera to view all")); connect(viewAllAct, SIGNAL(triggered()), mainViewer, SLOT(viewAll())); this->addAction(viewAllAct); simulationMenu->addAction(viewAllAct); toolbar->addAction(viewAllAct); } // print { QAction* printAct = new QAction( QIcon(":/icons/print.svg"), tr("&PrintGraph..."), this); printAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_P)); printAct->setToolTip(tr("Print the graph on the standard output")); connect(printAct, SIGNAL(triggered()), &sofaScene, SLOT(printGraph())); this->addAction(printAct); simulationMenu->addAction(printAct); toolbar->addAction(printAct); } // { // QAction* toggleFullScreenAct = new QAction( tr("&FullScreen"), this ); // toggleFullScreenAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_F)); // toggleFullScreenAct->setToolTip(tr("Show full screen")); // connect(toggleFullScreenAct, SIGNAL(triggered()), this, SLOT(toggleFullScreen())); // this->addAction(toggleFullScreenAct); // viewMenu->addAction(toggleFullScreenAct); // toolbar->addAction(toggleFullScreenAct); // _fullScreen = false; // } { QAction* createAdditionalViewerAct = new QAction( tr("&Additional viewer"), this ); createAdditionalViewerAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_V)); createAdditionalViewerAct->setToolTip(tr("Add/remove additional viewer")); connect(createAdditionalViewerAct, SIGNAL(triggered()), this, SLOT(createAdditionalViewer())); this->addAction(createAdditionalViewerAct); viewMenu->addAction(createAdditionalViewerAct); toolbar->addAction(createAdditionalViewerAct); } //======================================= mainViewer->setFocus(); } void QSofaMainWindow::initSofa(string fileName ) { // --- Init sofa --- if(fileName.empty()) { cout << "no fileName provided, using default scene" << endl; oneTetra(); //sofaScene.setScene(oneTetra()); // the sofa::Simulation is a singleton, the call to oneTetra already loaded the scene } else { sofaScene.open(fileName.c_str()); } QMessageBox::information( this, tr("Tip"), tr("Space to start/stop,\n\n" "Shift-Click and drag the control points to interact. Use Ctrl-Shift-Click to select Interactors only\n" "Release button before Shift to release the control point.\n" "Release Shift before button to keep it attached where it is.") ); } void QSofaMainWindow::isPlaying( bool playing ) { if( playing ) // propose to pause _playPauseAct->setIcon(this->style()->standardIcon(QStyle::SP_MediaPause)); else // propose to play _playPauseAct->setIcon(this->style()->standardIcon(QStyle::SP_MediaPlay)); } void QSofaMainWindow::open() { sofaScene.pause(); std::string path = std::string(QTSOFA_SRC_DIR) + "/../examples"; _fileName = QFileDialog::getOpenFileName(this, tr("Open scene file"), path.c_str(), tr("Scene Files (*.scn *.xml *.py)")); if( _fileName.size()>0 ) sofaScene.open(_fileName.toStdString().c_str()); } void QSofaMainWindow::reload() { if( _fileName.size()==0 ) { QMessageBox::information( this, tr("Error"), tr("No file to reload") ); return; } sofaScene.open(_fileName.toStdString().c_str()); } void QSofaMainWindow::setDt( int milis ) { sofaScene.setTimeStep( milis/1000.0 ); } void QSofaMainWindow::toggleFullScreen() { _fullScreen = !_fullScreen; if( _fullScreen ){ this->showFullScreen(); } else { this->showNormal(); } } void QSofaMainWindow::createAdditionalViewer() { QSofaViewer* additionalViewer = new QSofaViewer(&sofaScene, mainViewer, this); QDockWidget* additionalViewerDock = new QDockWidget(tr("Additional Viewer"), this); additionalViewerDock->setWidget(additionalViewer); addDockWidget(Qt::LeftDockWidgetArea, additionalViewerDock); }
Anatoscope/sofa
applications/projects/qtSofa/QSofaMainWindow.cpp
C++
lgpl-2.1
9,524
package beast.evolution.operators; import java.text.DecimalFormat; import beast.core.Description; import beast.core.Input; import beast.core.Input.Validate; import beast.core.Operator; import beast.core.parameter.RealParameter; import beast.util.Randomizer; @Description("A random walk operator that selects a random dimension of the real parameter and perturbs the value a " + "random amount within +/- windowSize.") public class RealRandomWalkOperator extends Operator { final public Input<Double> windowSizeInput = new Input<>("windowSize", "the size of the window both up and down when using uniform interval OR standard deviation when using Gaussian", Input.Validate.REQUIRED); final public Input<RealParameter> parameterInput = new Input<>("parameter", "the parameter to operate a random walk on.", Validate.REQUIRED); final public Input<Boolean> useGaussianInput = new Input<>("useGaussian", "Use Gaussian to move instead of uniform interval. Default false.", false); double windowSize = 1; boolean useGaussian; @Override public void initAndValidate() { windowSize = windowSizeInput.get(); useGaussian = useGaussianInput.get(); } /** * override this for proposals, * returns log of hastingRatio, or Double.NEGATIVE_INFINITY if proposal should not be accepted * */ @Override public double proposal() { RealParameter param = parameterInput.get(this); int i = Randomizer.nextInt(param.getDimension()); double value = param.getValue(i); double newValue = value; if (useGaussian) { newValue += Randomizer.nextGaussian() * windowSize; } else { newValue += Randomizer.nextDouble() * 2 * windowSize - windowSize; } if (newValue < param.getLower() || newValue > param.getUpper()) { return Double.NEGATIVE_INFINITY; } if (newValue == value) { // this saves calculating the posterior return Double.NEGATIVE_INFINITY; } param.setValue(i, newValue); return 0.0; } @Override public double getCoercableParameterValue() { return windowSize; } @Override public void setCoercableParameterValue(double value) { windowSize = value; } /** * called after every invocation of this operator to see whether * a parameter can be optimised for better acceptance hence faster * mixing * * @param logAlpha difference in posterior between previous state & proposed state + hasting ratio */ @Override public void optimize(double logAlpha) { // must be overridden by operator implementation to have an effect double delta = calcDelta(logAlpha); delta += Math.log(windowSize); windowSize = Math.exp(delta); } @Override public final String getPerformanceSuggestion() { double prob = m_nNrAccepted / (m_nNrAccepted + m_nNrRejected + 0.0); double targetProb = getTargetAcceptanceProbability(); double ratio = prob / targetProb; if (ratio > 2.0) ratio = 2.0; if (ratio < 0.5) ratio = 0.5; // new scale factor double newWindowSize = windowSize * ratio; DecimalFormat formatter = new DecimalFormat("#.###"); if (prob < 0.10) { return "Try setting window size to about " + formatter.format(newWindowSize); } else if (prob > 0.40) { return "Try setting window size to about " + formatter.format(newWindowSize); } else return ""; } } // class RealRandomWalkOperator
CompEvol/beast2
src/beast/evolution/operators/RealRandomWalkOperator.java
Java
lgpl-2.1
3,679
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.massindex.impl; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.List; import org.hibernate.CacheMode; import org.hibernate.FlushMode; import org.hibernate.LockOptions; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.ogm.loader.impl.OgmLoadingContext; import org.hibernate.ogm.loader.impl.TupleBasedEntityLoader; import org.hibernate.ogm.model.spi.Tuple; import org.hibernate.ogm.persister.impl.OgmEntityPersister; import org.hibernate.ogm.util.impl.LoggerFactory; import org.hibernate.search.backend.AddLuceneWork; import org.hibernate.search.backend.spi.BatchBackend; import org.hibernate.search.batchindexing.MassIndexerProgressMonitor; import org.hibernate.search.bridge.spi.ConversionContext; import org.hibernate.search.bridge.util.impl.ContextualExceptionBridgeHelper; import org.hibernate.search.engine.integration.impl.ExtendedSearchIntegrator; import org.hibernate.search.engine.service.spi.ServiceManager; import org.hibernate.search.engine.spi.DocumentBuilderIndexedEntity; import org.hibernate.search.engine.spi.EntityIndexBinding; import org.hibernate.search.exception.ErrorHandler; import org.hibernate.search.hcore.util.impl.HibernateHelper; import org.hibernate.search.indexes.interceptor.EntityIndexingInterceptor; import org.hibernate.search.indexes.interceptor.IndexingOverride; import org.hibernate.search.orm.loading.impl.HibernateSessionLoadingInitializer; import org.hibernate.search.spi.IndexedTypeIdentifier; import org.hibernate.search.spi.IndexedTypeMap; import org.hibernate.search.spi.InstanceInitializer; import org.hibernate.search.util.logging.impl.Log; import java.lang.invoke.MethodHandles; /** * Component of batch-indexing pipeline, using chained producer-consumers. * <p> * This Runnable will consume {@link Tuple} objects taken one-by-one and it will create an {@link AddLuceneWork} for the * corresponding entity. * * @author Sanne Grinovero * @author Davide D'Alto */ public class TupleIndexer implements SessionAwareRunnable { private static final Log log = LoggerFactory.make( Log.class, MethodHandles.lookup() ); private final SessionFactoryImplementor sessionFactory; private final IndexedTypeMap<EntityIndexBinding> entityIndexBindings; private final MassIndexerProgressMonitor monitor; private final CacheMode cacheMode; private final BatchBackend backend; private final ErrorHandler errorHandler; private final IndexedTypeIdentifier indexedTypeIdentifier; private final ServiceManager serviceManager; private final String tenantId; public TupleIndexer(IndexedTypeIdentifier indexedTypeIdentifier, MassIndexerProgressMonitor monitor, SessionFactoryImplementor sessionFactory, ExtendedSearchIntegrator searchIntegrator, CacheMode cacheMode, BatchBackend backend, ErrorHandler errorHandler, String tenantId) { this.indexedTypeIdentifier = indexedTypeIdentifier; this.monitor = monitor; this.sessionFactory = sessionFactory; this.cacheMode = cacheMode; this.backend = backend; this.errorHandler = errorHandler; this.tenantId = tenantId; //can be null when multi-tenancy isn't being used this.entityIndexBindings = searchIntegrator.getIndexBindings(); serviceManager = searchIntegrator.getServiceManager(); } private void index(Session session, Object entity) { try { final InstanceInitializer sessionInitializer = new HibernateSessionLoadingInitializer( (SessionImplementor) session ); final ConversionContext contextualBridge = new ContextualExceptionBridgeHelper(); // trick to attach the objects to session: session.buildLockRequest( LockOptions.NONE ).lock( entity ); index( entity, session, sessionInitializer, contextualBridge ); monitor.documentsBuilt( 1 ); session.clear(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } private void index(Object entity, Session session, InstanceInitializer sessionInitializer, ConversionContext conversionContext) throws InterruptedException { Class<?> clazz = HibernateHelper.getClass( entity ); EntityIndexBinding entityIndexBinding = entityIndexBindings.get( clazz ); // it might be possible to receive not-indexes subclasses of the currently indexed type; // being not-indexed, we skip them. // FIXME for improved performance: avoid loading them in an early phase. if ( entityIndexBinding != null ) { EntityIndexingInterceptor<?> interceptor = entityIndexBinding.getEntityIndexingInterceptor(); if ( isNotSkippable( interceptor, entity ) ) { Serializable id = session.getIdentifier( entity ); AddLuceneWork addWork = createAddLuceneWork( tenantId, entity, sessionInitializer, conversionContext, id, entityIndexBinding ); backend.enqueueAsyncWork( addWork ); } } } private AddLuceneWork createAddLuceneWork(String tenantIdentifier, Object entity, InstanceInitializer sessionInitializer, ConversionContext conversionContext, Serializable id, EntityIndexBinding entityIndexBinding) { DocumentBuilderIndexedEntity docBuilder = entityIndexBinding.getDocumentBuilder(); String idInString = idInString( conversionContext, id, docBuilder.getTypeIdentifier(), docBuilder ); // depending on the complexity of the object graph going to be indexed it's possible // that we hit the database several times during work construction. return docBuilder.createAddWork( tenantIdentifier, docBuilder.getTypeIdentifier(), entity, id, idInString, sessionInitializer, conversionContext ); } private String idInString(ConversionContext conversionContext, Serializable id, IndexedTypeIdentifier typeIdentifier, DocumentBuilderIndexedEntity docBuilder) { conversionContext.pushProperty( docBuilder.getIdPropertyName() ); try { String idInString = conversionContext.setConvertedTypeId( typeIdentifier ).twoWayConversionContext( docBuilder.getIdBridge() ) .objectToString( id ); return idInString; } finally { conversionContext.popProperty(); } } private boolean isNotSkippable(EntityIndexingInterceptor interceptor, Object entity) { if ( interceptor == null ) { return true; } else { return !isSkippable( interceptor.onAdd( entity ) ); } } private boolean isSkippable(IndexingOverride indexingOverride) { switch ( indexingOverride ) { case REMOVE: case SKIP: return true; default: return false; } } private Transaction beginTransaction(Session session) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { Transaction transaction = Helper.getTransactionAndMarkForJoin( session, serviceManager ); transaction.begin(); return transaction; } private Session openSession(Session upperSession) { Session session = upperSession; if ( upperSession == null ) { session = sessionFactory.openSession(); } initSession( session ); return session; } private void initSession(Session session) { session.setHibernateFlushMode( FlushMode.MANUAL ); session.setCacheMode( cacheMode ); session.setDefaultReadOnly( true ); } private void close(Session upperSession, Session session) { if ( upperSession == null ) { session.close(); } } @Override public void run(Session upperSession, Tuple tuple) { if ( upperSession == null ) { runInNewTransaction( upperSession, tuple ); } else { runIndexing( upperSession, tuple ); } } /* * Index using the existing session without opening new transactions */ private void runIndexing(Session upperSession, Tuple tuple) { initSession( upperSession ); try { index( upperSession, entity( upperSession, tuple ) ); } catch (Throwable e) { errorHandler.handleException( log.massIndexerUnexpectedErrorMessage(), e ); } finally { log.debug( "finished" ); } } private void runInNewTransaction(Session upperSession, Tuple tuple) { Session session = openSession( upperSession ); try { Transaction transaction = beginTransaction( session ); index( session, entity( session, tuple ) ); transaction.commit(); } catch ( Throwable e ) { errorHandler.handleException( log.massIndexerUnexpectedErrorMessage(), e ); } finally { close( upperSession, session ); log.debug( "finished" ); } } private Object entity(Session session, Tuple tuple) { SessionImplementor sessionImplementor = (SessionImplementor) session; OgmEntityPersister persister = (OgmEntityPersister) sessionFactory.getMetamodel().entityPersister( indexedTypeIdentifier.getPojoType() ); TupleBasedEntityLoader loader = (TupleBasedEntityLoader) persister.getAppropriateLoader( LockOptions.READ, sessionImplementor ); OgmLoadingContext ogmLoadingContext = new OgmLoadingContext(); ogmLoadingContext.setTuples( Collections.singletonList( tuple ) ); List<Object> entities = loader.loadEntitiesFromTuples( sessionImplementor, LockOptions.NONE, ogmLoadingContext ); return entities.get( 0 ); } }
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/massindex/impl/TupleIndexer.java
Java
lgpl-2.1
9,368
/* * Minecraft Forge * Copyright (c) 2016. * * This library 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 version 2.1 * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.client; import static net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType.BOSSINFO; import static net.minecraftforge.common.ForgeVersion.Status.BETA; import static net.minecraftforge.common.ForgeVersion.Status.BETA_OUTDATED; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL20.*; import java.awt.image.BufferedImage; import java.io.File; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.util.Collections; import java.util.Map; import javax.annotation.Nonnull; import javax.vecmath.Matrix3f; import javax.vecmath.Matrix4f; import javax.vecmath.Vector3f; import javax.vecmath.Vector4f; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.ISound; import net.minecraft.client.audio.SoundManager; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.BlockFaceUV; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.block.model.ModelManager; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.block.model.ModelRotation; import net.minecraft.client.renderer.block.model.SimpleBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraft.client.renderer.vertex.VertexFormatElement.EnumUsage; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.registry.IRegistry; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.BossInfoLerping; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraftforge.client.event.DrawBlockHighlightEvent; import net.minecraftforge.client.event.EntityViewRenderEvent; import net.minecraftforge.client.event.FOVUpdateEvent; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderHandEvent; import net.minecraftforge.client.event.RenderSpecificHandEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.event.ScreenshotEvent; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.client.event.sound.PlaySoundEvent; import net.minecraftforge.client.model.IPerspectiveAwareModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.client.model.animation.Animation; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.ForgeVersion.Status; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.model.IModelPart; import net.minecraftforge.common.model.ITransformation; import net.minecraftforge.common.model.TRSRTransformation; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.client.GuiJava8Error; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Java8VersionException; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.ModContainer; import org.apache.commons.lang3.tuple.Pair; import org.lwjgl.BufferUtils; import com.google.common.base.Optional; import com.google.common.collect.Maps; public class ForgeHooksClient { //private static final ResourceLocation ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png"); static TextureManager engine() { return FMLClientHandler.instance().getClient().renderEngine; } public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EntityEquipmentSlot slot, String type) { String result = armor.getItem().getArmorTexture(armor, entity, slot, type); return result != null ? result : _default; } //Optifine Helper Functions u.u, these are here specifically for Optifine //Note: When using Optifine, these methods are invoked using reflection, which //incurs a major performance penalty. public static void orientBedCamera(IBlockAccess world, BlockPos pos, IBlockState state, Entity entity) { Block block = state.getBlock(); if (block != null && block.isBed(state, world, pos, entity)) { glRotatef((float)(block.getBedDirection(state, world, pos).getHorizontalIndex() * 90), 0.0F, 1.0F, 0.0F); } } public static boolean onDrawBlockHighlight(RenderGlobal context, EntityPlayer player, RayTraceResult target, int subID, float partialTicks) { return MinecraftForge.EVENT_BUS.post(new DrawBlockHighlightEvent(context, player, target, subID, partialTicks)); } public static void dispatchRenderLast(RenderGlobal context, float partialTicks) { MinecraftForge.EVENT_BUS.post(new RenderWorldLastEvent(context, partialTicks)); } public static boolean renderFirstPersonHand(RenderGlobal context, float partialTicks, int renderPass) { return MinecraftForge.EVENT_BUS.post(new RenderHandEvent(context, partialTicks, renderPass)); } public static boolean renderSpecificFirstPersonHand(EnumHand hand, float partialTicks, float interpPitch, float swingProgress, float equipProgress, ItemStack stack) { return MinecraftForge.EVENT_BUS.post(new RenderSpecificHandEvent(hand, partialTicks, interpPitch, swingProgress, equipProgress, stack)); } public static void onTextureStitchedPre(TextureMap map) { MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Pre(map)); ModelLoader.White.INSTANCE.register(map); } public static void onTextureStitchedPost(TextureMap map) { MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Post(map)); } static int renderPass = -1; public static void setRenderPass(int pass) { renderPass = pass; } static final ThreadLocal<BlockRenderLayer> renderLayer = new ThreadLocal<BlockRenderLayer>(); public static void setRenderLayer(BlockRenderLayer layer) { renderLayer.set(layer); } public static ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, EntityEquipmentSlot slot, ModelBiped _default) { ModelBiped model = itemStack.getItem().getArmorModel(entityLiving, itemStack, slot, _default); return model == null ? _default : model; } //This properly moves the domain, if provided, to the front of the string before concatenating public static String fixDomain(String base, String complex) { int idx = complex.indexOf(':'); if (idx == -1) { return base + complex; } String name = complex.substring(idx + 1, complex.length()); if (idx > 1) { String domain = complex.substring(0, idx); return domain + ':' + base + name; } else { return base + name; } } public static boolean postMouseEvent() { return MinecraftForge.EVENT_BUS.post(new MouseEvent()); } public static float getOffsetFOV(EntityPlayer entity, float fov) { FOVUpdateEvent fovUpdateEvent = new FOVUpdateEvent(entity, fov); MinecraftForge.EVENT_BUS.post(fovUpdateEvent); return fovUpdateEvent.getNewfov(); } public static float getFOVModifier(EntityRenderer renderer, Entity entity, IBlockState state, double renderPartialTicks, float fov) { EntityViewRenderEvent.FOVModifier event = new EntityViewRenderEvent.FOVModifier(renderer, entity, state, renderPartialTicks, fov); MinecraftForge.EVENT_BUS.post(event); return event.getFOV(); } private static int skyX, skyZ; private static boolean skyInit; private static int skyRGBMultiplier; public static int getSkyBlendColour(World world, BlockPos center) { if (center.getX() == skyX && center.getZ() == skyZ && skyInit) { return skyRGBMultiplier; } skyInit = true; GameSettings settings = Minecraft.getMinecraft().gameSettings; int[] ranges = ForgeModContainer.blendRanges; int distance = 0; if (settings.fancyGraphics && settings.renderDistanceChunks >= 0 && settings.renderDistanceChunks < ranges.length) { distance = ranges[settings.renderDistanceChunks]; } int r = 0; int g = 0; int b = 0; int divider = 0; for (int x = -distance; x <= distance; ++x) { for (int z = -distance; z <= distance; ++z) { BlockPos pos = center.add(x, 0, z); Biome biome = world.getBiome(pos); int colour = biome.getSkyColorByTemp(biome.getFloatTemperature(pos)); r += (colour & 0xFF0000) >> 16; g += (colour & 0x00FF00) >> 8; b += colour & 0x0000FF; divider++; } } int multiplier = (r / divider & 255) << 16 | (g / divider & 255) << 8 | b / divider & 255; skyX = center.getX(); skyZ = center.getZ(); skyRGBMultiplier = multiplier; return skyRGBMultiplier; } /** * Initialization of Forge Renderers. */ static { //FluidRegistry.renderIdFluid = RenderingRegistry.getNextAvailableRenderId(); //RenderingRegistry.registerBlockHandler(RenderBlockFluid.instance); } private static int updatescrollcounter = 0; public static String renderMainMenu(GuiMainMenu gui, FontRenderer font, int width, int height, String splashText) { Status status = ForgeVersion.getStatus(); if (status == BETA || status == BETA_OUTDATED) { // render a warning at the top of the screen, String line = I18n.format("forge.update.beta.1", TextFormatting.RED, TextFormatting.RESET); gui.drawString(font, line, (width - font.getStringWidth(line)) / 2, 4 + (0 * (font.FONT_HEIGHT + 1)), -1); line = I18n.format("forge.update.beta.2"); gui.drawString(font, line, (width - font.getStringWidth(line)) / 2, 4 + (1 * (font.FONT_HEIGHT + 1)), -1); } if (!Loader.instance().java8) { String line = I18n.format("fml.messages.java8warning.1", TextFormatting.RED, TextFormatting.RESET); gui.drawString(font, line, (width - font.getStringWidth(line)) / 2, 4 + (8 * (font.FONT_HEIGHT + 1)), -1); line = I18n.format("fml.messages.java8warning.2"); gui.drawString(font, line, (width - font.getStringWidth(line)) / 2, 4 + (9 * (font.FONT_HEIGHT + 1)), -1); splashText = updatescrollcounter < 50 ? "UPDATE!" : "JAVA!"; updatescrollcounter+=1; updatescrollcounter%=100; } String line = null; switch(status) { //case FAILED: line = " Version check failed"; break; //case UP_TO_DATE: line = "Forge up to date"}; break; //case AHEAD: line = "Using non-recommended Forge build, issues may arise."}; break; case OUTDATED: case BETA_OUTDATED: line = I18n.format("forge.update.newversion", ForgeVersion.getTarget()); break; default: break; } if (line != null) { // if we have a line, render it in the bottom right, above Mojang's copyright line gui.drawString(font, line, width - font.getStringWidth(line) - 2, height - (2 * (font.FONT_HEIGHT + 1)), -1); } return splashText; } public static void mainMenuMouseClick(int mouseX, int mouseY, int mouseButton, FontRenderer font, int width) { if (!Loader.instance().java8) { if (mouseY >= (4 + (8 * 10)) && mouseY < (4 + (10 * 10))) { int w = font.getStringWidth(I18n.format("fml.messages.java8warning.1", TextFormatting.RED, TextFormatting.RESET)); w = Math.max(w, font.getStringWidth(I18n.format("fml.messages.java8warning.2"))); if (mouseX >= ((width - w) / 2) && mouseX <= ((width + w) / 2)) { FMLClientHandler.instance().showGuiScreen(new GuiJava8Error(new Java8VersionException(Collections.<ModContainer>emptyList()))); } } } } public static ISound playSound(SoundManager manager, ISound sound) { PlaySoundEvent e = new PlaySoundEvent(manager, sound); MinecraftForge.EVENT_BUS.post(e); return e.getResultSound(); } //static RenderBlocks VertexBufferRB; static int worldRenderPass; public static int getWorldRenderPass() { return worldRenderPass; } public static void drawScreen(GuiScreen screen, int mouseX, int mouseY, float partialTicks) { if (!MinecraftForge.EVENT_BUS.post(new GuiScreenEvent.DrawScreenEvent.Pre(screen, mouseX, mouseY, partialTicks))) screen.drawScreen(mouseX, mouseY, partialTicks); MinecraftForge.EVENT_BUS.post(new GuiScreenEvent.DrawScreenEvent.Post(screen, mouseX, mouseY, partialTicks)); } public static float getFogDensity(EntityRenderer renderer, Entity entity, IBlockState state, float partial, float density) { EntityViewRenderEvent.FogDensity event = new EntityViewRenderEvent.FogDensity(renderer, entity, state, partial, density); if (MinecraftForge.EVENT_BUS.post(event)) return event.getDensity(); return -1; } public static void onFogRender(EntityRenderer renderer, Entity entity, IBlockState state, float partial, int mode, float distance) { MinecraftForge.EVENT_BUS.post(new EntityViewRenderEvent.RenderFogEvent(renderer, entity, state, partial, mode, distance)); } public static void onModelBake(ModelManager modelManager, IRegistry<ModelResourceLocation, IBakedModel> modelRegistry, ModelLoader modelLoader) { MinecraftForge.EVENT_BUS.post(new ModelBakeEvent(modelManager, modelRegistry, modelLoader)); modelLoader.onPostBakeEvent(modelRegistry); } @SuppressWarnings("deprecation") public static Matrix4f getMatrix(net.minecraft.client.renderer.block.model.ItemTransformVec3f transform) { javax.vecmath.Matrix4f m = new javax.vecmath.Matrix4f(), t = new javax.vecmath.Matrix4f(); m.setIdentity(); m.setTranslation(TRSRTransformation.toVecmath(transform.translation)); t.setIdentity(); t.rotY(transform.rotation.y); m.mul(t); t.setIdentity(); t.rotX(transform.rotation.x); m.mul(t); t.setIdentity(); t.rotZ(transform.rotation.z); m.mul(t); t.setIdentity(); t.m00 = transform.scale.x; t.m11 = transform.scale.y; t.m22 = transform.scale.z; m.mul(t); return m; } private static final Matrix4f flipX; static { flipX = new Matrix4f(); flipX.setIdentity(); flipX.m00 = -1; } @SuppressWarnings("deprecation") public static IBakedModel handleCameraTransforms(IBakedModel model, ItemCameraTransforms.TransformType cameraTransformType, boolean leftHandHackery) { if(model instanceof IPerspectiveAwareModel) { Pair<? extends IBakedModel, Matrix4f> pair = ((IPerspectiveAwareModel)model).handlePerspective(cameraTransformType); if(pair.getRight() != null) { Matrix4f matrix = new Matrix4f(pair.getRight()); if(leftHandHackery) { matrix.mul(flipX, matrix); matrix.mul(matrix, flipX); } multiplyCurrentGlMatrix(matrix); } return pair.getLeft(); } else { //if(leftHandHackery) GlStateManager.scale(-1, 1, 1); ItemCameraTransforms.applyTransformSide(model.getItemCameraTransforms().getTransform(cameraTransformType), leftHandHackery); //if(leftHandHackery) GlStateManager.scale(-1, 1, 1); } return model; } private static final FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); public static void multiplyCurrentGlMatrix(Matrix4f matrix) { matrixBuf.clear(); float[] t = new float[4]; for(int i = 0; i < 4; i++) { matrix.getColumn(i, t); matrixBuf.put(t); } matrixBuf.flip(); glMultMatrix(matrixBuf); } // moved and expanded from WorldVertexBufferUploader.draw public static void preDraw(EnumUsage attrType, VertexFormat format, int element, int stride, ByteBuffer buffer) { VertexFormatElement attr = format.getElement(element); int count = attr.getElementCount(); int constant = attr.getType().getGlConstant(); buffer.position(format.getOffset(element)); switch(attrType) { case POSITION: glVertexPointer(count, constant, stride, buffer); glEnableClientState(GL_VERTEX_ARRAY); break; case NORMAL: if(count != 3) { throw new IllegalArgumentException("Normal attribute should have the size 3: " + attr); } glNormalPointer(constant, stride, buffer); glEnableClientState(GL_NORMAL_ARRAY); break; case COLOR: glColorPointer(count, constant, stride, buffer); glEnableClientState(GL_COLOR_ARRAY); break; case UV: OpenGlHelper.setClientActiveTexture(OpenGlHelper.defaultTexUnit + attr.getIndex()); glTexCoordPointer(count, constant, stride, buffer); glEnableClientState(GL_TEXTURE_COORD_ARRAY); OpenGlHelper.setClientActiveTexture(OpenGlHelper.defaultTexUnit); break; case PADDING: break; case GENERIC: glEnableVertexAttribArray(attr.getIndex()); glVertexAttribPointer(attr.getIndex(), count, constant, false, stride, buffer); default: FMLLog.severe("Unimplemented vanilla attribute upload: %s", attrType.getDisplayName()); } } public static void postDraw(EnumUsage attrType, VertexFormat format, int element, int stride, ByteBuffer buffer) { VertexFormatElement attr = format.getElement(element); switch(attrType) { case POSITION: glDisableClientState(GL_VERTEX_ARRAY); break; case NORMAL: glDisableClientState(GL_NORMAL_ARRAY); break; case COLOR: glDisableClientState(GL_COLOR_ARRAY); // is this really needed? GlStateManager.resetColor(); break; case UV: OpenGlHelper.setClientActiveTexture(OpenGlHelper.defaultTexUnit + attr.getIndex()); glDisableClientState(GL_TEXTURE_COORD_ARRAY); OpenGlHelper.setClientActiveTexture(OpenGlHelper.defaultTexUnit); break; case PADDING: break; case GENERIC: glDisableVertexAttribArray(attr.getIndex()); default: FMLLog.severe("Unimplemented vanilla attribute upload: %s", attrType.getDisplayName()); } } public static void transform(org.lwjgl.util.vector.Vector3f vec, Matrix4f m) { Vector4f tmp = new Vector4f(vec.x, vec.y, vec.z, 1f); m.transform(tmp); if(Math.abs(tmp.w - 1f) > 1e-5) tmp.scale(1f / tmp.w); vec.set(tmp.x, tmp.y, tmp.z); } public static Matrix4f getMatrix(ModelRotation modelRotation) { Matrix4f ret = new Matrix4f(TRSRTransformation.toVecmath(modelRotation.getMatrix4d())), tmp = new Matrix4f(); tmp.setIdentity(); tmp.m03 = tmp.m13 = tmp.m23 = .5f; ret.mul(tmp, ret); tmp.invert(); //tmp.m03 = tmp.m13 = tmp.m23 = -.5f; ret.mul(tmp); return ret; } public static void putQuadColor(VertexBuffer renderer, BakedQuad quad, int color) { float cb = color & 0xFF; float cg = (color >>> 8) & 0xFF; float cr = (color >>> 16) & 0xFF; float ca = (color >>> 24) & 0xFF; VertexFormat format = quad.getFormat(); int size = format.getIntegerSize(); int offset = format.getColorOffset() / 4; // assumes that color is aligned for(int i = 0; i < 4; i++) { int vc = quad.getVertexData()[offset + size * i]; float vcr = vc & 0xFF; float vcg = (vc >>> 8) & 0xFF; float vcb = (vc >>> 16) & 0xFF; float vca = (vc >>> 24) & 0xFF; int ncr = Math.min(0xFF, (int)(cr * vcr / 0xFF)); int ncg = Math.min(0xFF, (int)(cg * vcg / 0xFF)); int ncb = Math.min(0xFF, (int)(cb * vcb / 0xFF)); int nca = Math.min(0xFF, (int)(ca * vca / 0xFF)); renderer.putColorRGBA(renderer.getColorIndex(4 - i), ncr, ncg, ncb, nca); } } private static Map<Pair<Item, Integer>, Class<? extends TileEntity>> tileItemMap = Maps.newHashMap(); public static void renderTileItem(Item item, int metadata) { Class<? extends TileEntity> tileClass = tileItemMap.get(Pair.of(item, metadata)); if (tileClass != null) { TileEntitySpecialRenderer<?> r = TileEntityRendererDispatcher.instance.getSpecialRendererByClass(tileClass); if (r != null) { r.renderTileEntityAt(null, 0, 0, 0, 0, -1); } } } /** * @deprecated Will be removed as soon as possible, hopefully 1.9. */ @Deprecated public static void registerTESRItemStack(Item item, int metadata, Class<? extends TileEntity> TileClass) { tileItemMap.put(Pair.of(item, metadata), TileClass); } /** * internal, relies on fixed format of FaceBakery */ public static void fillNormal(int[] faceData, EnumFacing facing) { Vector3f v1 = new Vector3f(faceData[3 * 7 + 0], faceData[3 * 7 + 1], faceData[3 * 7 + 2]); Vector3f t = new Vector3f(faceData[1 * 7 + 0], faceData[1 * 7 + 1], faceData[1 * 7 + 2]); Vector3f v2 = new Vector3f(faceData[2 * 7 + 0], faceData[2 * 7 + 1], faceData[2 * 7 + 2]); v1.sub(t); t.set(faceData[0 * 7 + 0], faceData[0 * 7 + 1], faceData[0 * 7 + 2]); v2.sub(t); v1.cross(v2, v1); v1.normalize(); int x = ((byte)(v1.x * 127)) & 0xFF; int y = ((byte)(v1.y * 127)) & 0xFF; int z = ((byte)(v1.z * 127)) & 0xFF; for(int i = 0; i < 4; i++) { faceData[i * 7 + 6] = x | (y << 0x08) | (z << 0x10); } } @SuppressWarnings("deprecation") public static Optional<TRSRTransformation> applyTransform(net.minecraft.client.renderer.block.model.ItemTransformVec3f transform, Optional<? extends IModelPart> part) { if(part.isPresent()) return Optional.absent(); return Optional.of(TRSRTransformation.blockCenterToCorner(new TRSRTransformation(transform))); } public static Optional<TRSRTransformation> applyTransform(Matrix4f matrix, Optional<? extends IModelPart> part) { if(part.isPresent()) return Optional.absent(); return Optional.of(new TRSRTransformation(matrix)); } public static void loadEntityShader(Entity entity, EntityRenderer entityRenderer) { if (entity != null) { ResourceLocation shader = ClientRegistry.getEntityShader(entity.getClass()); if (shader != null) { entityRenderer.loadShader(shader); } } } public static IBakedModel getDamageModel(IBakedModel ibakedmodel, TextureAtlasSprite texture, IBlockState state, IBlockAccess world, BlockPos pos) { state = state.getBlock().getExtendedState(state, world, pos); return (new SimpleBakedModel.Builder(state, ibakedmodel, texture, pos)).makeBakedModel(); } private static int slotMainHand = 0; // FIXME public static boolean shouldCauseReequipAnimation(ItemStack from, ItemStack to, int slot) { if (from == null && to != null) return true; if (from == null && to == null) return false; if (from != null && to == null) return true; boolean changed = false; if (slot != -1) { changed = slot != slotMainHand; slotMainHand = slot; } return from.getItem().shouldCauseReequipAnimation(from, to, changed); } public static boolean shouldCauseBlockBreakReset(@Nonnull ItemStack from, @Nonnull ItemStack to) { return from.getItem().shouldCauseBlockBreakReset(from, to); } public static BlockFaceUV applyUVLock(BlockFaceUV blockFaceUV, EnumFacing originalSide, ITransformation rotation) { TRSRTransformation global = new TRSRTransformation(rotation.getMatrix()); Matrix4f uv = global.getUVLockTransform(originalSide).getMatrix(); Vector4f vec = new Vector4f(0, 0, 0, 1); vec.x = blockFaceUV.getVertexU(blockFaceUV.getVertexRotatedRev(0)) / 16; vec.y = blockFaceUV.getVertexV(blockFaceUV.getVertexRotatedRev(0)) / 16; uv.transform(vec); float uMin = 16 * vec.x; // / vec.w; float vMin = 16 * vec.y; // / vec.w; vec.x = blockFaceUV.getVertexU(blockFaceUV.getVertexRotatedRev(2)) / 16; vec.y = blockFaceUV.getVertexV(blockFaceUV.getVertexRotatedRev(2)) / 16; vec.z = 0; vec.w = 1; uv.transform(vec); float uMax = 16 * vec.x; // / vec.w; float vMax = 16 * vec.y; // / vec.w; if(uMin > uMax) { float t = uMin; uMin = uMax; uMax = t; } if(vMin > vMax) { float t = vMin; vMin = vMax; vMax = t; } float a = (float)Math.toRadians(blockFaceUV.rotation); Vector3f rv = new Vector3f(MathHelper.cos(a), MathHelper.sin(a), 0); Matrix3f rot = new Matrix3f(); uv.getRotationScale(rot); rot.transform(rv); int angle = MathHelper.normalizeAngle(-(int)Math.round(Math.toDegrees(Math.atan2(rv.y, rv.x)) / 90) * 90, 360); return new BlockFaceUV(new float[]{ uMin, vMin, uMax, vMax }, angle); } public static RenderGameOverlayEvent.BossInfo bossBarRenderPre(ScaledResolution res, BossInfoLerping bossInfo, int x, int y, int increment) { RenderGameOverlayEvent.BossInfo evt = new RenderGameOverlayEvent.BossInfo(new RenderGameOverlayEvent(Animation.getPartialTickTime(), res), BOSSINFO, bossInfo, x, y, increment); MinecraftForge.EVENT_BUS.post(evt); return evt; } public static void bossBarRenderPost(ScaledResolution res) { MinecraftForge.EVENT_BUS.post(new RenderGameOverlayEvent.Post(new RenderGameOverlayEvent(Animation.getPartialTickTime(), res), BOSSINFO)); } public static ScreenshotEvent onScreenshot(BufferedImage image, File screenshotFile) { ScreenshotEvent event = new ScreenshotEvent(image, screenshotFile); MinecraftForge.EVENT_BUS.post(event); return event; } }
boredherobrine13/morefuelsmod-1.10
build/tmp/recompileMc/sources/net/minecraftforge/client/ForgeHooksClient.java
Java
lgpl-2.1
30,248
// Integer Utility export const UINT32_MAX = 0xffff_ffff; // DataView extension to handle int64 / uint64, // where the actual range is 53-bits integer (a.k.a. safe integer) export function setUint64(view: DataView, offset: number, value: number): void { const high = value / 0x1_0000_0000; const low = value; // high bits are truncated by DataView view.setUint32(offset, high); view.setUint32(offset + 4, low); } export function setInt64(view: DataView, offset: number, value: number): void { const high = Math.floor(value / 0x1_0000_0000); const low = value; // high bits are truncated by DataView view.setUint32(offset, high); view.setUint32(offset + 4, low); } export function getInt64(view: DataView, offset: number): number { const high = view.getInt32(offset); const low = view.getUint32(offset + 4); return high * 0x1_0000_0000 + low; } export function getUint64(view: DataView, offset: number): number { const high = view.getUint32(offset); const low = view.getUint32(offset + 4); return high * 0x1_0000_0000 + low; }
qianqians/abelkhan
sample/CocosCli/assets/script/@msgpack/msgpack/utils/int.ts
TypeScript
lgpl-2.1
1,060
/* * Copyright (C) 2005-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.policy; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.alfresco.api.AlfrescoPublicApi; import org.alfresco.util.LockHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Policy Factory with caching support. * * @author David Caruana * * @param <B> the type of Binding * @param <P> the type of Policy */ /*package*/ @AlfrescoPublicApi class CachedPolicyFactory<B extends BehaviourBinding, P extends Policy> extends PolicyFactory<B, P> { // Logger private static final Log logger = LogFactory.getLog(PolicyComponentImpl.class); // Behaviour Filter private BehaviourFilter behaviourFilter = null; // Cache Lock private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); /** * Cache for a single Policy interface (keyed by Binding) */ private Map<B, P> singleCache = new HashMap<B, P>(); /** * Cache for a collection of Policy interfaces (keyed by Binding) */ private Map<B, Collection<P>> listCache = new HashMap<B, Collection<P>>(); // Try lock timeout (MNT-11371) private long tryLockTimeout; public void setTryLockTimeout(long tryLockTimeout) { this.tryLockTimeout = tryLockTimeout; } /** * Construct cached policy factory * * @param policyClass the policy interface class * @param index the behaviour index to search on */ /*package*/ CachedPolicyFactory(Class<P> policyClass, BehaviourIndex<B> index) { super(policyClass, index); behaviourFilter = index.getFilter(); // Register this cached policy factory as a change observer of the behaviour index // to allow for cache to be cleared appropriately. index.addChangeObserver(new BehaviourChangeObserver<B>() { public void addition(B binding, Behaviour behaviour) { clearCache("aggregate delegate", singleCache, binding); clearCache("delegate collection", listCache, binding); } public void removal(B binding, Behaviour behaviour) { clearCache("aggregate delegate", singleCache, binding); clearCache("delegate collection", listCache, binding); } }); } @Override public P create(B binding) { // When behaviour filters are activated bypass the cache if (behaviourFilter != null && behaviourFilter.isActivated()) { return super.create(binding); } LockHelper.tryLock(lock.readLock(), tryLockTimeout, "getting policy from cache in 'CachedPolicyFactory.create()'"); try { P policyInterface = singleCache.get(binding); if (policyInterface != null) { return policyInterface; } } finally { lock.readLock().unlock(); } // There wasn't one LockHelper.tryLock(lock.writeLock(), tryLockTimeout, "putting new policy to cache in 'CachedPolicyFactory.create()'"); try { P policyInterface = singleCache.get(binding); if (policyInterface != null) { return policyInterface; } policyInterface = super.create(binding); singleCache.put(binding, policyInterface); if (logger.isDebugEnabled()) logger.debug("Cached delegate interface " + policyInterface + " for " + binding + " and policy " + getPolicyClass()); return policyInterface; } finally { lock.writeLock().unlock(); } } @Override public Collection<P> createList(B binding) { // When behaviour filters are activated bypass the cache if (behaviourFilter != null && behaviourFilter.isActivated()) { return super.createList(binding); } LockHelper.tryLock(lock.readLock(), tryLockTimeout, "getting policy list from cache in 'CachedPolicyFactory.createList()'"); try { Collection<P> policyInterfaces = listCache.get(binding); if (policyInterfaces != null) { return policyInterfaces; } } finally { lock.readLock().unlock(); } // There wasn't one LockHelper.tryLock(lock.writeLock(), tryLockTimeout, "putting policy list to cache in 'CachedPolicyFactory.createList()'"); try { Collection<P> policyInterfaces = listCache.get(binding); if (policyInterfaces != null) { return policyInterfaces; } policyInterfaces = super.createList(binding); listCache.put(binding, policyInterfaces); if (logger.isDebugEnabled()) logger.debug("Cached delegate interface collection " + policyInterfaces + " for " + binding + " and policy " + getPolicyClass()); return policyInterfaces; } finally { lock.writeLock().unlock(); } } /** * Clear entries in the cache based on binding changes. * * @param cacheDescription description of cache to clear * @param cache the cache to clear * @param binding the binding */ private void clearCache(String cacheDescription, Map<B, ?> cache, B binding) { if (binding == null) { LockHelper.tryLock(lock.writeLock(), tryLockTimeout, "clearing policy cache in 'CachedPolicyFactory.clearCache()'"); try { // A specific binding has not been provided, so clear all entries cache.clear(); if (logger.isDebugEnabled() && cache.isEmpty() == false) logger.debug("Cleared " + cacheDescription + " cache (all class bindings) for policy " + getPolicyClass()); } finally { lock.writeLock().unlock(); } } else { // A specific binding has been provided. Build a list of entries // that require removal. An entry is removed if the binding in the // list is equal or derived from the changed binding. Collection<B> invalidBindings = new ArrayList<B>(); for (B cachedBinding : cache.keySet()) { // Determine if binding is equal or derived from changed binding BehaviourBinding generalisedBinding = cachedBinding; while(generalisedBinding != null) { if (generalisedBinding.equals(binding)) { invalidBindings.add(cachedBinding); break; } generalisedBinding = generalisedBinding.generaliseBinding(); } } // Remove all invalid bindings if (invalidBindings.size() > 0) { LockHelper.tryLock(lock.writeLock(), tryLockTimeout, "removing invalid policy bindings from cache in 'CachedPolicyFactory.clearCache()'"); try { for (B invalidBinding : invalidBindings) { cache.remove(invalidBinding); if (logger.isDebugEnabled()) logger.debug("Cleared " + cacheDescription + " cache for " + invalidBinding + " and policy " + getPolicyClass()); } } finally { lock.writeLock().unlock(); } } } } }
nguyentienlong/community-edition
projects/repository/source/java/org/alfresco/repo/policy/CachedPolicyFactory.java
Java
lgpl-3.0
8,878
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\network\mcpe\protocol\types; class ScorePacketEntry{ public const TYPE_PLAYER = 1; public const TYPE_ENTITY = 2; public const TYPE_FAKE_PLAYER = 3; /** @var int */ public $scoreboardId; /** @var string */ public $objectiveName; /** @var int */ public $score; /** @var int */ public $type; /** @var int|null (if type entity or player) */ public $entityUniqueId; /** @var string|null (if type fake player) */ public $customName; }
kabluinc/PocketMine-MP
src/pocketmine/network/mcpe/protocol/types/ScorePacketEntry.php
PHP
lgpl-3.0
1,203
import javax.swing.text.*; class Notepad { //declaration of the private variables used in the program //create the text area private JTextPane textPane; Notepad() { Container cp = getContentPane(); textPane = new JTextPane(); cp.add(textPane); cp.add(new JScrollPane(textPane)); } public JTextPane getTextPane() { return textPane; } public JTextComponent getTextComponent() { return textPane; } }
SergiyKolesnikov/fuji
examples/Notepad_casestudies/NotepadAdrianQuark/TextStyled/Notepad.java
Java
lgpl-3.0
420
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2014 Pelican Mapping * http://osgearth.org * * osgEarth 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 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "KML_IconStyle" #include <osgEarthSymbology/IconSymbol> using namespace osgEarth_kml; void KML_IconStyle::scan( xml_node<>* node, Style& style, KMLContext& cx ) { if ( node ) { IconSymbol* icon = style.getOrCreate<IconSymbol>(); // Icon/Href or just Icon are both valid std::string iconHref; xml_node<>* iconNode = node->first_node("icon", 0, false); if (iconNode) { iconHref = getValue(iconNode, "href"); if ( iconHref.empty() ) iconHref = getValue(node, "icon"); } if ( !iconHref.empty() ) { icon->url() = StringExpression( iconHref, URIContext(cx._referrer) ); } // see: https://developers.google.com/kml/documentation/kmlreference#headingdiagram std::string heading = getValue(node, "heading"); if ( !heading.empty() ) icon->heading() = NumericExpression( heading ); float finalScale = *cx._options->iconBaseScale(); std::string scale = getValue(node, "scale"); if ( !scale.empty() ) icon->scale() = NumericExpression( scale ); } }
Riorlan/osgearth
src/osgEarthDrivers/kml/KML_IconStyle.cpp
C++
lgpl-3.0
1,910
// // ComMethodElement.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2006 Novell, Inc. http://www.novell.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration; using System.Net; using System.Net.Security; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.IdentityModel.Tokens; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.ServiceModel.MsmqIntegration; using System.ServiceModel.PeerResolvers; using System.ServiceModel.Security; using System.Runtime.Serialization; using System.Text; using System.Xml; namespace System.ServiceModel.Configuration { [MonoTODO] public sealed partial class ComMethodElement : ConfigurationElement { // Static Fields static ConfigurationPropertyCollection properties; static ConfigurationProperty exposed_method; static ComMethodElement () { properties = new ConfigurationPropertyCollection (); exposed_method = new ConfigurationProperty ("exposedMethod", typeof (string), null, new StringConverter (), null, ConfigurationPropertyOptions.IsRequired| ConfigurationPropertyOptions.IsKey); properties.Add (exposed_method); } public ComMethodElement () { } // Properties [ConfigurationProperty ("exposedMethod", Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey, IsRequired = true, IsKey = true)] [StringValidator ( MinLength = 1, MaxLength = int.MaxValue, InvalidCharacters = null)] public string ExposedMethod { get { return (string) base [exposed_method]; } set { base [exposed_method] = value; } } protected override ConfigurationPropertyCollection Properties { get { return properties; } } } }
edwinspire/VSharp
class/System.ServiceModel/System.ServiceModel.Configuration/ComMethodElement.cs
C#
lgpl-3.0
3,179
<?php /** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to * use, copy, modify, and distribute this software in source code or binary * form for use in connection with the web services and APIs provided by * Facebook. * * As with any software that integrates with the Facebook platform, your use * of this software is subject to the Facebook Developer Principles and * Policies [http://developers.facebook.com/policy/]. This copyright notice * shall be included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ namespace FacebookAds\Object\Values; use FacebookAds\Enum\AbstractEnum; /** * @method static ReachFrequencyPredictionStatuses getInstance() */ class ReachFrequencyPredictionStatuses extends AbstractEnum { const SUCCESS = 1; const PENDING = 2; const UNREACHABLE_AUDIENCE = 3; const CONFIG_INVALID = 4; const TARGET_SPEC_INVALID = 5; const BUDGET_TOO_LOW = 6; const TOO_SHORT_AD_SET_LENGTH = 7; const TOO_LONG_AD_SET_LENGTH = 8; const END_DATE_TOO_FAR = 9; const FREQUENCY_CAP_NOT_SPECIFIED = 10; const UNSUPPORTED_PLACEMENT = 11; const DATE_ERROR = 12; const COUNTRY_NOT_SUPPORTED = 13; const BLACKOUT_DAYS = 14; const INSUFFICIENT_INVENTORY = 15; const REACH_BELOW_1_MILLION = 16; const MINIMUM_REACH_NOT_AVAILABLE = 17; const INVENTORY_CHANGED = 21; }
advanced-online-marketing/AOM
vendor/facebook/php-business-sdk/src/FacebookAds/Object/Values/ReachFrequencyPredictionStatuses.php
PHP
lgpl-3.0
1,911
package org.molgenis.security.permission; import static java.util.Objects.requireNonNull; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; @Component public class PrincipalSecurityContextRegistryImpl implements PrincipalSecurityContextRegistry { private final SecurityContextRegistry securityContextRegistry; PrincipalSecurityContextRegistryImpl(SecurityContextRegistry securityContextRegistry) { this.securityContextRegistry = requireNonNull(securityContextRegistry); } @Override public Stream<SecurityContext> getSecurityContexts(Object principal) { Set<SecurityContext> securityContexts = new HashSet<>(); SecurityContext currentExecutionThreadSecurityContext = getSecurityContextCurrentExecutionThread(principal); if (currentExecutionThreadSecurityContext != null) { securityContexts.add(currentExecutionThreadSecurityContext); } getSecurityContextsFromRegistry(principal).forEach(securityContexts::add); return securityContexts.stream(); } private SecurityContext getSecurityContextCurrentExecutionThread(Object principal) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null && authentication.getPrincipal().equals(principal)) { return securityContext; } else { return null; } } private Stream<SecurityContext> getSecurityContextsFromRegistry(Object principal) { String username = getUsername(principal); return securityContextRegistry .getSecurityContexts() .filter( securityContext -> { Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { Object securityContextPrincipal = authentication.getPrincipal(); if (username.equals(getUsername(securityContextPrincipal))) { return true; } } return false; }); } private String getUsername(Object principal) { String username; if (principal instanceof User) { username = ((User) principal).getUsername(); } else { username = principal.toString(); } return username; } }
dennishendriksen/molgenis
molgenis-security/src/main/java/org/molgenis/security/permission/PrincipalSecurityContextRegistryImpl.java
Java
lgpl-3.0
2,625