code
stringlengths
5
1.01M
repo_name
stringlengths
5
84
path
stringlengths
4
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
5
1.01M
input_ids
listlengths
502
502
token_type_ids
listlengths
502
502
attention_mask
listlengths
502
502
labels
listlengths
502
502
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe OmniAuth::Strategies::SmugMug do it_should_behave_like 'an oauth strategy' end
sbhalerao/CIYH_ver3
oa-oauth/spec/omniauth/strategies/smug_mug_spec.rb
Ruby
mit
161
[ 30522, 5478, 5371, 1012, 7818, 1035, 4130, 1006, 5371, 1012, 16101, 18442, 1006, 1035, 1035, 5371, 1035, 1035, 1007, 1009, 1005, 1013, 1012, 1012, 1013, 1012, 1012, 1013, 28699, 1035, 2393, 2121, 1005, 1007, 6235, 18168, 6200, 14317, 1024, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!doctype html> <html> <head> <meta charset="utf-8"> <title>System\Browser\assets\scripts\Flash.js 源码</title> <link href="../../assets/styles/prettify.css" type="text/css" rel="stylesheet" /> <script src="../../assets/scripts/prettify.js" type="text/javascript"></script> <style type="text/css">.highlight { display: block; background-color: #ddd; }</style> </head> <body onload="setTimeout('prettyPrint()', 0);var node = document.getElementById(location.hash.replace(/#/, ''));if(node)node.className = 'highlight';"><pre class="prettyprint lang-js">//=========================================== // Swf swiff.js A //=========================================== using(&quot;System.Controls.Control&quot;); namespace(&quot;.Swiff&quot;, JPlus.Control.extend({ options: { id: null, height: 1, width: 1, container: null, properties: {}, params: { quality: 'high', allowScriptAccess: 'always', wMode: 'window', swLiveConnect: true }, callBacks: {}, vars: {} }, constructor: function (path, options) { this.instance = 'Swiff_' + String.uniqueID(); this.setOptions(options); options = this.options; var id = this.id = options.id || this.instance; var container = document.id(options.container); Swiff.CallBacks[this.instance] = {}; var params = options.params, vars = options.vars, callBacks = options.callBacks; var properties = Object.append({ height: options.height, width: options.width }, options.properties); var self = this; for (var callBack in callBacks) { Swiff.CallBacks[this.instance][callBack] = (function (option) { return function () { return option.apply(self.object, arguments); }; })(callBacks[callBack]); vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack; } params.flashVars = Object.toQueryString(vars); if (Browser.ie) { properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; params.movie = path; } else { properties.type = 'application/x-shockwave-flash'; } properties.data = path; var build = '&lt;object id=&quot;' + id + '&quot;'; for (var property in properties) build += ' ' + property + '=&quot;' + properties[property] + '&quot;'; build += '&gt;'; for (var param in params) { if (params[param]) build += '&lt;param name=&quot;' + param + '&quot; value=&quot;' + params[param] + '&quot; /&gt;'; } build += '&lt;/object&gt;'; this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild; }, remote: function () { return Swiff.remote.apply(Swiff, [this.node || this].append(arguments)); } })); Swiff.CallBacks = {}; Swiff.remote = function (obj, fn) { var rs = obj.CallFunction('&lt;invoke name=&quot;' + fn + '&quot; returntype=&quot;javascript&quot;&gt;' + __flash__argumentsToXML(arguments, 2) + '&lt;/invoke&gt;'); return eval(rs); };</pre> </body> </html>
jplusui/jplusui.github.com
resources/cookbooks/jplusui-full-api/data/source/System/Browser/assets/scripts/Flash.js.html
HTML
bsd-3-clause
3,002
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 2516, 1028, 2291, 1032, 16602, 1032, 7045, 1032, 14546, 1032, 5956, 1012, 104...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.thoughtcrime.securesms.service; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.thoughtcrime.redphone.signaling.RedPhoneAccountAttributes; import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager; import org.thoughtcrime.redphone.signaling.RedPhoneTrustStore; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; import org.thoughtcrime.securesms.crypto.PreKeyUtil; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.jobs.GcmRefreshJob; import org.thoughtcrime.securesms.push.TextSecureCommunicationFactory; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.util.DirectoryHelper; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.libaxolotl.IdentityKeyPair; import org.whispersystems.libaxolotl.state.PreKeyRecord; import org.whispersystems.libaxolotl.state.SignedPreKeyRecord; import org.whispersystems.libaxolotl.util.KeyHelper; import org.whispersystems.libaxolotl.util.guava.Optional; import org.whispersystems.textsecure.api.TextSecureAccountManager; import org.whispersystems.textsecure.api.push.exceptions.ExpectationFailedException; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * The RegisterationService handles the process of PushService registration and verification. * If it receives an intent with a REGISTER_NUMBER_ACTION, it does the following through * an executor: * * 1) Generate secrets. * 2) Register the specified number and those secrets with the server. * 3) Wait for a challenge SMS. * 4) Verify the challenge with the server. * 5) Start the GCM registration process. * 6) Retrieve the current directory. * * The RegistrationService broadcasts its state throughout this process, and also makes its * state available through service binding. This enables a View to display progress. * * @author Moxie Marlinspike * */ public class RegistrationService extends Service { public static final String REGISTER_NUMBER_ACTION = "org.thoughtcrime.securesms.RegistrationService.REGISTER_NUMBER"; public static final String VOICE_REQUESTED_ACTION = "org.thoughtcrime.securesms.RegistrationService.VOICE_REQUESTED"; public static final String VOICE_REGISTER_ACTION = "org.thoughtcrime.securesms.RegistrationService.VOICE_REGISTER"; public static final String NOTIFICATION_TITLE = "org.thoughtcrime.securesms.NOTIFICATION_TITLE"; public static final String NOTIFICATION_TEXT = "org.thoughtcrime.securesms.NOTIFICATION_TEXT"; public static final String CHALLENGE_EVENT = "org.thoughtcrime.securesms.CHALLENGE_EVENT"; public static final String REGISTRATION_EVENT = "org.thoughtcrime.securesms.REGISTRATION_EVENT"; public static final String CHALLENGE_EXTRA = "CAAChallenge"; private static final long REGISTRATION_TIMEOUT_MILLIS = 120000; private final ExecutorService executor = Executors.newSingleThreadExecutor(); private final Binder binder = new RegistrationServiceBinder(); private volatile RegistrationState registrationState = new RegistrationState(RegistrationState.STATE_IDLE); private volatile WeakReference<Handler> registrationStateHandler; private volatile ChallengeReceiver challengeReceiver; private String challenge; private long verificationStartTime; private boolean generatingPreKeys; @Override public int onStartCommand(final Intent intent, int flags, int startId) { if (intent != null) { executor.execute(new Runnable() { @Override public void run() { if (REGISTER_NUMBER_ACTION.equals(intent.getAction())) handleSmsRegistrationIntent(intent); else if (VOICE_REQUESTED_ACTION.equals(intent.getAction())) handleVoiceRequestedIntent(intent); else if (VOICE_REGISTER_ACTION.equals(intent.getAction())) handleVoiceRegistrationIntent(intent); } }); } return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); executor.shutdown(); shutdown(); } @Override public IBinder onBind(Intent intent) { return binder; } public void shutdown() { shutdownChallengeListener(); markAsVerifying(false); registrationState = new RegistrationState(RegistrationState.STATE_IDLE); } public synchronized int getSecondsRemaining() { long millisPassed; if (verificationStartTime == 0) millisPassed = 0; else millisPassed = System.currentTimeMillis() - verificationStartTime; return Math.max((int)(REGISTRATION_TIMEOUT_MILLIS - millisPassed) / 1000, 0); } public RegistrationState getRegistrationState() { return registrationState; } private void initializeChallengeListener() { this.challenge = null; challengeReceiver = new ChallengeReceiver(); IntentFilter filter = new IntentFilter(CHALLENGE_EVENT); registerReceiver(challengeReceiver, filter); } private synchronized void shutdownChallengeListener() { if (challengeReceiver != null) { unregisterReceiver(challengeReceiver); challengeReceiver = null; } } private void handleVoiceRequestedIntent(Intent intent) { setState(new RegistrationState(RegistrationState.STATE_VOICE_REQUESTED, intent.getStringExtra("e164number"), intent.getStringExtra("password"))); } private void handleVoiceRegistrationIntent(Intent intent) { markAsVerifying(true); String number = intent.getStringExtra("e164number"); String password = intent.getStringExtra("password"); String signalingKey = intent.getStringExtra("signaling_key"); try { TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(this, number, password); handleCommonRegistration(accountManager, number, password, signalingKey); markAsVerified(number, password, signalingKey); setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number)); broadcastComplete(true); } catch (UnsupportedOperationException uoe) { Log.w("RegistrationService", uoe); setState(new RegistrationState(RegistrationState.STATE_GCM_UNSUPPORTED, number)); broadcastComplete(false); } catch (IOException e) { Log.w("RegistrationService", e); setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number)); broadcastComplete(false); } } private void handleSmsRegistrationIntent(Intent intent) { markAsVerifying(true); String number = intent.getStringExtra("e164number"); int registrationId = TextSecurePreferences.getLocalRegistrationId(this); if (registrationId == 0) { registrationId = KeyHelper.generateRegistrationId(false); TextSecurePreferences.setLocalRegistrationId(this, registrationId); } try { String password = Util.getSecret(18); String signalingKey = Util.getSecret(52); initializeChallengeListener(); setState(new RegistrationState(RegistrationState.STATE_CONNECTING, number)); TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(this, number, password); accountManager.requestSmsVerificationCode(); setState(new RegistrationState(RegistrationState.STATE_VERIFYING, number)); String challenge = waitForChallenge(); accountManager.verifyAccountWithCode(challenge, signalingKey, registrationId, true); handleCommonRegistration(accountManager, number, password, signalingKey); markAsVerified(number, password, signalingKey); setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number)); broadcastComplete(true); } catch (ExpectationFailedException efe) { Log.w("RegistrationService", efe); setState(new RegistrationState(RegistrationState.STATE_MULTI_REGISTERED, number)); broadcastComplete(false); } catch (UnsupportedOperationException uoe) { Log.w("RegistrationService", uoe); setState(new RegistrationState(RegistrationState.STATE_GCM_UNSUPPORTED, number)); broadcastComplete(false); } catch (AccountVerificationTimeoutException avte) { Log.w("RegistrationService", avte); setState(new RegistrationState(RegistrationState.STATE_TIMEOUT, number)); broadcastComplete(false); } catch (IOException e) { Log.w("RegistrationService", e); setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number)); broadcastComplete(false); } finally { shutdownChallengeListener(); } } private void handleCommonRegistration(TextSecureAccountManager accountManager, String number, String password, String signalingKey) throws IOException { setState(new RegistrationState(RegistrationState.STATE_GENERATING_KEYS, number)); Recipient self = RecipientFactory.getRecipientsFromString(this, number, false).getPrimaryRecipient(); IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(this); List<PreKeyRecord> records = PreKeyUtil.generatePreKeys(this); PreKeyRecord lastResort = PreKeyUtil.generateLastResortKey(this); SignedPreKeyRecord signedPreKey = PreKeyUtil.generateSignedPreKey(this, identityKey); accountManager.setPreKeys(identityKey.getPublicKey(),lastResort, signedPreKey, records); setState(new RegistrationState(RegistrationState.STATE_GCM_REGISTERING, number)); String gcmRegistrationId = GoogleCloudMessaging.getInstance(this).register(GcmRefreshJob.REGISTRATION_ID); accountManager.setGcmId(Optional.of(gcmRegistrationId)); TextSecurePreferences.setGcmRegistrationId(this, gcmRegistrationId); TextSecurePreferences.setWebsocketRegistered(this, true); DatabaseFactory.getIdentityDatabase(this).saveIdentity(self.getRecipientId(), identityKey.getPublicKey()); DirectoryHelper.refreshDirectory(this, accountManager, number); RedPhoneAccountManager redPhoneAccountManager = new RedPhoneAccountManager(BuildConfig.REDPHONE_MASTER_URL, new RedPhoneTrustStore(this), number, password); String verificationToken = accountManager.getAccountVerificationToken(); redPhoneAccountManager.createAccount(verificationToken, new RedPhoneAccountAttributes(signalingKey, gcmRegistrationId)); DirectoryRefreshListener.schedule(this); } private synchronized String waitForChallenge() throws AccountVerificationTimeoutException { this.verificationStartTime = System.currentTimeMillis(); if (this.challenge == null) { try { wait(REGISTRATION_TIMEOUT_MILLIS); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } if (this.challenge == null) throw new AccountVerificationTimeoutException(); return this.challenge; } private synchronized void challengeReceived(String challenge) { this.challenge = challenge; notifyAll(); } private void markAsVerifying(boolean verifying) { TextSecurePreferences.setVerifying(this, verifying); if (verifying) { TextSecurePreferences.setPushRegistered(this, false); } } private void markAsVerified(String number, String password, String signalingKey) { TextSecurePreferences.setVerifying(this, false); TextSecurePreferences.setPushRegistered(this, true); TextSecurePreferences.setLocalNumber(this, number); TextSecurePreferences.setPushServerPassword(this, password); TextSecurePreferences.setSignalingKey(this, signalingKey); TextSecurePreferences.setSignedPreKeyRegistered(this, true); TextSecurePreferences.setPromptedPushRegistration(this, true); } private void setState(RegistrationState state) { this.registrationState = state; Handler registrationStateHandler = this.registrationStateHandler.get(); if (registrationStateHandler != null) { registrationStateHandler.obtainMessage(state.state, state).sendToTarget(); } } private void broadcastComplete(boolean success) { Intent intent = new Intent(); intent.setAction(REGISTRATION_EVENT); if (success) { intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_complete)); intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_signal_registration_has_successfully_completed)); } else { intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_error)); intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_signal_registration_has_encountered_a_problem)); } this.sendOrderedBroadcast(intent, null); } public void setRegistrationStateHandler(Handler registrationStateHandler) { this.registrationStateHandler = new WeakReference<>(registrationStateHandler); } public class RegistrationServiceBinder extends Binder { public RegistrationService getService() { return RegistrationService.this; } } private class ChallengeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.w("RegistrationService", "Got a challenge broadcast..."); challengeReceived(intent.getStringExtra(CHALLENGE_EXTRA)); } } public static class RegistrationState { public static final int STATE_IDLE = 0; public static final int STATE_CONNECTING = 1; public static final int STATE_VERIFYING = 2; public static final int STATE_TIMER = 3; public static final int STATE_COMPLETE = 4; public static final int STATE_TIMEOUT = 5; public static final int STATE_NETWORK_ERROR = 6; public static final int STATE_GCM_UNSUPPORTED = 8; public static final int STATE_GCM_REGISTERING = 9; public static final int STATE_GCM_TIMEOUT = 10; public static final int STATE_VOICE_REQUESTED = 12; public static final int STATE_GENERATING_KEYS = 13; public static final int STATE_MULTI_REGISTERED = 14; public final int state; public final String number; public final String password; public RegistrationState(int state) { this(state, null); } public RegistrationState(int state, String number) { this(state, number, null); } public RegistrationState(int state, String number, String password) { this.state = state; this.number = number; this.password = password; } } }
jocelynthode/TextSecure
src/org/thoughtcrime/securesms/service/RegistrationService.java
Java
gpl-3.0
15,468
[ 30522, 7427, 8917, 1012, 2245, 26775, 14428, 1012, 5851, 19230, 1012, 2326, 1025, 12324, 11924, 1012, 10439, 1012, 2326, 1025, 12324, 11924, 1012, 4180, 1012, 3743, 2890, 3401, 16402, 1025, 12324, 11924, 1012, 4180, 1012, 6123, 1025, 12324, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env bash mkdir -p ${PREFIX}/bin chmod +x primerclip mv primerclip ${PREFIX}/bin
roryk/recipes
recipes/primerclip/build.sh
Shell
mit
92
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 24234, 12395, 4305, 2099, 1011, 1052, 1002, 1063, 17576, 1065, 1013, 8026, 10381, 5302, 2094, 1009, 1060, 3539, 11890, 15000, 19842, 3539, 11890, 15000, 1002, 1063, 17576, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// // opjlib.h // opjlib // // Created by Rich Stoner on 11/26/13. // Copyright (c) 2013 WholeSlide. All rights reserved. // #import <Foundation/Foundation.h> @interface opjlib : NSObject @end
richstoner/openjpeg-framework-ios
opjlib/opjlib.h
C
mit
200
[ 30522, 1013, 1013, 1013, 1013, 6728, 3501, 29521, 1012, 1044, 1013, 1013, 6728, 3501, 29521, 1013, 1013, 1013, 1013, 2580, 2011, 4138, 2962, 2099, 2006, 2340, 1013, 2656, 1013, 2410, 1012, 1013, 1013, 9385, 1006, 1039, 1007, 2286, 2878, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2)
juanjosegzl/learningpygame
ezmenu.py
Python
gpl-3.0
2,298
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 18750, 1001, 1045, 2179, 2023, 5371, 2503, 3565, 30524, 1013, 1013, 3120, 29278, 3351, 1012, 5658, 1013, 3934, 1013, 3565, 7849, 3695, 12618, 13102, 1013, 1001, 1996, 3143, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; using Windows.Devices.Enumeration; using Windows.Devices.Spi; using Windows.Foundation.Metadata; namespace ABElectronics_Win10IOT_Libraries { /// <summary> /// Class for accessing the ADCDAC Pi from AB Electronics UK. /// </summary> public class ADCDACPi : IDisposable { private const string SPI_CONTROLLER_NAME = "SPI0"; private const Int32 ADC_CHIP_SELECT_LINE = 0; // ADC on SPI channel select CE0 private const Int32 DAC_CHIP_SELECT_LINE = 1; // ADC on SPI channel select CE1 private SpiDevice adc; private double ADCReferenceVoltage = 3.3; private SpiDevice dac; /// <summary> /// Event triggers when a connection is established. /// </summary> public bool IsConnected { get; private set; } // Flag: Has Dispose already been called? bool disposed = false; // Instantiate a SafeHandle instance. System.Runtime.InteropServices.SafeHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(IntPtr.Zero, true); /// <summary> /// Open a connection to the ADCDAC Pi. /// </summary> public async void Connect() { if (IsConnected) { return; // Already connected } if(!ApiInformation.IsTypePresent("Windows.Devices.Spi.SpiDevice")) { return; // This system does not support this feature: can't connect } try { // Create SPI initialization settings for the ADC var adcsettings = new SpiConnectionSettings(ADC_CHIP_SELECT_LINE) { ClockFrequency = 10000000, // SPI clock frequency of 10MHz Mode = SpiMode.Mode0 }; var spiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME); // Find the selector string for the SPI bus controller var devicesInfo = await DeviceInformation.FindAllAsync(spiAqs); // Find the SPI bus controller device with our selector string if (devicesInfo.Count == 0) { return; // Controller not found } adc = await SpiDevice.FromIdAsync(devicesInfo[0].Id, adcsettings); // Create an ADC connection with our bus controller and SPI settings // Create SPI initialization settings for the DAC var dacSettings = new SpiConnectionSettings(DAC_CHIP_SELECT_LINE) { ClockFrequency = 2000000, // SPI clock frequency of 20MHz Mode = SpiMode.Mode0 }; dac = await SpiDevice.FromIdAsync(devicesInfo[0].Id, dacSettings); // Create a DAC connection with our bus controller and SPI settings IsConnected = true; // connection established, set IsConnected to true. // Fire the Connected event handler Connected?.Invoke(this, EventArgs.Empty); } /* If initialization fails, display the exception and stop running */ catch (Exception ex) { IsConnected = false; throw new Exception("SPI Initialization Failed", ex); } } /// <summary> /// Event occurs when connection is made. /// </summary> public event EventHandler Connected; /// <summary> /// Read the voltage from the selected <paramref name="channel" /> on the ADC. /// </summary> /// <param name="channel">1 or 2</param> /// <returns>voltage</returns> public double ReadADCVoltage(byte channel) { if (channel < 1 || channel > 2) { throw new ArgumentOutOfRangeException(nameof(channel)); } var raw = ReadADCRaw(channel); var voltage = ADCReferenceVoltage / 4096 * raw; // convert the raw value into a voltage based on the reference voltage. return voltage; } /// <summary> /// Read the raw value from the selected <paramref name="channel" /> on the ADC. /// </summary> /// <param name="channel">1 or 2</param> /// <returns>Integer</returns> public int ReadADCRaw(byte channel) { if (channel < 1 || channel > 2) { throw new ArgumentOutOfRangeException(nameof(channel)); } CheckConnected(); var writeArray = new byte[] { 0x01, (byte) ((1 + channel) << 6), 0x00}; // create the write bytes based on the input channel var readBuffer = new byte[3]; // this holds the output data adc.TransferFullDuplex(writeArray, readBuffer); // transfer the adc data var ret = (short) (((readBuffer[1] & 0x0F) << 8) + readBuffer[2]); // combine the two bytes into a single 16bit integer return ret; } /// <summary> /// Set the reference <paramref name="voltage" /> for the analogue to digital converter. /// The ADC uses the raspberry pi 3.3V power as a <paramref name="voltage" /> reference /// so using this method to set the reference to match the exact output /// <paramref name="voltage" /> from the 3.3V regulator will increase the accuracy of /// the ADC readings. /// </summary> /// <param name="voltage">double</param> public void SetADCrefVoltage(double voltage) { CheckConnected(); if (voltage < 0.0 || voltage > 7.0) { throw new ArgumentOutOfRangeException(nameof(voltage), "Reference voltage must be between 0.0V and 7.0V."); } ADCReferenceVoltage = voltage; } /// <summary> /// Set the <paramref name="voltage" /> for the selected channel on the DAC. /// </summary> /// <param name="channel">1 or 2</param> /// <param name="voltage">Voltage can be between 0 and 2.047 volts</param> public void SetDACVoltage(byte channel, double voltage) { // Check for valid channel and voltage variables if (channel < 1 || channel > 2) { throw new ArgumentOutOfRangeException(); } if (voltage >= 0.0 && voltage < 2.048) { var rawval = Convert.ToInt16(voltage / 2.048 * 4096); // convert the voltage into a raw value SetDACRaw(channel, rawval); } else { throw new ArgumentOutOfRangeException(); } } /// <summary> /// Set the raw <paramref name="value" /> from the selected <paramref name="channel" /> on the DAC. /// </summary> /// <param name="channel">1 or 2</param> /// <param name="value">Value between 0 and 4095</param> public void SetDACRaw(byte channel, short value) { CheckConnected(); if (channel < 1 || channel > 2) { throw new ArgumentOutOfRangeException(); } // split the raw value into two bytes and send it to the DAC. var lowByte = (byte) (value & 0xff); var highByte = (byte) (((value >> 8) & 0xff) | ((channel - 1) << 7) | (0x1 << 5) | (1 << 4)); var writeBuffer = new [] { highByte, lowByte}; dac.Write(writeBuffer); } private void CheckConnected() { if (!IsConnected) { throw new InvalidOperationException("Not connected. You must call .Connect() first."); } } /// <summary> /// Dispose of the resources /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Protected implementation of Dispose pattern /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { handle.Dispose(); // Free any other managed objects here. adc?.Dispose(); adc = null; dac?.Dispose(); dac = null; IsConnected = false; } // Free any unmanaged objects here. // disposed = true; } } }
abelectronicsuk/ABElectronics_Win10IOT_Libraries
ABElectronics_Win10IOT_Libraries/ADCDACPi.cs
C#
mit
8,804
[ 30522, 2478, 2291, 1025, 2478, 3645, 1012, 5733, 1012, 4372, 17897, 8156, 1025, 2478, 3645, 1012, 5733, 1012, 11867, 2072, 1025, 2478, 3645, 1012, 3192, 1012, 27425, 1025, 3415, 15327, 16768, 22471, 4948, 6558, 1035, 2663, 10790, 25185, 103...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using MatrixApi.Domain; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Data.Json; namespace MatrixPhone.DataModel { public static class UserDataSource { public static User user = new User(); public static User GetUser() { return user; } public static async void Login(string Email, string Password) { user.Email = Email; user.Password = Password; var httpClient = new appHttpClient(); var response = await httpClient.GetAsync("Users"); try { response.EnsureSuccessStatusCode(); // Throw on error code. } catch { user = new User(); } var result = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<User>(result); } public static string Auth() { var authText = string.Format("{0}:{1}", user.Email, user.Password); return Convert.ToBase64String(Encoding.UTF8.GetBytes(authText)); } } }
jdehlin/MatrixApi
MatrixPhone/DataModel/UserDataSource.cs
C#
apache-2.0
1,203
[ 30522, 2478, 8185, 9331, 2072, 1012, 5884, 1025, 2478, 8446, 6499, 6199, 1012, 1046, 3385, 1025, 2478, 2291, 1025, 2478, 2291, 1012, 6407, 1012, 12391, 1025, 2478, 2291, 1012, 11409, 4160, 1025, 2478, 2291, 1012, 3793, 1025, 2478, 2291, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * */ package com.fjnu.fund.domain; /** * @author Administrator * */ public class Fund { private Integer fundNo; private String fundName; private Float fundPrice; private String fundDes; private String fundStatus; private String fundDate; public Integer getFundNo() { return fundNo; } public void setFundNo(Integer fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public Float getFundPrice() { return fundPrice; } public void setFundPrice(Float fundPrice) { this.fundPrice = fundPrice; } public String getFundDes() { return fundDes; } public void setFundDes(String fundDes) { this.fundDes = fundDes; } public String getFundDate() { return fundDate; } public void setFundDate(String fundDate) { this.fundDate = fundDate; } public String getFundStatus() { return fundStatus; } public void setFundStatus(String fundStatus) { this.fundStatus = fundStatus; } }
WebbWangPrivate/JavaSystem
FundSystem/src/com/fjnu/fund/domain/Fund.java
Java
apache-2.0
1,040
[ 30522, 1013, 1008, 1008, 1008, 1008, 1013, 7427, 4012, 1012, 1042, 22895, 2226, 1012, 4636, 1012, 5884, 1025, 1013, 1008, 1008, 30524, 11263, 4859, 3630, 1006, 1007, 1063, 2709, 4636, 3630, 1025, 1065, 2270, 11675, 2275, 11263, 4859, 3630, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace ProcessWire; /** * ProcessWire WireData * * This is the base data container class used throughout ProcessWire. * It provides get and set access to properties internally stored in a $data array. * Otherwise it is identical to the Wire class. * * #pw-summary WireData is the base data-storage class used by many ProcessWire object types and most modules. * #pw-body = * WireData is very much like its parent `Wire` class with the fundamental difference being that it is designed * for runtime data storage. It provides this primarily through the built-in `get()` and `set()` methods for * getting and setting named properties to WireData objects. The most common example of a WireData object is * `Page`, the type used for all pages in ProcessWire. * * Properties set to a WireData object can also be set or accessed directly, like `$item->property` or using * array access like `$item[$property]`. If you `foreach()` a WireData object, the default behavior is to * iterate all of the properties/values present within it. * #pw-body * * May also be accessed as array. * * ProcessWire 3.x, Copyright 2016 by Ryan Cramer * https://processwire.com * * @method WireArray and($items = null) * */ class WireData extends Wire implements \IteratorAggregate, \ArrayAccess { /** * Array where get/set properties are stored * */ protected $data = array(); /** * Set a value to this object’s data * * ~~~~~ * // Set a value for a property * $item->set('foo', 'bar'); * * // Set a property value directly * $item->foo = 'bar'; * * // Set a property using array access * $item['foo'] = 'bar'; * ~~~~~ * * #pw-group-manipulation * * @param string $key Name of property you want to set * @param mixed $value Value of property * @return $this * @see WireData::setQuietly(), WireData::get() * */ public function set($key, $value) { if($key === 'data') { if(!is_array($value)) $value = (array) $value; return $this->setArray($value); } $v = isset($this->data[$key]) ? $this->data[$key] : null; if(!$this->isEqual($key, $v, $value)) $this->trackChange($key, $v, $value); $this->data[$key] = $value; return $this; } /** * Same as set() but without change tracking * * - If `$this->trackChanges()` is false, then this is no different than set(), since changes aren't being tracked. * - If `$this->trackChanges()` is true, then the value will be set quietly (i.e. not recorded in the changes list). * * #pw-group-manipulation * * @param string $key Name of property you want to set * @param mixed $value Value of property * @return $this * @see Wire::trackChanges(), WireData::set() * */ public function setQuietly($key, $value) { $track = $this->trackChanges(); $this->setTrackChanges(false); $this->set($key, $value); if($track) $this->setTrackChanges(true); return $this; } /** * Is $value1 equal to $value2? * * This template method provided so that descending classes can optionally determine * whether a change should be tracked. * * #pw-internal * * @param string $key Name of the property/key that triggered the check (see `WireData::set()`) * @param mixed $value1 Comparison value * @param mixed $value2 A second comparison value * @return bool True if values are equal, false if not * */ protected function isEqual($key, $value1, $value2) { if($key) {} // intentional to avoid unused argument notice // $key intentionally not used here, but may be used by descending classes return $value1 === $value2; } /** * Set an array of key=value pairs * * This is the same as the `WireData::set()` method except that it can set an array * of properties at once. * * #pw-group-manipulation * * @param array $data Associative array of where the keys are property names, and values are… values. * @return $this * @see WireData::set() * */ public function setArray(array $data) { foreach($data as $key => $value) $this->set($key, $value); return $this; } /** * Provides direct reference access to set values in the $data array * * @param string $key * @param mixed $value * return $this * */ public function __set($key, $value) { $this->set($key, $value); } /** * Retrieve the value for a previously set property, or retrieve an API variable * * - If the given $key is an object, it will cast it to a string. * - If the given $key is a string with "|" pipe characters in it, it will try all till it finds a non-empty value. * - If given an API variable name, it will return that API variable unless the class has direct access API variables disabled. * * ~~~~~ * // Retrieve the value of a property * $value = $item->get("some_property"); * * // Retrieve the value of the first non-empty property: * $value = $item->get("property1|property2|property2"); * * // Retrieve a value using array access * $value = $item["some_property"]; * ~~~~~ * * #pw-group-retrieval * * @param string|object $key Name of property you want to retrieve. * @return mixed|null Returns value of requested property, or null if the property was not found. * @see WireData::set() * */ public function get($key) { if(is_object($key)) $key = "$key"; if(array_key_exists($key, $this->data)) return $this->data[$key]; if(strpos($key, '|')) { $keys = explode('|', $key); foreach($keys as $k) { /** @noinspection PhpAssignmentInConditionInspection */ if($value = $this->get($k)) return $value; } } return parent::__get($key); // back to Wire } /** * Get or set a low-level data value * * Like get() or set() but will only get/set from the WireData's protected $data array. * This is used to bypass any extra logic a class may have added to its get() or set() * methods. The benefit of this method over get() is that it excludes API vars and potentially * other things (defined by descending classes) that you may not want. * * - To get a value, simply omit the $value argument. * - To set a value, specify both the $key and $value arguments. * - If you omit a $key and $value, this method will return the entire data array. * * #pw-group-manipulation * #pw-group-retrieval * * ~~~~~ * // Set a property * $item->data('some_property', 'some value'); * * // Get the value of a previously set property * $value = $item->data('some_property'); * ~~~~~ * * @param string|array $key Property you want to get or set, or associative array of properties you want to set. * @param mixed $value Optionally specify a value if you want to set rather than get. * Or Specify boolean TRUE if setting an array via $key and you want to overwrite any existing values (rather than merge). * @return array|WireData|null Returns one of the following: * - `mixed` - Actual value if getting a previously set value. * - `null` - If you are attempting to get a value that has not been set. * - `$this` - If you are setting a value. */ public function data($key = null, $value = null) { if(is_null($key)) return $this->data; if(is_array($key)) { if($value === true) { $this->data = $key; } else { $this->data = array_merge($this->data, $key); } return $this; } else if(is_null($value)) { return isset($this->data[$key]) ? $this->data[$key] : null; } else { $this->data[$key] = $value; return $this; } } /** * Returns the full array of properties set to this object * * If descending classes also store data in other containers, they may want to * override this method to include that data as well. * * #pw-group-retrieval * * @return array Returned array is associative and indexed by property name. * */ public function getArray() { return $this->data; } /** * Get a property via dot syntax: field.subfield (static) * * Static version for internal core use. Use the non-static getDot() instead. * * #pw-internal * * @param string $key * @param Wire $from The instance you want to pull the value from * @return null|mixed Returns value if found or null if not * */ public static function _getDot($key, Wire $from) { $key = trim($key, '.'); if(strpos($key, '.')) { // dot present $keys = explode('.', $key); // convert to array $key = array_shift($keys); // get first item } else { // dot not present $keys = array(); } if($from->wire($key) !== null) return null; // don't allow API vars to be retrieved this way if($from instanceof WireData) $value = $from->get($key); else if($from instanceof WireArray) $value = $from->getProperty($key); else $value = $from->$key; if(!count($keys)) return $value; // final value if(is_object($value)) { if(count($keys) > 1) { $keys = implode('.', $keys); // convert back to string if($value instanceof WireData) $value = $value->getDot($keys); // for override potential else $value = self::_getDot($keys, $value); } else { $key = array_shift($keys); // just one key left, like 'title' if($value instanceof WireData) { $value = $value->get($key); } else if($value instanceof WireArray) { if($key == 'count') { $value = count($value); } else { $a = array(); foreach($value as $v) $a[] = $v->get($key); $value = $a; } } } } else { // there is a dot property remaining and nothing to send it to $value = null; } return $value; } /** * Get a property via dot syntax: field.subfield.subfield * * Some classes descending WireData may choose to add a call to this as part of their * get() method as a syntax convenience. * * ~~~~~ * $value = $item->get("parent.title"); * ~~~~~ * * #pw-group-retrieval * * @param string $key Name of property you want to retrieve in "a.b" or "a.b.c" format * @return null|mixed Returns value if found or null if not * */ public function getDot($key) { return self::_getDot($key, $this); } /** * Provides direct reference access to variables in the $data array * * Otherwise the same as get() * * @param string $key * @return mixed|null * */ public function __get($key) { return $this->get($key); } /** * Enables use of $var('key') * * @param string $key * @return mixed * */ public function __invoke($key) { return $this->get($key); } /** * Remove a previously set property * * ~~~~~ * $item->remove('some_property'); * ~~~~~ * * #pw-group-manipulation * * @param string $key Name of property you want to remove * @return $this * */ public function remove($key) { $value = isset($this->data[$key]) ? $this->data[$key] : null; $this->trackChange("unset:$key", $value, null); unset($this->data[$key]); return $this; } /** * Enables the object data properties to be iterable as an array * * ~~~~~ * foreach($item as $key => $value) { * // ... * } * ~~~~~ * * #pw-group-retrieval * * @return \ArrayObject * */ public function getIterator() { return new \ArrayObject($this->data); } /** * Does this object have the given property? * * ~~~~~ * if($item->has('some_property')) { * // the item has some_property * } * ~~~~~ * * #pw-group-retrieval * * @param string $key Name of property you want to check. * @return bool True if it has the property, false if not. * */ public function has($key) { return ($this->get($key) !== null); } /** * Take the current item and append the given item(s), returning a new WireArray * * This is for syntactic convenience in fluent interfaces. * ~~~~~ * if($page->and($page->parents)->has("featured=1")) { * // page or one of its parents has a featured property with value of 1 * } * ~~~~~ * * #pw-group-retrieval * * @param WireArray|WireData|string|null $items May be any of the following: * - `WireData` object (or derivative) * - `WireArray` object (or derivative) * - Name of any property from this object that returns one of the above. * - Omit argument to simply return this object in a WireArray * @return WireArray Returns a WireArray of this object *and* the one(s) given. * @throws WireException If invalid argument supplied. * */ public function ___and($items = null) { if(is_string($items)) $items = $this->get($items); if($items instanceof WireArray) { // great, that's what we want $a = clone $items; $a->prepend($this); } else if($items instanceof WireData || is_null($items)) { // single item $className = $this->className(true) . 'Array'; if(!class_exists($className)) $className = wireClassName('WireArray', true); $a = $this->wire(new $className()); $a->add($this); if($items) $a->add($items); } else { // unknown throw new WireException('Invalid argument provided to WireData::and(...)'); } return $a; } /** * Ensures that isset() and empty() work for this classes properties. * * #pw-internal * * @param string $key * @return bool * */ public function __isset($key) { return isset($this->data[$key]); } /** * Ensures that unset() works for this classes data. * * #pw-internal * * @param string $key * */ public function __unset($key) { $this->remove($key); } /** * Sets an index in the WireArray. * * For the ArrayAccess interface. * * #pw-internal * * @param int|string $key Key of item to set. * @param int|string|array|object $value Value of item. * */ public function offsetSet($key, $value) { $this->set($key, $value); } /** * Returns the value of the item at the given index, or false if not set. * * #pw-internal * * @param int|string $key Key of item to retrieve. * @return int|string|array|object Value of item requested, or false if it doesn't exist. * */ public function offsetGet($key) { $value = $this->get($key); return is_null($value) ? false : $value; } /** * Unsets the value at the given index. * * For the ArrayAccess interface. * * #pw-internal * * @param int|string $key Key of the item to unset. * @return bool True if item existed and was unset. False if item didn't exist. * */ public function offsetUnset($key) { if($this->__isset($key)) { $this->remove($key); return true; } else { return false; } } /** * Determines if the given index exists in this WireData. * * For the ArrayAccess interface. * * #pw-internal * * @param int|string $key Key of the item to check for existence. * @return bool True if the item exists, false if not. * */ public function offsetExists($key) { return $this->__isset($key); } /** * debugInfo PHP 5.6+ magic method * * @return array * */ public function __debugInfo() { $info = parent::__debugInfo(); if(count($this->data)) $info['data'] = $this->data; return $info; } }
sunlix/ProcessWire
wire/core/WireData.php
PHP
mpl-2.0
15,064
[ 30522, 1026, 1029, 25718, 3415, 15327, 2832, 20357, 1025, 1013, 1008, 1008, 1008, 2832, 20357, 17502, 6790, 1008, 1008, 2023, 2003, 1996, 2918, 2951, 11661, 2465, 2109, 2802, 2832, 20357, 1012, 1008, 2009, 3640, 2131, 1998, 2275, 3229, 2000...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * from: FreeBSD: src/sys/tools/fw_stub.awk,v 1.6 2007/03/02 11:42:53 flz */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/dev/cxgb/cxgb_t3fw.c 189643 2009-03-10 19:22:45Z gnn $"); #include <sys/param.h> #include <sys/errno.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/linker.h> #include <sys/firmware.h> #include <sys/systm.h> #include <cxgb_t3fw.h> #include <t3b_protocol_sram.h> #include <t3b_tp_eeprom.h> #include <t3c_protocol_sram.h> #include <t3c_tp_eeprom.h> static int cxgb_t3fw_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3fw", t3fw, (size_t)t3fw_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3fw"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3fw_mod = { "cxgb_t3fw", cxgb_t3fw_modevent, 0 }; DECLARE_MODULE(cxgb_t3fw, cxgb_t3fw_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3fw, 1); MODULE_DEPEND(cxgb_t3fw, firmware, 1, 1, 1); static int cxgb_t3b_protocol_sram_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_protocol_sram", t3b_protocol_sram, (size_t)t3b_protocol_sram_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_protocol_sram"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3b_protocol_sram_mod = { "cxgb_t3b_protocol_sram", cxgb_t3b_protocol_sram_modevent, 0 }; DECLARE_MODULE(cxgb_t3b_protocol_sram, cxgb_t3b_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_protocol_sram, 1); MODULE_DEPEND(cxgb_t3b_protocol_sram, firmware, 1, 1, 1); static int cxgb_t3b_tp_eeprom_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_tp_eeprom", t3b_tp_eeprom, (size_t)t3b_tp_eeprom_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3b_tp_eeprom_mod = { "cxgb_t3b_tp_eeprom", cxgb_t3b_tp_eeprom_modevent, 0 }; DECLARE_MODULE(cxgb_t3b_tp_eeprom, cxgb_t3b_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3b_tp_eeprom, firmware, 1, 1, 1); static int cxgb_t3c_protocol_sram_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_protocol_sram", t3c_protocol_sram, (size_t)t3c_protocol_sram_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_protocol_sram"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3c_protocol_sram_mod = { "cxgb_t3c_protocol_sram", cxgb_t3c_protocol_sram_modevent, 0 }; DECLARE_MODULE(cxgb_t3c_protocol_sram, cxgb_t3c_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_protocol_sram, 1); MODULE_DEPEND(cxgb_t3c_protocol_sram, firmware, 1, 1, 1); static int cxgb_t3c_tp_eeprom_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_tp_eeprom", t3c_tp_eeprom, (size_t)t3c_tp_eeprom_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3c_tp_eeprom_mod = { "cxgb_t3c_tp_eeprom", cxgb_t3c_tp_eeprom_modevent, 0 }; DECLARE_MODULE(cxgb_t3c_tp_eeprom, cxgb_t3c_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3c_tp_eeprom, firmware, 1, 1, 1);
dcui/FreeBSD-9.3_kernel
sys/dev/cxgb/cxgb_t3fw.c
C
bsd-3-clause
4,506
[ 30522, 1013, 1008, 1008, 2013, 1024, 2489, 5910, 2094, 1024, 5034, 2278, 1013, 25353, 2015, 1013, 5906, 1013, 1042, 2860, 1035, 24646, 2497, 1012, 22091, 2243, 1010, 1058, 1015, 1012, 1020, 2289, 1013, 6021, 1013, 6185, 2340, 1024, 4413, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
@echo off CLS %header% echo. if not exist "Programme\HackMii Installer" mkdir "Programme\HackMii Installer" echo Downloade den HackMii Installer... start /min/wait Support\wget -c -l1 -r -nd --retr-symlinks -t10 -T30 --random-wait --reject "*.html" --reject "%2A" --reject "get.php@file=hackmii_installer_v1.0*" "http://bootmii.org/download/" move get.php* hackmii-installer_v1.2.zip >NUL start /min/wait Support\7za e -aoa hackmii-installer_v1.2.zip -o"Programme\HackMii Installer" *.elf -r del hackmii* :endedesmoduls
Brawl345/WiiDataDownloader-Module
HackMii Installer herunterladen.bat
Batchfile
isc
521
[ 30522, 1030, 9052, 2125, 18856, 2015, 1003, 20346, 1003, 9052, 1012, 2065, 2025, 4839, 1000, 4746, 1032, 20578, 4328, 2072, 16500, 2121, 1000, 12395, 4305, 2099, 1000, 4746, 1032, 20578, 4328, 2072, 16500, 2121, 1000, 9052, 8816, 2063, 7939...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2014 - 2017 Board of Regents of the University of * Wisconsin-Madison, University of Konstanz and Brian Northan. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * 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 HOLDERS 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. * #L% */ package net.imagej.ops.create.img; import net.imagej.ops.Ops; import net.imagej.ops.special.chain.UFViaUFSameIO; import net.imagej.ops.special.function.Functions; import net.imagej.ops.special.function.UnaryFunctionOp; import net.imglib2.Interval; import net.imglib2.img.Img; import net.imglib2.type.numeric.real.DoubleType; import org.scijava.plugin.Plugin; /** * Creates an {@link Img} from an {@link Interval} with no additional hints. * {@link Interval} contents are not copied. * * @author Curtis Rueden */ @Plugin(type = Ops.Create.Img.class) public class CreateImgFromInterval extends UFViaUFSameIO<Interval, Img<DoubleType>> implements Ops.Create.Img { @Override @SuppressWarnings({"rawtypes", "unchecked"}) public UnaryFunctionOp<Interval, Img<DoubleType>> createWorker( final Interval input) { // NB: Intended to match CreateImgFromDimsAndType. return (UnaryFunctionOp) Functions.unary(ops(), Ops.Create.Img.class, Img.class, input, new DoubleType()); } }
gab1one/imagej-ops
src/main/java/net/imagej/ops/create/img/CreateImgFromInterval.java
Java
bsd-2-clause
2,532
[ 30522, 1013, 1008, 1008, 1001, 1003, 1048, 1008, 3746, 3501, 4007, 2005, 4800, 22172, 6132, 19301, 3746, 6364, 1998, 4106, 1012, 1008, 1003, 1003, 1008, 9385, 1006, 1039, 1007, 2297, 1011, 2418, 2604, 1997, 22832, 1997, 1996, 2118, 1997, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """DocExtract REST and Web API Exposes document extration facilities to the world """ from tempfile import NamedTemporaryFile from invenio.webinterface_handler import WebInterfaceDirectory from invenio.webuser import collect_user_info from invenio.webpage import page from invenio.config import CFG_TMPSHAREDDIR, CFG_ETCDIR from invenio.refextract_api import extract_references_from_file_xml, \ extract_references_from_url_xml, \ extract_references_from_string_xml from invenio.bibformat_engine import format_record def check_login(req): """Check that the user is logged in""" user_info = collect_user_info(req) if user_info['email'] == 'guest': # 1. User is guest: must login prior to upload # return 'Please login before uploading file.' pass def check_url(url): """Check that the url we received is not gibberish""" return url.startswith('http://') or \ url.startswith('https://') or \ url.startswith('ftp://') def extract_from_pdf_string(pdf): """Extract references from a pdf stored in a string Given a string representing a pdf, this function writes the string to disk and passes it to refextract. We need to create a temoporary file because we need to run pdf2text on it""" # Save new record to file tf = NamedTemporaryFile(prefix='docextract-pdf', dir=CFG_TMPSHAREDDIR) try: tf.write(pdf) tf.flush() refs = extract_references_from_file_xml(tf.name) finally: # Also deletes the file tf.close() return refs def make_arxiv_url(arxiv_id): """Make a url we can use to download a pdf from arxiv Arguments: arxiv_id -- the arxiv id of the record to link to """ return "http://arxiv.org/pdf/%s.pdf" % arxiv_id class WebInterfaceAPIDocExtract(WebInterfaceDirectory): """DocExtract REST API""" _exports = [ ('extract-references-pdf', 'extract_references_pdf'), ('extract-references-pdf-url', 'extract_references_pdf_url'), ('extract-references-txt', 'extract_references_txt'), ] def extract_references_pdf(self, req, form): """Extract references from uploaded pdf""" check_login(req) if 'pdf' not in form: return 'No PDF file uploaded' return extract_from_pdf_string(form['pdf'].stream.read()) def extract_references_pdf_url(self, req, form): """Extract references from the pdf pointed by the passed url""" check_login(req) if 'url' not in form: return 'No URL specified' url = form['url'] if not check_url(url): return 'Invalid URL specified' return extract_references_from_url_xml(url) def extract_references_txt(self, req, form): """Extract references from plain text""" check_login(req) if 'txt' not in form: return 'No text specified' txt = form['txt'].stream.read() return extract_references_from_string_xml(txt) class WebInterfaceDocExtract(WebInterfaceDirectory): """DocExtract API""" _exports = ['api', ('extract-references', 'extract_references'), ('example.pdf', 'example_pdf'), ] api = WebInterfaceAPIDocExtract() def example_pdf(self, req, _form): """Serve a test pdf for tests""" f = open("%s/docextract/example.pdf" % CFG_ETCDIR, 'rb') try: req.write(f.read()) finally: f.close() def extract_references_template(self): """Template for reference extraction page""" return """Please specify a pdf or a url or some references to parse <form action="extract-references" method="post" enctype="multipart/form-data"> <p>PDF: <input type="file" name="pdf" /></p> <p>arXiv: <input type="text" name="arxiv" /></p> <p>URL: <input type="text" name="url" style="width: 600px;"/></p> <textarea name="txt" style="width: 500px; height: 500px;"></textarea> <p><input type="submit" /></p> </form> """ def extract_references(self, req, form): """Refrences extraction page This page can be used for authors to test their pdfs against our refrences extraction process""" user_info = collect_user_info(req) # Handle the 3 POST parameters if 'pdf' in form and form['pdf']: pdf = form['pdf'] references_xml = extract_from_pdf_string(pdf) elif 'arxiv' in form and form['arxiv']: url = make_arxiv_url(arxiv_id=form['arxiv']) references_xml = extract_references_from_url_xml(url) elif 'url' in form and form['url']: url = form['url'] references_xml = extract_references_from_url_xml(url) elif 'txt' in form and form['txt']: txt = form['txt'] references_xml = extract_references_from_string_xml(txt) else: references_xml = None # If we have not uploaded anything yet # Display the form that allows us to do so if not references_xml: out = self.extract_references_template() else: out = """ <style type="text/css"> #referenceinp_link { display: none; } </style> """ out += format_record(0, 'hdref', xml_record=references_xml.encode('utf-8'), user_info=user_info) # Render the page (including header, footer) return page(title='References Extractor', body=out, uid=user_info['uid'], req=req)
labordoc/labordoc-next
modules/docextract/lib/docextract_webinterface.py
Python
gpl-2.0
6,745
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1001, 1001, 1001, 1001, 2023, 5371, 2003, 2112, 1997, 1999, 8159, 3695, 1012, 1001, 1001, 9385, 1006, 1039, 1007, 2384, 1010, 2294, 1010, 2289, 1010, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Copyright 2014-2016 CyberVision, 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 org.kaaproject.kaa.server.admin.client.mvp.view.schema; import java.util.Comparator; import org.kaaproject.avro.ui.gwt.client.widget.grid.cell.ActionsButtonCell; import org.kaaproject.avro.ui.gwt.client.widget.grid.event.RowActionEvent; import org.kaaproject.kaa.common.dto.BaseSchemaDto; import org.kaaproject.kaa.server.admin.client.mvp.view.grid.AbstractKaaGrid; import org.kaaproject.kaa.server.admin.client.mvp.view.grid.KaaRowAction; import org.kaaproject.kaa.server.admin.client.util.Utils; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.DataGrid; import com.google.gwt.user.cellview.client.Header; import com.google.gwt.user.cellview.client.SafeHtmlHeader; public class BaseCtlSchemasGrid<T extends BaseSchemaDto> extends AbstractKaaGrid<T, String> { private static final int DEFAULT_PAGE_SIZE = 12; private Column<T, T> downloadSchemaColumn; public BaseCtlSchemasGrid() { super(Unit.PX, false, DEFAULT_PAGE_SIZE); } @Override protected float constructColumnsImpl(DataGrid<T> table) { float prefWidth = 0; prefWidth += constructStringColumn(table, Utils.constants.version(), new StringValueProvider<T>() { @Override public String getValue(T item) { return item.getVersion()+""; } }, new Comparator<T>() { @Override public int compare(T o1, T o2) { return o1.compareTo(o2); } }, Boolean.FALSE, 80); prefWidth += constructStringColumn(table, Utils.constants.name(), new StringValueProvider<T>() { @Override public String getValue(T item) { return item.getName(); } }, new Comparator<T>() { @Override public int compare(T o1, T o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }, null, true, 80); prefWidth += constructStringColumn(table, Utils.constants.author(), new StringValueProvider<T>() { @Override public String getValue(T item) { return item.getCreatedUsername(); } }, 60); prefWidth += constructStringColumn(table, Utils.constants.dateCreated(), new StringValueProvider<T>() { @Override public String getValue(T item) { return Utils.millisecondsToDateString(item.getCreatedTime()); } }, 40); return prefWidth; } @Override protected float constructActions(DataGrid<T> table, float prefWidth) { float result = 0; if (downloadSchemaColumn == null || table.getColumnIndex(downloadSchemaColumn) == -1) { Header<SafeHtml> downloadRecordSchemaHeader = new SafeHtmlHeader( SafeHtmlUtils.fromSafeConstant(Utils.constants.downloadRecordSchema())); downloadSchemaColumn = constructDownloadSchemaColumn(); table.addColumn(downloadSchemaColumn, downloadRecordSchemaHeader); table.setColumnWidth(downloadSchemaColumn, 60, Unit.PX); result += 60; } return result; } protected Column<T, T> constructDownloadSchemaColumn() { ActionsButtonCell<T> cell = new ActionsButtonCell<>(Utils.resources.export(), Utils.constants.export()); cell.addMenuItem(Utils.constants.shallow(), new ActionsButtonCell.ActionMenuItemListener<T>() { @Override public void onMenuItemSelected(T value) { RowActionEvent<String> schemaEvent = new RowActionEvent<>(value.getCtlSchemaId(), KaaRowAction.CTL_EXPORT_SHALLOW); fireEvent(schemaEvent); } }); cell.addMenuItem(Utils.constants.deep(), new ActionsButtonCell.ActionMenuItemListener<T>() { @Override public void onMenuItemSelected(T value) { RowActionEvent<String> schemaEvent = new RowActionEvent<>(value.getCtlSchemaId(), KaaRowAction.CTL_EXPORT_DEEP); fireEvent(schemaEvent); } }); cell.addMenuItem(Utils.constants.flat(), new ActionsButtonCell.ActionMenuItemListener<T>() { @Override public void onMenuItemSelected(T value) { RowActionEvent<String> schemaEvent = new RowActionEvent<>(value.getCtlSchemaId(), KaaRowAction.CTL_EXPORT_FLAT); fireEvent(schemaEvent); } }); cell.addMenuItem(Utils.constants.javaLibrary(), new ActionsButtonCell.ActionMenuItemListener<T>() { @Override public void onMenuItemSelected(T value) { RowActionEvent<String> schemaEvent = new RowActionEvent<>(value.getCtlSchemaId(), KaaRowAction.CTL_EXPORT_LIBRARY); fireEvent(schemaEvent); } }); Column<T, T> column = new Column<T, T>(cell) { @Override public T getValue(T item) { return item; } }; return column; } }
Deepnekroz/kaa
server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/view/schema/BaseCtlSchemasGrid.java
Java
apache-2.0
6,465
[ 30522, 1013, 1008, 1008, 1008, 9385, 2297, 1011, 2355, 16941, 17084, 1010, 4297, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, 2224, 2023, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
from django.contrib import admin try: from django.contrib.auth import get_permission_codename except ImportError: # pragma: no cover # Django < 1.6 def get_permission_codename(action, opts): return '%s_%s' % (action, opts.object_name.lower()) class ObjectPermissionsModelAdminMixin(object): def has_change_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('delete', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) class ObjectPermissionsInlineModelAdminMixin(ObjectPermissionsModelAdminMixin): def has_change_permission(self, request, obj=None): # pragma: no cover opts = self.opts if opts.auto_created: for field in opts.fields: if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): # pragma: no cover if self.opts.auto_created: return self.has_change_permission(request, obj) return super(ObjectPermissionsInlineModelAdminMixin, self).has_delete_permission(request, obj) class ObjectPermissionsModelAdmin(ObjectPermissionsModelAdminMixin, admin.ModelAdmin): pass class ObjectPermissionsStackedInline(ObjectPermissionsInlineModelAdminMixin, admin.StackedInline): pass class ObjectPermissionsTabularInline(ObjectPermissionsInlineModelAdminMixin, admin.TabularInline): pass
smcoll/django-rules
rules/contrib/admin.py
Python
mit
1,879
[ 30522, 2013, 6520, 23422, 1012, 9530, 18886, 2497, 12324, 4748, 10020, 3046, 1024, 2013, 6520, 23422, 1012, 9530, 18886, 2497, 1012, 8740, 2705, 12324, 2131, 1035, 6656, 1035, 3642, 18442, 3272, 12324, 2121, 29165, 1024, 1001, 10975, 8490, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (c) 2010-2017 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.testing.sanity; import static com.evolveum.midpoint.prism.util.PrismAsserts.assertEqualsPolyString; import static com.evolveum.midpoint.prism.util.PrismAsserts.assertParentConsistency; import static com.evolveum.midpoint.test.IntegrationTestTools.assertAttributeNotNull; import static com.evolveum.midpoint.test.IntegrationTestTools.assertNoRepoCache; import static com.evolveum.midpoint.test.IntegrationTestTools.assertNotEmpty; import static com.evolveum.midpoint.test.IntegrationTestTools.displayJaxb; import static com.evolveum.midpoint.test.IntegrationTestTools.getAttributeValues; import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import javax.xml.ws.Holder; import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.*; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.xnode.MapXNode; import com.evolveum.midpoint.prism.xnode.XNode; import com.evolveum.midpoint.util.exception.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.opends.server.core.ModifyOperation; import org.opends.server.protocols.internal.InternalSearchOperation; import org.opends.server.types.*; import org.opends.server.types.ModificationType; import org.opends.server.util.ChangeRecordEntry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition; import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; import com.evolveum.midpoint.prism.crypto.EncryptionException; import com.evolveum.midpoint.prism.match.MatchingRule; import com.evolveum.midpoint.prism.match.MatchingRuleRegistry; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.schema.SchemaRegistry; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.CapabilityUtil; import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.ResultHandler; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; import com.evolveum.midpoint.schema.util.SchemaDebugUtil; import com.evolveum.midpoint.schema.util.SchemaTestConstants; import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.test.Checker; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.ObjectChecker; import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.DerbyController; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.JAXBUtil; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaOperationListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.PropertyReferenceListType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.GenericObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaOperationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ProjectionPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectShadowChangeDescriptionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectTypeDefinitionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SchemaHandlingType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SelectorQualifiedGetOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage; import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultType; import com.evolveum.midpoint.xml.ns._public.common.fault_3.ObjectAlreadyExistsFaultType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ActivationCapabilityType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType; import com.evolveum.prism.xml.ns._public.query_3.QueryType; import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; import com.evolveum.prism.xml.ns._public.types_3.EncryptedDataType; import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; import com.evolveum.prism.xml.ns._public.types_3.ModificationTypeType; import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; import com.evolveum.prism.xml.ns._public.types_3.RawType; /** * Sanity test suite. * <p/> * It tests the very basic representative test cases. It does not try to be * complete. It rather should be quick to execute and pass through the most * representative cases. It should test all the system components except for * GUI. Therefore the test cases are selected to pass through most of the * components. * <p/> * It is using embedded H2 repository and embedded OpenDJ instance as a testing * resource. The repository is instantiated from the Spring context in the * same way as all other components. OpenDJ instance is started explicitly using * BeforeClass method. Appropriate resource definition to reach the OpenDJ * instance is provided in the test data and is inserted in the repository as * part of test initialization. * * @author Radovan Semancik */ @ContextConfiguration(locations = {"classpath:ctx-sanity-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSanity extends AbstractModelIntegrationTest { private static final String REPO_DIR_NAME = "src/test/resources/repo/"; private static final String REQUEST_DIR_NAME = "src/test/resources/request/"; private static final File REQUEST_DIR = new File(REQUEST_DIR_NAME); private static final String SYSTEM_CONFIGURATION_FILENAME = REPO_DIR_NAME + "system-configuration.xml"; private static final String SYSTEM_CONFIGURATION_OID = "00000000-0000-0000-0000-000000000001"; private static final String ROLE_SUPERUSER_FILENAME = REPO_DIR_NAME + "role-superuser.xml"; private static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004"; private static final String RESOURCE_OPENDJ_FILENAME = REPO_DIR_NAME + "resource-opendj.xml"; private static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; private static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; protected static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS,"inetOrgPerson"); private static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID"; private static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn"; private static final String RESOURCE_DERBY_FILENAME = REPO_DIR_NAME + "resource-derby.xml"; private static final String RESOURCE_DERBY_OID = "ef2bc95b-76e0-59e2-86d6-999902d3abab"; private static final String RESOURCE_BROKEN_FILENAME = REPO_DIR_NAME + "resource-broken.xml"; private static final String RESOURCE_BROKEN_OID = "ef2bc95b-76e0-59e2-ffff-ffffffffffff"; private static final String RESOURCE_DUMMY_FILENAME = REPO_DIR_NAME + "resource-dummy.xml"; private static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000004"; private static final String CONNECTOR_LDAP_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector"; private static final String CONNECTOR_DBTABLE_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-databasetable/org.identityconnectors.databasetable.DatabaseTableConnector"; private static final String CONNECTOR_BROKEN_FILENAME = REPO_DIR_NAME + "connector-broken.xml"; private static final String CONNECTOR_BROKEN_OID = "cccccccc-76e0-59e2-ffff-ffffffffffff"; private static final String TASK_OPENDJ_SYNC_FILENAME = REPO_DIR_NAME + "task-opendj-sync.xml"; private static final String TASK_OPENDJ_SYNC_OID = "91919191-76e0-59e2-86d6-3d4f02d3ffff"; private static final String TASK_USER_RECOMPUTE_FILENAME = REPO_DIR_NAME + "task-user-recompute.xml"; private static final String TASK_USER_RECOMPUTE_OID = "91919191-76e0-59e2-86d6-3d4f02d3aaaa"; private static final String TASK_OPENDJ_RECON_FILENAME = REPO_DIR_NAME + "task-opendj-reconciliation.xml"; private static final String TASK_OPENDJ_RECON_OID = "91919191-76e0-59e2-86d6-3d4f02d30000"; private static final String SAMPLE_CONFIGURATION_OBJECT_FILENAME = REPO_DIR_NAME + "sample-configuration-object.xml"; private static final String SAMPLE_CONFIGURATION_OBJECT_OID = "c0c010c0-d34d-b33f-f00d-999111111111"; private static final String USER_TEMPLATE_FILENAME = REPO_DIR_NAME + "user-template.xml"; private static final String USER_TEMPLATE_OID = "c0c010c0-d34d-b33f-f00d-777111111111"; private static final String USER_ADMINISTRATOR_FILENAME = REPO_DIR_NAME + "user-administrator.xml"; private static final String USER_ADMINISTRATOR_NAME = "administrator"; private static final String USER_ADMINISTRATOR_OID = "00000000-0000-0000-0000-000000000002"; private static final String USER_JACK_FILENAME = REPO_DIR_NAME + "user-jack.xml"; private static final File USER_JACK_FILE = new File(USER_JACK_FILENAME); private static final String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; private static final String USER_JACK_LDAP_UID = "jack"; private static final String USER_JACK_LDAP_DN = "uid=" + USER_JACK_LDAP_UID + "," + OPENDJ_PEOPLE_SUFFIX; private static final String USER_GUYBRUSH_FILENAME = REPO_DIR_NAME + "user-guybrush.xml"; private static final File USER_GUYBRUSH_FILE = new File(USER_GUYBRUSH_FILENAME); private static final String USER_GUYBRUSH_OID = "c0c010c0-d34d-b33f-f00d-111111111222"; private static final String USER_GUYBRUSH_USERNAME = "guybrush"; private static final String USER_GUYBRUSH_LDAP_UID = "guybrush"; private static final String USER_GUYBRUSH_LDAP_DN = "uid=" + USER_GUYBRUSH_LDAP_UID + "," + OPENDJ_PEOPLE_SUFFIX; private static final String USER_E_LINK_ACTION_FILENAME = REPO_DIR_NAME + "user-e.xml"; private static final File USER_E_LINK_ACTION_FILE = new File(USER_E_LINK_ACTION_FILENAME); private static final String LDIF_E_FILENAME_LINK = "src/test/resources/request/e-create.ldif"; private static final String ROLE_PIRATE_FILENAME = REPO_DIR_NAME + "role-pirate.xml"; private static final String ROLE_PIRATE_OID = "12345678-d34d-b33f-f00d-987987987988"; private static final String ROLE_SAILOR_FILENAME = REPO_DIR_NAME + "role-sailor.xml"; private static final String ROLE_SAILOR_OID = "12345678-d34d-b33f-f00d-987955553535"; private static final String ROLE_CAPTAIN_FILENAME = REPO_DIR_NAME + "role-captain.xml"; private static final String ROLE_CAPTAIN_OID = "12345678-d34d-b33f-f00d-987987cccccc"; private static final String ROLE_JUDGE_FILENAME = REPO_DIR_NAME + "role-judge.xml"; private static final String ROLE_JUDGE_OID = "12345111-1111-2222-1111-121212111111"; private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account.xml"; private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account-derby.xml"; private static final String USER_JACK_DERBY_LOGIN = "jsparrow"; private static final String REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME = REQUEST_DIR_NAME + "user-modify-fullname-locality.xml"; private static final String REQUEST_USER_MODIFY_GIVENNAME_FILENAME = REQUEST_DIR_NAME + "user-modify-givenname.xml"; private static final String REQUEST_USER_MODIFY_PASSWORD_FILENAME = REQUEST_DIR_NAME + "user-modify-password.xml"; private static final String REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME = REQUEST_DIR_NAME + "user-modify-activation-disable.xml"; private static final String REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME = REQUEST_DIR_NAME + "user-modify-activation-enable.xml"; private static final String REQUEST_USER_MODIFY_NAME_FILENAME = REQUEST_DIR_NAME + "user-modify-name.xml"; private static final String REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-pirate.xml"; private static final String REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-captain-1.xml"; private static final String REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-captain-2.xml"; private static final String REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-judge.xml"; private static final String REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-pirate.xml"; private static final String REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-captain-1.xml"; private static final String REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-captain-2.xml"; private static final File REQUEST_ACCOUNT_MODIFY_ATTRS_FILE = new File(REQUEST_DIR, "account-modify-attrs.xml"); private static final File REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE = new File(REQUEST_DIR, "account-modify-roomnumber.xml"); private static final File REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE = new File(REQUEST_DIR, "account-modify-roomnumber-explicit-type.xml"); private static final File REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE = new File(REQUEST_DIR, "account-modify-bad-path.xml"); private static final String LDIF_WILL_FILENAME = REQUEST_DIR_NAME + "will.ldif"; private static final File LDIF_WILL_MODIFY_FILE = new File (REQUEST_DIR_NAME, "will-modify.ldif"); private static final String LDIF_WILL_WITHOUT_LOCATION_FILENAME = REQUEST_DIR_NAME + "will-without-location.ldif"; private static final String WILL_NAME = "wturner"; private static final String LDIF_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "angelika.ldif"; private static final String ANGELIKA_NAME = "angelika"; private static final String ACCOUNT_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "account-angelika.xml"; private static final String LDIF_ELAINE_FILENAME = REQUEST_DIR_NAME + "elaine.ldif"; private static final String ELAINE_NAME = "elaine"; private static final File LDIF_GIBBS_MODIFY_FILE = new File (REQUEST_DIR_NAME, "gibbs-modify.ldif"); private static final String LDIF_HERMAN_FILENAME = REQUEST_DIR_NAME + "herman.ldif"; private static final Trace LOGGER = TraceManager.getTrace(TestSanity.class); private static final String NS_MY = "http://whatever.com/my"; private static final ItemName MY_SHIP_STATE = new ItemName(NS_MY, "shipState"); private static final ItemName MY_DEAD = new ItemName(NS_MY, "dead"); private static final long WAIT_FOR_LOOP_SLEEP_MILIS = 1000; /** * Unmarshalled resource definition to reach the embedded OpenDJ instance. * Used for convenience - the tests method may find it handy. */ private static ResourceType resourceTypeOpenDjrepo; private static ResourceType resourceDerby; private static String accountShadowOidOpendj; private static String accountShadowOidDerby; private static String accountShadowOidGuybrushOpendj; private static String accountGuybrushOpendjEntryUuuid = null; private static String originalJacksLdapPassword; private static String lastJacksLdapPassword = null; private int lastSyncToken; @Autowired(required = true) private MatchingRuleRegistry matchingRuleRegistry; // This will get called from the superclass to init the repository // It will be called only once public void initSystem(Task initTask, OperationResult initResult) throws Exception { LOGGER.trace("initSystem"); try{ super.initSystem(initTask, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILENAME, initResult); repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult); // This should discover the connectors LOGGER.trace("initSystem: trying modelService.postInit()"); modelService.postInit(initResult); LOGGER.trace("initSystem: modelService.postInit() done"); login(USER_ADMINISTRATOR_NAME); // We need to add config after calling postInit() so it will not be applied. // we want original logging configuration from the test logback config file, not // the one from the system config. repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILENAME, initResult); // Add broken connector before importing resources repoAddObjectFromFile(CONNECTOR_BROKEN_FILENAME, initResult); // Need to import instead of add, so the (dynamic) connector reference // will be resolved // correctly importObjectFromFile(RESOURCE_OPENDJ_FILENAME, initResult); importObjectFromFile(RESOURCE_BROKEN_FILENAME, initResult); repoAddObjectFromFile(SAMPLE_CONFIGURATION_OBJECT_FILENAME, initResult); repoAddObjectFromFile(USER_TEMPLATE_FILENAME, initResult); repoAddObjectFromFile(ROLE_SAILOR_FILENAME, initResult); repoAddObjectFromFile(ROLE_PIRATE_FILENAME, initResult); repoAddObjectFromFile(ROLE_CAPTAIN_FILENAME, initResult); repoAddObjectFromFile(ROLE_JUDGE_FILENAME, initResult); } catch (Exception ex){ LOGGER.error("erro: {}", ex); throw ex; } } /** * Initialize embedded OpenDJ instance Note: this is not in the abstract * superclass so individual tests may avoid starting OpenDJ. */ @Override public void startResources() throws Exception { openDJController.startCleanServer(); derbyController.startCleanServer(); } /** * Shutdown embedded OpenDJ instance Note: this is not in the abstract * superclass so individual tests may avoid starting OpenDJ. */ @AfterClass public static void stopResources() throws Exception { openDJController.stop(); derbyController.stop(); } /** * Test integrity of the test setup. * * @throws SchemaException * @throws ObjectNotFoundException * @throws CommunicationException */ @Test public void test000Integrity() throws Exception { final String TEST_NAME = "test000Integrity"; TestUtil.displayTestTitle(this, TEST_NAME); assertNotNull(modelWeb); assertNotNull(modelService); assertNotNull(repositoryService); assertTrue(isSystemInitialized()); assertNotNull(taskManager); assertNotNull(prismContext); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull(schemaRegistry); // This is defined in extra schema. So this effectively checks whether the extra schema was loaded PrismPropertyDefinition shipStateDefinition = schemaRegistry.findPropertyDefinitionByElementName(MY_SHIP_STATE); assertNotNull("No my:shipState definition", shipStateDefinition); assertEquals("Wrong maxOccurs in my:shipState definition", 1, shipStateDefinition.getMaxOccurs()); assertNoRepoCache(); Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test000Integrity"); OperationResult result = task.getResult(); // Check if OpenDJ resource was imported correctly PrismObject<ResourceType> openDjResource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); display("Imported OpenDJ resource (repository)", openDjResource); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, openDjResource.getOid()); assertNoRepoCache(); String ldapConnectorOid = openDjResource.asObjectable().getConnectorRef().getOid(); PrismObject<ConnectorType> ldapConnector = repositoryService.getObject(ConnectorType.class, ldapConnectorOid, null, result); display("LDAP Connector: ", ldapConnector); // TODO: test if OpenDJ and Derby are running repositoryService.getObject(GenericObjectType.class, SAMPLE_CONFIGURATION_OBJECT_OID, null, result); } /** * Repeat self-test when we have all the dependencies on the classpath. */ @Test public void test001SelfTests() throws Exception { final String TEST_NAME = "test001SelfTests"; displayTestTitle(TEST_NAME); // GIVEN Task task = taskManager.createTaskInstance(TestSanity.class.getName()+"."+TEST_NAME); // WHEN OperationResult repositorySelfTestResult = modelDiagnosticService.repositorySelfTest(task); // THEN assertSuccess("Repository self test", repositorySelfTestResult); // WHEN OperationResult provisioningSelfTestResult = modelDiagnosticService.provisioningSelfTest(task); // THEN display("Repository self test result", provisioningSelfTestResult); // There may be warning about illegal key size on some platforms. As far as it is warning and not error we are OK // the system will fall back to a interoperable key size if (provisioningSelfTestResult.getStatus() != OperationResultStatus.SUCCESS && provisioningSelfTestResult.getStatus() != OperationResultStatus.WARNING) { AssertJUnit.fail("Provisioning self-test failed: "+provisioningSelfTestResult); } } /** * Test the testResource method. Expect a complete success for now. */ @Test public void test001TestConnectionOpenDJ() throws Exception { final String TEST_NAME = "test001TestConnectionOpenDJ"; displayTestTitle(TEST_NAME); // GIVEN try{ assertNoRepoCache(); // WHEN OperationResultType result = modelWeb.testResource(RESOURCE_OPENDJ_OID); // THEN assertNoRepoCache(); displayJaxb("testResource result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("testResource has failed", result); OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test001TestConnectionOpenDJ"); PrismObject<ResourceType> resourceOpenDjRepo = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, opResult); resourceTypeOpenDjrepo = resourceOpenDjRepo.asObjectable(); assertNoRepoCache(); assertEquals(RESOURCE_OPENDJ_OID, resourceTypeOpenDjrepo.getOid()); display("Initialized OpenDJ resource (respository)", resourceTypeOpenDjrepo); assertNotNull("Resource schema was not generated", resourceTypeOpenDjrepo.getSchema()); Element resourceOpenDjXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeOpenDjrepo); assertNotNull("Resource schema was not generated", resourceOpenDjXsdSchemaElement); PrismObject<ResourceType> openDjResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult); display("Initialized OpenDJ resource resource (provisioning)", openDjResourceProvisioninig); PrismObject<ResourceType> openDjResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult); display("Initialized OpenDJ resource OpenDJ resource (model)", openDjResourceModel); checkOpenDjResource(resourceTypeOpenDjrepo, "repository"); System.out.println("------------------------------------------------------------------"); display("OpenDJ resource schema (repo XML)", DOMUtil.serializeDOMToString(ResourceTypeUtil.getResourceXsdSchema(resourceOpenDjRepo))); System.out.println("------------------------------------------------------------------"); checkOpenDjResource(openDjResourceProvisioninig.asObjectable(), "provisioning"); checkOpenDjResource(openDjResourceModel.asObjectable(), "model"); // TODO: model web } catch (Exception ex){ LOGGER.info("exception: " + ex); throw ex; } } private void checkRepoOpenDjResource() throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoOpenDjResource"); PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); checkOpenDjResource(resource.asObjectable(), "repository"); } /** * Checks if the resource is internally consistent, if it has everything it should have. * * @throws SchemaException */ private void checkOpenDjResource(ResourceType resource, String source) throws SchemaException { assertNotNull("Resource from " + source + " is null", resource); ObjectReferenceType connectorRefType = resource.getConnectorRef(); assertNotNull("Resource from " + source + " has null connectorRef", connectorRefType); assertFalse("Resource from " + source + " has no OID in connectorRef", StringUtils.isBlank(connectorRefType.getOid())); assertNotNull("Resource from " + source + " has null description in connectorRef", connectorRefType.getDescription()); assertNotNull("Resource from " + source + " has null filter in connectorRef", connectorRefType.getFilter()); assertNotNull("Resource from " + source + " has null filter element in connectorRef", connectorRefType.getFilter().getFilterClauseXNode()); assertNotNull("Resource from " + source + " has null configuration", resource.getConnectorConfiguration()); assertNotNull("Resource from " + source + " has null schema", resource.getSchema()); checkOpenDjSchema(resource, source); assertNotNull("Resource from " + source + " has null schemahandling", resource.getSchemaHandling()); checkOpenDjSchemaHandling(resource, source); if (!source.equals("repository")) { // This is generated on the fly in provisioning assertNotNull("Resource from " + source + " has null nativeCapabilities", resource.getCapabilities().getNative()); assertFalse("Resource from " + source + " has empty nativeCapabilities", resource.getCapabilities().getNative().getAny().isEmpty()); } assertNotNull("Resource from " + source + " has null configured capabilities", resource.getCapabilities().getConfigured()); assertFalse("Resource from " + source + " has empty capabilities", resource.getCapabilities().getConfigured().getAny().isEmpty()); assertNotNull("Resource from " + source + " has null synchronization", resource.getSynchronization()); checkOpenDjConfiguration(resource.asPrismObject(), source); } private void checkOpenDjSchema(ResourceType resource, String source) throws SchemaException { ResourceSchema schema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); ObjectClassComplexTypeDefinition accountDefinition = schema.findObjectClassDefinition(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS); assertNotNull("Schema does not define any account (resource from " + source + ")", accountDefinition); Collection<? extends ResourceAttributeDefinition> identifiers = accountDefinition.getPrimaryIdentifiers(); assertFalse("No account identifiers (resource from " + source + ")", identifiers == null || identifiers.isEmpty()); // TODO: check for naming attributes and display names, etc ActivationCapabilityType capActivation = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class); if (capActivation != null && capActivation.getStatus() != null && capActivation.getStatus().getAttribute() != null) { // There is simulated activation capability, check if the attribute is in schema. QName enableAttrName = capActivation.getStatus().getAttribute(); ResourceAttributeDefinition enableAttrDef = accountDefinition.findAttributeDefinition(enableAttrName); display("Simulated activation attribute definition", enableAttrDef); assertNotNull("No definition for enable attribute " + enableAttrName + " in account (resource from " + source + ")", enableAttrDef); assertTrue("Enable attribute " + enableAttrName + " is not ignored (resource from " + source + ")", enableAttrDef.isIgnored()); } } private void checkOpenDjSchemaHandling(ResourceType resource, String source) { SchemaHandlingType schemaHandling = resource.getSchemaHandling(); for (ResourceObjectTypeDefinitionType resObjectTypeDef: schemaHandling.getObjectType()) { if (resObjectTypeDef.getKind() == ShadowKindType.ACCOUNT) { String name = resObjectTypeDef.getIntent(); assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig account definition without intent", name); assertNotNull("Account type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass()); } if (resObjectTypeDef.getKind() == ShadowKindType.ENTITLEMENT) { String name = resObjectTypeDef.getIntent(); assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig entitlement definition without intent", name); assertNotNull("Entitlement type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass()); } } } private void checkOpenDjConfiguration(PrismObject<ResourceType> resource, String source) { checkOpenResourceConfiguration(resource, CONNECTOR_LDAP_NAMESPACE, "bindPassword", 8, source); } private void checkOpenResourceConfiguration(PrismObject<ResourceType> resource, String connectorNamespace, String credentialsPropertyName, int numConfigProps, String source) { PrismContainer<Containerable> configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); assertNotNull("No configuration container in "+resource+" from "+source, configurationContainer); PrismContainer<Containerable> configPropsContainer = configurationContainer.findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES); assertNotNull("No configuration properties container in "+resource+" from "+source, configPropsContainer); Collection<? extends Item<?,?>> configProps = configPropsContainer.getValue().getItems(); assertEquals("Wrong number of config properties in "+resource+" from "+source, numConfigProps, configProps.size()); PrismProperty<Object> credentialsProp = configPropsContainer.findProperty(new ItemName(connectorNamespace,credentialsPropertyName)); if (credentialsProp == null) { // The is the heisenbug we are looking for. Just dump the entire damn thing. display("Configuration with the heisenbug", configurationContainer.debugDump()); } assertNotNull("No "+credentialsPropertyName+" property in "+resource+" from "+source, credentialsProp); assertEquals("Wrong number of "+credentialsPropertyName+" property value in "+resource+" from "+source, 1, credentialsProp.getValues().size()); PrismPropertyValue<Object> credentialsPropertyValue = credentialsProp.getValues().iterator().next(); assertNotNull("No "+credentialsPropertyName+" property value in "+resource+" from "+source, credentialsPropertyValue); if (credentialsPropertyValue.isRaw()) { Object rawElement = credentialsPropertyValue.getRawElement(); assertTrue("Wrong element class "+rawElement.getClass()+" in "+resource+" from "+source, rawElement instanceof MapXNode); // Element rawDomElement = (Element)rawElement; MapXNode xmap = (MapXNode) rawElement; try{ ProtectedStringType protectedType = new ProtectedStringType(); prismContext.hacks().parseProtectedType(protectedType, xmap, prismContext, prismContext.getDefaultParsingContext()); // display("LDAP credentials raw element", DOMUtil.serializeDOMToString(rawDomElement)); // assertEquals("Wrong credentials element namespace in "+resource+" from "+source, connectorNamespace, rawDomElement.getNamespaceURI()); // assertEquals("Wrong credentials element local name in "+resource+" from "+source, credentialsPropertyName, rawDomElement.getLocalName()); // Element encryptedDataElement = DOMUtil.getChildElement(rawDomElement, new QName(DOMUtil.NS_XML_ENC, "EncryptedData")); EncryptedDataType encryptedDataType = protectedType.getEncryptedDataType(); assertNotNull("No EncryptedData element", encryptedDataType); } catch (SchemaException ex){ throw new IllegalArgumentException(ex); } // assertEquals("Wrong EncryptedData element namespace in "+resource+" from "+source, DOMUtil.NS_XML_ENC, encryptedDataType.getNamespaceURI()); // assertEquals("Wrong EncryptedData element local name in "+resource+" from "+source, "EncryptedData", encryptedDataType.getLocalName()); } else { Object credentials = credentialsPropertyValue.getValue(); assertTrue("Wrong type of credentials configuration property in "+resource+" from "+source+": "+credentials.getClass(), credentials instanceof ProtectedStringType); ProtectedStringType credentialsPs = (ProtectedStringType)credentials; EncryptedDataType encryptedData = credentialsPs.getEncryptedDataType(); assertNotNull("No EncryptedData element", encryptedData); } } @Test public void test002AddDerbyResource() throws Exception { final String TEST_NAME = "test002AddDerbyResource"; displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); checkRepoOpenDjResource(); assertNoRepoCache(); PrismObject<ResourceType> resource = PrismTestUtil.parseObject(new File(RESOURCE_DERBY_FILENAME)); assertParentConsistency(resource); fillInConnectorRef(resource, IntegrationTestTools.DBTABLE_CONNECTOR_TYPE, result); OperationResultType resultType = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(resultType); Holder<String> oidHolder = new Holder<>(); display("Adding Derby Resource", resource); // WHEN addObjectViaModelWS(resource.asObjectable(), null, oidHolder, resultHolder); // THEN // Check if Derby resource was imported correctly PrismObject<ResourceType> derbyResource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); AssertJUnit.assertEquals(RESOURCE_DERBY_OID, derbyResource.getOid()); assertNoRepoCache(); String dbConnectorOid = derbyResource.asObjectable().getConnectorRef().getOid(); PrismObject<ConnectorType> dbConnector = repositoryService.getObject(ConnectorType.class, dbConnectorOid, null, result); display("DB Connector: ", dbConnector); // Check if password was encrypted during import // via JAXB Object configurationPropertiesElement = JAXBUtil.findElement(derbyResource.asObjectable().getConnectorConfiguration().getAny(), new QName(dbConnector.asObjectable().getNamespace(), "configurationProperties")); Object passwordElement = JAXBUtil.findElement(JAXBUtil.listChildElements(configurationPropertiesElement), new QName(dbConnector.asObjectable().getNamespace(), "password")); System.out.println("Password element: " + passwordElement); // via prisms PrismContainerValue configurationProperties = derbyResource.findContainer( ItemPath.create( ResourceType.F_CONNECTOR_CONFIGURATION, new QName("configurationProperties"))) .getValue(); PrismProperty password = configurationProperties.findProperty(new ItemName(dbConnector.asObjectable().getNamespace(), "password")); System.out.println("Password property: " + password); } private void addObjectViaModelWS(ObjectType objectType, ModelExecuteOptionsType options, Holder<String> oidHolder, Holder<OperationResultType> resultHolder) throws FaultMessage { ObjectDeltaListType deltaList = new ObjectDeltaListType(); ObjectDeltaType objectDelta = new ObjectDeltaType(); objectDelta.setObjectToAdd(objectType); QName type = objectType.asPrismObject().getDefinition().getTypeName(); objectDelta.setObjectType(type); objectDelta.setChangeType(ChangeTypeType.ADD); deltaList.getDelta().add(objectDelta); ObjectDeltaOperationListType objectDeltaOperationListType = modelWeb.executeChanges(deltaList, options); ObjectDeltaOperationType objectDeltaOperationType = getOdoFromDeltaOperationList(objectDeltaOperationListType, objectDelta); resultHolder.value = objectDeltaOperationType.getExecutionResult(); oidHolder.value = ((ObjectType) objectDeltaOperationType.getObjectDelta().getObjectToAdd()).getOid(); } // ugly hack... private static ObjectDeltaOperationType getOdoFromDeltaOperationList(ObjectDeltaOperationListType operationListType, ObjectDeltaType originalDelta) { Validate.notNull(operationListType); Validate.notNull(originalDelta); for (ObjectDeltaOperationType operationType : operationListType.getDeltaOperation()) { ObjectDeltaType objectDeltaType = operationType.getObjectDelta(); if (originalDelta.getChangeType() == ChangeTypeType.ADD) { if (objectDeltaType.getChangeType() == originalDelta.getChangeType() && objectDeltaType.getObjectToAdd() != null) { ObjectType objectAdded = (ObjectType) objectDeltaType.getObjectToAdd(); if (objectAdded.getClass().equals(originalDelta.getObjectToAdd().getClass())) { return operationType; } } } else { if (objectDeltaType.getChangeType() == originalDelta.getChangeType() && originalDelta.getOid().equals(objectDeltaType.getOid())) { return operationType; } } } throw new IllegalStateException("No suitable ObjectDeltaOperationType found"); } private void checkRepoDerbyResource() throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoDerbyResource"); PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); checkDerbyResource(resource, "repository"); } private void checkDerbyResource(PrismObject<ResourceType> resource, String source) { checkDerbyConfiguration(resource, source); } private void checkDerbyConfiguration(PrismObject<ResourceType> resource, String source) { checkOpenResourceConfiguration(resource, CONNECTOR_DBTABLE_NAMESPACE, "password", 10, source); } /** * Test the testResource method. Expect a complete success for now. */ @Test public void test003TestConnectionDerby() throws Exception { TestUtil.displayTestTitle("test003TestConnectionDerby"); // GIVEN checkRepoDerbyResource(); assertNoRepoCache(); // WHEN OperationResultType result = modelWeb.testResource(RESOURCE_DERBY_OID); // THEN assertNoRepoCache(); displayJaxb("testResource result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("testResource has failed", result.getPartialResults().get(0)); OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test002TestConnectionDerby"); PrismObject<ResourceType> rObject = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, opResult); resourceDerby = rObject.asObjectable(); checkDerbyResource(rObject, "repository(after test)"); assertNoRepoCache(); assertEquals(RESOURCE_DERBY_OID, resourceDerby.getOid()); display("Initialized Derby resource (respository)", resourceDerby); assertNotNull("Resource schema was not generated", resourceDerby.getSchema()); Element resourceDerbyXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceDerby); assertNotNull("Resource schema was not generated", resourceDerbyXsdSchemaElement); PrismObject<ResourceType> derbyResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, null, opResult); display("Initialized Derby resource (provisioning)", derbyResourceProvisioninig); PrismObject<ResourceType> derbyResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, null, opResult); display("Initialized Derby resource (model)", derbyResourceModel); // TODO: check // checkOpenDjResource(resourceOpenDj,"repository"); // checkOpenDjResource(openDjResourceProvisioninig,"provisioning"); // checkOpenDjResource(openDjResourceModel,"model"); // TODO: model web } @Test public void test004Capabilities() throws ObjectNotFoundException, CommunicationException, SchemaException, FaultMessage { TestUtil.displayTestTitle("test004Capabilities"); // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); // WHEN modelWeb.getObject(ObjectTypes.RESOURCE.getTypeQName(), RESOURCE_OPENDJ_OID, options , objectHolder, resultHolder); ResourceType resource = (ResourceType) objectHolder.value; // THEN display("Resource", resource); assertNoRepoCache(); CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative(); List<Object> capabilities = nativeCapabilities.getAny(); assertFalse("Empty capabilities returned", capabilities.isEmpty()); for (Object capability : nativeCapabilities.getAny()) { System.out.println("Native Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } if (resource.getCapabilities() != null) { for (Object capability : resource.getCapabilities().getConfigured().getAny()) { System.out.println("Configured Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } } List<Object> effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource); for (Object capability : effectiveCapabilities) { System.out.println("Efective Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } CredentialsCapabilityType capCred = CapabilityUtil.getCapability(capabilities, CredentialsCapabilityType.class); assertNotNull("password capability not present", capCred.getPassword()); // Connector cannot do activation, this should be null ActivationCapabilityType capAct = CapabilityUtil.getCapability(capabilities, ActivationCapabilityType.class); assertNull("Found activation capability while not expecting it", capAct); capCred = ResourceTypeUtil.getEffectiveCapability(resource, CredentialsCapabilityType.class); assertNotNull("password capability not found", capCred.getPassword()); // Although connector does not support activation, the resource specifies a way how to simulate it. // Therefore the following should succeed capAct = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class); assertNotNull("activation capability not found", capAct); } @Test public void test005resolveConnectorRef() throws Exception{ TestUtil.displayTestTitle("test005resolveConnectorRef"); PrismObject<ResourceType> resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); ModelExecuteOptionsType options = new ModelExecuteOptionsType(); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>()); OperationResult repoResult = new OperationResult("getObject"); PrismObject<ResourceType> uObject = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); assertNotNull(uObject); ResourceType resourceType = uObject.asObjectable(); assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef()); assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid()); } @Test public void test006reimportResourceDummy() throws Exception{ TestUtil.displayTestTitle("test006reimportResourceDummy"); //get object from repo (with version set and try to add it - it should be re-added, without error) OperationResult repoResult = new OperationResult("getObject"); PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); assertNotNull(resource); ModelExecuteOptionsType options = new ModelExecuteOptionsType(); options.setOverwrite(Boolean.TRUE); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>()); //TODO: add some asserts //parse object from file again and try to add it - this should fail, becasue the same object already exists) resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); try { Holder<OperationResultType> resultHolder = new Holder<>(); options = new ModelExecuteOptionsType(); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), resultHolder); OperationResultType result = resultHolder.value; TestUtil.assertFailure(result); fail("Expected object already exists exception, but haven't got one."); } catch (FaultMessage ex) { LOGGER.info("fault {}", ex.getFaultInfo()); LOGGER.info("fault {}", ex.getCause()); if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType) { // this is OK, we expect this } else{ fail("Expected object already exists exception, but got: " + ex.getFaultInfo()); } } // ResourceType resourceType = uObject.asObjectable(); // assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef()); // assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid()); } /** * Attempt to add new user. It is only added to the repository, so check if * it is in the repository after the operation. */ @Test public void test010AddUser() throws Exception { final String TEST_NAME = "test010AddUser"; displayTestTitle(TEST_NAME); // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); PrismObject<UserType> user = PrismTestUtil.parseObject(USER_JACK_FILE); UserType userType = user.asObjectable(); assertParentConsistency(user); // Encrypt Jack's password protector.encrypt(userType.getCredentials().getPassword().getValue()); assertParentConsistency(user); OperationResultType result = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(result); Holder<String> oidHolder = new Holder<>(); display("Adding user object", userType); // WHEN addObjectViaModelWS(userType, null, oidHolder, resultHolder); // THEN assertNoRepoCache(); displayJaxb("addObject result:", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("addObject has failed", resultHolder.value); // AssertJUnit.assertEquals(USER_JACK_OID, oid); OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("repository.getObject result", repoResult); TestUtil.assertSuccess("getObject has failed", repoResult); AssertJUnit.assertEquals(USER_JACK_OID, repoUser.getOid()); assertEqualsPolyString("fullName", userType.getFullName(), repoUser.getFullName()); // TODO: better checks } /** * Add account to user. This should result in account provisioning. Check if * that happens in repo and in LDAP. */ @Test public void test013AddOpenDjAccountToUser() throws Exception { final String TEST_NAME = "test013AddOpenDjAccountToUser"; displayTestTitle(TEST_NAME); try{ // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); // IMPORTANT! SWITCHING OFF ASSIGNMENT ENFORCEMENT HERE! setAssignmentEnforcement(AssignmentPolicyEnforcementType.NONE); // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.NONE); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME, ObjectDeltaType.class); // WHEN displayWhen(TEST_NAME); OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN displayThen(TEST_NAME); assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals("No accountRefs", 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidOpendj = accountRef.getOid(); assertFalse(accountShadowOidOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); assertNotNull("Shadow stored in repository has no name", repoShadowType.getName()); // Check the "name" property, it should be set to DN, not entryUUID assertEquals("Wrong name property", USER_JACK_LDAP_DN.toLowerCase(), repoShadowType.getName().getOrig().toLowerCase()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // check if account was created in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "jack"); OpenDJController.assertAttribute(entry, "givenName", "Jack"); OpenDJController.assertAttribute(entry, "sn", "Sparrow"); OpenDJController.assertAttribute(entry, "cn", "Jack Sparrow"); OpenDJController.assertAttribute(entry, "displayName", "Jack Sparrow"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Black Pearl"); assertTrue("LDAP account is not enabled", openDJController.isAccountEnabled(entry)); originalJacksLdapPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", originalJacksLdapPassword); System.out.println("password after create: " + originalJacksLdapPassword); // Use getObject to test fetch of complete shadow assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); // WHEN modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj, options, objectHolder, resultHolder); // THEN assertNoRepoCache(); displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("getObject has failed", resultHolder.value); ShadowType modelShadow = (ShadowType) objectHolder.value; display("Shadow (model)", modelShadow); AssertJUnit.assertNotNull(modelShadow); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid()); assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "Black Pearl"); assertNull("carLicense attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "carLicense")); assertNull("postalAddress attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "postalAddress")); assertNotNull("Activation is null (model)", modelShadow.getActivation()); assertEquals("Wrong administrativeStatus in the shadow (model)", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus()); } catch (Exception ex){ LOGGER.info("ERROR: {}", ex); throw ex; } } private OperationResultType modifyObjectViaModelWS(ObjectDeltaType objectChange) throws FaultMessage { ObjectDeltaListType deltaList = new ObjectDeltaListType(); deltaList.getDelta().add(objectChange); ObjectDeltaOperationListType list = modelWeb.executeChanges(deltaList, null); return getOdoFromDeltaOperationList(list, objectChange).getExecutionResult(); } /** * Add Derby account to user. This should result in account provisioning. Check if * that happens in repo and in Derby. */ @Test public void test014AddDerbyAccountToUser() throws IOException, JAXBException, FaultMessage, ObjectNotFoundException, SchemaException, DirectoryException, SQLException { TestUtil.displayTestTitle("test014AddDerbyAccountToUser"); // GIVEN checkRepoDerbyResource(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); // OpenDJ account was added in previous test, hence 2 accounts assertEquals(2, accountRefs.size()); ObjectReferenceType accountRef = null; for (ObjectReferenceType ref : accountRefs) { if (!ref.getOid().equals(accountShadowOidOpendj)) { accountRef = ref; } } accountShadowOidDerby = accountRef.getOid(); assertFalse(accountShadowOidDerby.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidDerby, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("addObject has failed", repoResult); display("Shadow (repository)", repoShadowType); assertNotNull(repoShadowType); assertEquals(RESOURCE_DERBY_OID, repoShadowType.getResourceRef().getOid()); // Check the "name" property, it should be set to DN, not entryUUID assertEquals("Wrong name property", PrismTestUtil.createPolyStringType(USER_JACK_DERBY_LOGIN), repoShadowType.getName()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // check if account was created in DB Table Statement stmt = derbyController.getExecutedStatementWhereLoginName(uid); ResultSet rs = stmt.getResultSet(); System.out.println("RS: " + rs); assertTrue("No records found for login name " + uid, rs.next()); assertEquals(USER_JACK_DERBY_LOGIN, rs.getString(DerbyController.COLUMN_LOGIN)); assertEquals("Cpt. Jack Sparrow", rs.getString(DerbyController.COLUMN_FULL_NAME)); // TODO: check password //assertEquals("3lizab3th",rs.getString(DerbyController.COLUMN_PASSWORD)); System.out.println("Password: " + rs.getString(DerbyController.COLUMN_PASSWORD)); assertFalse("Too many records found for login name " + uid, rs.next()); rs.close(); stmt.close(); // Use getObject to test fetch of complete shadow assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType (); // WHEN modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby, options, objectHolder, resultHolder); // THEN assertNoRepoCache(); displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("getObject has failed", resultHolder.value); ShadowType modelShadow = (ShadowType) objectHolder.value; display("Shadow (model)", modelShadow); AssertJUnit.assertNotNull(modelShadow); AssertJUnit.assertEquals(RESOURCE_DERBY_OID, modelShadow.getResourceRef().getOid()); assertAttribute(modelShadow, SchemaConstants.ICFS_UID, USER_JACK_DERBY_LOGIN); assertAttribute(modelShadow, SchemaConstants.ICFS_NAME, USER_JACK_DERBY_LOGIN); assertAttribute(resourceDerby, modelShadow, "FULL_NAME", "Cpt. Jack Sparrow"); } @Test public void test015AccountOwner() throws FaultMessage, ObjectNotFoundException, SchemaException, JAXBException { TestUtil.displayTestTitle("test015AccountOwner"); // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<UserType> userHolder = new Holder<>(); // WHEN modelWeb.findShadowOwner(accountShadowOidOpendj, userHolder, resultHolder); // THEN display("listAccountShadowOwner result", resultHolder.value); TestUtil.assertSuccess("listAccountShadowOwner has failed (result)", resultHolder.value); UserType user = userHolder.value; assertNotNull("No owner", user); assertEquals(USER_JACK_OID, user.getOid()); System.out.println("Account " + accountShadowOidOpendj + " has owner " + ObjectTypeUtil.toShortString(user)); } @Test public void test016ProvisioningSearchAccountsIterative() throws Exception { TestUtil.displayTestTitle("test016ProvisioningSearchAccountsIterative"); // GIVEN OperationResult result = new OperationResult(TestSanity.class.getName() + ".test016ProvisioningSearchAccountsIterative"); RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceTypeOpenDjrepo, prismContext); final RefinedObjectClassDefinition refinedAccountDefinition = refinedSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); QName objectClass = refinedAccountDefinition.getObjectClassDefinition().getTypeName(); ObjectQuery q = ObjectQueryUtil.createResourceAndObjectClassQuery(resourceTypeOpenDjrepo.getOid(), objectClass, prismContext); final Collection<ObjectType> objects = new HashSet<>(); final MatchingRule caseIgnoreMatchingRule = matchingRuleRegistry.getMatchingRule(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME, DOMUtil.XSD_STRING); ResultHandler handler = new ResultHandler<ObjectType>() { @Override public boolean handle(PrismObject<ObjectType> prismObject, OperationResult parentResult) { ObjectType objectType = prismObject.asObjectable(); objects.add(objectType); display("Found object", objectType); assertTrue(objectType instanceof ShadowType); ShadowType shadow = (ShadowType) objectType; assertNotNull(shadow.getOid()); assertNotNull(shadow.getName()); assertEquals(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS, shadow.getObjectClass()); assertEquals(RESOURCE_OPENDJ_OID, shadow.getResourceRef().getOid()); String icfUid = getAttributeValue(shadow, getOpenDjPrimaryIdentifierQName()); assertNotNull("No ICF UID", icfUid); String icfName = getNormalizedAttributeValue(shadow, refinedAccountDefinition, getOpenDjSecondaryIdentifierQName()); assertNotNull("No ICF NAME", icfName); try { PrismAsserts.assertEquals("Wrong shadow name", caseIgnoreMatchingRule, shadow.getName().getOrig(), icfName); } catch (SchemaException e) { throw new IllegalArgumentException(e.getMessage(),e); } assertNotNull("Missing LDAP uid", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "uid"))); assertNotNull("Missing LDAP cn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "cn"))); assertNotNull("Missing LDAP sn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "sn"))); assertNotNull("Missing activation", shadow.getActivation()); assertNotNull("Missing activation status", shadow.getActivation().getAdministrativeStatus()); return true; } }; // WHEN provisioningService.searchObjectsIterative(ShadowType.class, q, null, handler, null, result); // THEN display("Count", objects.size()); } /** * We are going to modify the user. As the user has an account, the user * changes should be also applied to the account (by schemaHandling). */ @Test public void test020ModifyUser() throws Exception { final String TEST_NAME = "test020ModifyUser"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); PrismAsserts.assertEqualsPolyString("wrong value for locality", "somewhere", repoUserType.getLocality()); assertEquals("wrong value for employeeNumber", "1", repoUserType.getEmployeeNumber()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { assertTrue("No OID in "+accountRef+" in "+repoUserType, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); } // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated assertOpenDJAccountJack(uid, "jack"); } private Entry assertOpenDJAccountJack(String entryUuid, String uid) throws DirectoryException { Entry entry = openDJController.searchAndAssertByEntryUuid(entryUuid); return assertOpenDJAccountJack(entry, uid); } private Entry assertOpenDJAccountJack(Entry entry, String uid) throws DirectoryException { return assertOpenDJAccountJack(entry, uid, "Jack"); } private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) throws DirectoryException { display(entry); OpenDJController.assertDn(entry, "uid="+uid+",ou=people,dc=example,dc=com"); OpenDJController.assertAttribute(entry, "uid", uid); if (givenName == null) { OpenDJController.assertAttribute(entry, "givenName"); } else { OpenDJController.assertAttribute(entry, "givenName", givenName); } OpenDJController.assertAttribute(entry, "sn", "Sparrow"); // These two should be assigned from the User modification by // schemaHandling OpenDJController.assertAttribute(entry, "cn", "Cpt. Jack Sparrow"); OpenDJController.assertAttribute(entry, "displayName", "Cpt. Jack Sparrow"); // This will get translated from "somewhere" to this (outbound // expression in schemeHandling) -> this is not more supported...we // don't support complex run-time properties. the value will be // evaluated from outbound expression OpenDJController.assertAttribute(entry, "l", "somewhere"); OpenDJController.assertAttribute(entry, "postalAddress", "Number 1"); return entry; } /** * We are going to change user's password. As the user has an account, the password change * should be also applied to the account (by schemaHandling). */ @Test public void test022ChangeUserPassword() throws Exception { final String TEST_NAME = "test022ChangeUserPassword"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_PASSWORD_FILENAME, ObjectDeltaType.class); System.out.println("In modification: " + objectChange.getItemDelta().get(0).getValue().get(0)); assertNoRepoCache(); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertUserPasswordChange("butUnd3dM4yT4lkAL0t", result); } /** * Similar to previous test just the request is constructed a bit differently. */ @Test public void test023ChangeUserPasswordJAXB() throws Exception { final String TEST_NAME = "test023ChangeUserPasswordJAXB"; displayTestTitle(TEST_NAME); // GIVEN final String NEW_PASSWORD = "abandonSHIP"; Document doc = ModelClientUtil.getDocumnent(); ObjectDeltaType userDelta = new ObjectDeltaType(); userDelta.setOid(USER_JACK_OID); userDelta.setChangeType(ChangeTypeType.MODIFY); userDelta.setObjectType(UserType.COMPLEX_TYPE); ItemDeltaType passwordDelta = new ItemDeltaType(); passwordDelta.setModificationType(ModificationTypeType.REPLACE); passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value", prismContext)); ProtectedStringType pass = new ProtectedStringType(); pass.setClearValue(NEW_PASSWORD); XNode passValue = prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(pass).getSubnode(); System.out.println("PASSWORD VALUE: " + passValue.debugDump()); RawType passwordValue = new RawType(passValue, prismContext); passwordDelta.getValue().add(passwordValue); userDelta.getItemDelta().add(passwordDelta); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(userDelta); // THEN assertUserPasswordChange(NEW_PASSWORD, result); } private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws JAXBException, ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException { assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); // Check if nothing else was modified PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); PrismAsserts.assertEqualsPolyString("wrong repo locality", "somewhere", repoUserType.getLocality()); // Check if appropriate accountRef is still there assertLinks(repoUser, 2); assertLinked(repoUser, accountShadowOidOpendj); assertLinked(repoUser, accountShadowOidDerby); assertPassword(repoUser, expectedUserPassword); // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); display("repository shadow", repoShadow); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertNotNull(repoShadowType); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated Entry entry = assertOpenDJAccountJack(uid, "jack"); String ldapPasswordAfter = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull(ldapPasswordAfter); display("LDAP password after change", ldapPasswordAfter); assertFalse("No change in password (original)", ldapPasswordAfter.equals(originalJacksLdapPassword)); if (lastJacksLdapPassword != null) { assertFalse("No change in password (last)", ldapPasswordAfter.equals(lastJacksLdapPassword)); } lastJacksLdapPassword = ldapPasswordAfter; } @Test public void test027ModifyAccountDj() throws Exception { final String TEST_NAME = "test027ModifyAccountDj"; testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE, "quarterdeck"); } @Test public void test028ModifyAccountDjExplicitType() throws Exception { final String TEST_NAME = "test028ModifyAccountDjExplicitType"; testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE, "upperdeck"); } public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, String expectedVal) throws Exception { displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile(reqFile, ObjectDeltaType.class); objectChange.setOid(accountShadowOidOpendj); // WHEN OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); OperationResult repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated Entry jackLdapEntry = assertOpenDJAccountJack(uid, "jack"); OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", expectedVal); } @Test public void test029ModifyAccountDjBadPath() throws Exception { final String TEST_NAME = "test029ModifyAccountDjBadPath"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidOpendj); OperationResultType result; try { // WHEN result = modifyObjectViaModelWS(objectChange); AssertJUnit.fail("Unexpected success"); } catch (FaultMessage f) { // this is expected FaultType faultInfo = f.getFaultInfo(); result = faultInfo.getOperationResult(); } // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertFailure(result); OperationResult repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated Entry jackLdapEntry = assertOpenDJAccountJack(uid, "jack"); OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", "upperdeck"); } /** * Try to disable user. As the user has an account, the account should be disabled as well. */ @Test public void test030DisableUser() throws Exception { final String TEST_NAME = "test030DisableUser"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME, ObjectDeltaType.class); Entry entry = openDJController.searchByUid("jack"); assertOpenDJAccountJack(entry, "jack"); String pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled"); display("ds-pwp-account-disabled before change", pwpAccountDisabled); assertTrue("LDAP account is not enabled (precondition)", openDJController.isAccountEnabled(entry)); assertNoRepoCache(); // WHEN displayWhen(TEST_NAME); OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN displayThen(TEST_NAME); assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); display("repository user", repoUser); UserType repoUserType = repoUser.asObjectable(); // Check if nothing else was modified assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); assertEqualsPolyString("wrong repo locality", "somewhere", repoUserType.getLocality()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { assertTrue("No OID in "+accountRef+" in "+repoUserType, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); } // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); display("repo shadow", repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); AssertJUnit.assertNotNull(repoShadowType); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated entry = openDJController.searchAndAssertByEntryUuid(uid); assertOpenDJAccountJack(entry, "jack"); pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled"); display("ds-pwp-account-disabled after change", pwpAccountDisabled); assertFalse("LDAP account was not disabled", openDJController.isAccountEnabled(entry)); // Use getObject to test fetch of complete shadow Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); assertNoRepoCache(); // WHEN displayWhen(TEST_NAME); modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj, options, objectHolder, resultHolder); // THEN displayThen(TEST_NAME); assertNoRepoCache(); displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("getObject has failed", resultHolder.value); ShadowType modelShadow = (ShadowType) objectHolder.value; display("Shadow (model)", modelShadow); AssertJUnit.assertNotNull(modelShadow); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid()); assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Cpt. Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Cpt. Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "somewhere"); assertNotNull("The account activation is null in the shadow", modelShadow.getActivation()); assertNotNull("The account activation status was not present in shadow", modelShadow.getActivation().getAdministrativeStatus()); assertEquals("The account was not disabled in the shadow", ActivationStatusType.DISABLED, modelShadow.getActivation().getAdministrativeStatus()); } /** * Try to enable user after it has been disabled. As the user has an account, the account should be enabled as well. */ @Test public void test031EnableUser() throws Exception { final String TEST_NAME = "test031EnableUser"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME, ObjectDeltaType.class); assertNoRepoCache(); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); display("repo user", repoUser); // Check if nothing else was modified PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUser.getFullName()); PrismAsserts.assertEqualsPolyString("wrong repo locality", "somewhere", repoUser.getLocality()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { assertTrue("No OID in "+accountRef+" in "+repoUser, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); } // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repo shadow", repoShadowType); AssertJUnit.assertNotNull(repoShadowType); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Use getObject to test fetch of complete shadow Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); assertNoRepoCache(); // WHEN modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj, options, objectHolder, resultHolder); // THEN assertNoRepoCache(); displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("getObject has failed", resultHolder.value); ShadowType modelShadow = (ShadowType) objectHolder.value; display("Shadow (model)", modelShadow); AssertJUnit.assertNotNull(modelShadow); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid()); assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Cpt. Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Cpt. Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "somewhere"); assertNotNull("The account activation is null in the shadow", modelShadow.getActivation()); assertNotNull("The account activation status was not present in shadow", modelShadow.getActivation().getAdministrativeStatus()); assertEquals("The account was not enabled in the shadow", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus()); // Check if LDAP account was updated Entry entry = openDJController.searchAndAssertByEntryUuid(uid); assertOpenDJAccountJack(entry, "jack"); // The value of ds-pwp-account-disabled should have been removed String pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled"); System.out.println("ds-pwp-account-disabled after change: " + pwpAccountDisabled); assertTrue("LDAP account was not enabled", openDJController.isAccountEnabled(entry)); } /** * Unlink account by removing the accountRef from the user. * The account will not be deleted, just the association to user will be broken. */ @Test public void test040UnlinkDerbyAccountFromUser() throws FileNotFoundException, JAXBException, FaultMessage, ObjectNotFoundException, SchemaException, DirectoryException, SQLException { TestUtil.displayTestTitle("test040UnlinkDerbyAccountFromUser"); // GIVEN ObjectDeltaType objectChange = new ObjectDeltaType(); objectChange.setOid(USER_JACK_OID); ItemDeltaType modificationDeleteAccountRef = new ItemDeltaType(); modificationDeleteAccountRef.setModificationType(ModificationTypeType.DELETE); ObjectReferenceType accountRefToDelete = new ObjectReferenceType(); accountRefToDelete.setOid(accountShadowOidDerby); RawType modificationValue = new RawType(prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(accountRefToDelete).getSubnode(), prismContext); modificationDeleteAccountRef.getValue().add(modificationValue); modificationDeleteAccountRef.setPath(new ItemPathType(UserType.F_LINK_REF)); objectChange.getItemDelta().add(modificationDeleteAccountRef); objectChange.setChangeType(ChangeTypeType.MODIFY); objectChange.setObjectType(UserType.COMPLEX_TYPE); displayJaxb("modifyObject input", objectChange, new QName(SchemaConstants.NS_C, "change")); assertNoRepoCache(); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); // only OpenDJ account should be left now assertEquals(1, accountRefs.size()); ObjectReferenceType ref = accountRefs.get(0); assertEquals("Wrong OID in accountRef in "+repoUser, accountShadowOidOpendj, ref.getOid()); } /** * Delete the shadow which will cause deletion of associated account. * The account was unlinked in the previous test, therefore no operation with user is needed. */ @Test public void test041DeleteDerbyAccount() throws FileNotFoundException, JAXBException, FaultMessage, ObjectNotFoundException, SchemaException, DirectoryException, SQLException { TestUtil.displayTestTitle("test041DeleteDerbyAccount"); // GIVEN assertNoRepoCache(); // WHEN OperationResultType result = deleteObjectViaModelWS(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby); // THEN assertNoRepoCache(); displayJaxb("deleteObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("deleteObject has failed", result); // Check if shadow was deleted OperationResult repoResult = new OperationResult("getObject"); try { repositoryService.getObject(ShadowType.class, accountShadowOidDerby, null, repoResult); AssertJUnit.fail("Shadow was not deleted"); } catch (ObjectNotFoundException ex) { display("Caught expected exception from getObject(shadow): " + ex); } // check if account was deleted in DB Table Statement stmt = derbyController.getExecutedStatementWhereLoginName(USER_JACK_DERBY_LOGIN); ResultSet rs = stmt.getResultSet(); System.out.println("RS: " + rs); assertFalse("Account was not deleted in database", rs.next()); } private OperationResultType deleteObjectViaModelWS(QName typeQName, String oid) throws FaultMessage { ObjectDeltaListType deltaList = new ObjectDeltaListType(); ObjectDeltaType objectDelta = new ObjectDeltaType(); objectDelta.setOid(oid); objectDelta.setObjectType(typeQName); objectDelta.setChangeType(ChangeTypeType.DELETE); deltaList.getDelta().add(objectDelta); ObjectDeltaOperationListType list = modelWeb.executeChanges(deltaList, null); return getOdoFromDeltaOperationList(list, objectDelta).getExecutionResult(); } @Test public void test047RenameUser() throws Exception { final String TEST_NAME = "test047RenameUser"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_NAME_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for User name", "jsparrow", repoUserType.getName()); PrismAsserts.assertEqualsPolyString("wrong value for User fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); PrismAsserts.assertEqualsPolyString("wrong value for User locality", "somewhere", repoUserType.getLocality()); assertEquals("wrong value for employeeNumber", "1", repoUserType.getEmployeeNumber()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.iterator().next(); assertEquals("Wrong OID in "+accountRef+" in "+repoUserType, accountShadowOidOpendj, accountRef.getOid()); // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated assertOpenDJAccountJack(uid, "jsparrow"); } /** * We are going to modify the user. As the user has an account, the user * changes should be also applied to the account (by schemaHandling). * * @throws DirectoryException */ @Test public void test048ModifyUserRemoveGivenName() throws Exception { final String TEST_NAME = "test048ModifyUserRemoveGivenName"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_GIVENNAME_FILENAME, ObjectDeltaType.class); displayJaxb("objectChange:", objectChange, SchemaConstants.T_OBJECT_DELTA); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); assertNull("Value for givenName still present", repoUserType.getGivenName()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.iterator().next(); accountRef.getOid().equals(accountShadowOidOpendj); // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated Entry entry = openDJController.searchAndAssertByEntryUuid(uid); assertOpenDJAccountJack(entry, "jsparrow", null); } /** * The user should have an account now. Let's try to delete the user. The * account should be gone as well. * * @throws JAXBException */ @Test public void test049DeleteUser() throws SchemaException, FaultMessage, DirectoryException, JAXBException { TestUtil.displayTestTitle("test049DeleteUser"); // GIVEN assertNoRepoCache(); // WHEN OperationResultType result = deleteObjectViaModelWS(ObjectTypes.USER.getTypeQName(), USER_JACK_OID); // THEN assertNoRepoCache(); displayJaxb("deleteObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("deleteObject has failed", result); // User should be gone from the repository OperationResult repoResult = new OperationResult("getObject"); try { repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); AssertJUnit.fail("User still exists in repo after delete"); } catch (ObjectNotFoundException e) { // This is expected } // Account shadow should be gone from the repository repoResult = new OperationResult("getObject"); try { repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); AssertJUnit.fail("Shadow still exists in repo after delete"); } catch (ObjectNotFoundException e) { // This is expected, but check also the result AssertJUnit.assertFalse("getObject failed as expected, but the result indicates success", repoResult.isSuccess()); } // Account should be deleted from LDAP InternalSearchOperation op = openDJController.getInternalConnection().processSearch( "dc=example,dc=com", SearchScope.WHOLE_SUBTREE, DereferencePolicy.NEVER_DEREF_ALIASES, 100, 100, false, "(uid=" + USER_JACK_LDAP_UID + ")", null); AssertJUnit.assertEquals(0, op.getEntriesSent()); } @Test public void test100AssignRolePirate() throws Exception { final String TEST_NAME = "test100AssignRolePirate"; displayTestTitle(TEST_NAME); // GIVEN // IMPORTANT! Assignment enforcement is FULL now setAssignmentEnforcement(AssignmentPolicyEnforcementType.FULL); // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.FULL); PrismObject<UserType> user = PrismTestUtil.parseObject(USER_GUYBRUSH_FILE); UserType userType = user.asObjectable(); // Encrypt the password protector.encrypt(userType.getCredentials().getPassword().getValue()); OperationResultType result = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(result); Holder<String> oidHolder = new Holder<>(); assertNoRepoCache(); addObjectViaModelWS(userType, null, oidHolder, resultHolder); assertNoRepoCache(); TestUtil.assertSuccess("addObject has failed", resultHolder.value); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidGuybrushOpendj = accountRef.getOid(); assertFalse(accountShadowOidGuybrushOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadowType); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow); // check if account was created in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Bloody Pirate"); OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", guybrushPassword); // TODO: Derby } @Test public void test101AccountOwnerAfterRole() throws Exception { final String TEST_NAME = "test101AccountOwnerAfterRole"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<UserType> userHolder = new Holder<>(); // WHEN modelWeb.findShadowOwner(accountShadowOidGuybrushOpendj, userHolder, resultHolder); // THEN TestUtil.assertSuccess("listAccountShadowOwner has failed (result)", resultHolder.value); UserType user = userHolder.value; assertNotNull("No owner", user); assertEquals(USER_GUYBRUSH_OID, user.getOid()); System.out.println("Account " + accountShadowOidGuybrushOpendj + " has owner " + ObjectTypeUtil.toShortString(user)); } @Test public void test102AssignRoleCaptain() throws Exception { final String TEST_NAME = "test102AssignRoleCaptain"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid()); // Check if shadow is still in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadow = aObject.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadow); assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid()); // check if account is still in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignment OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); // TODO: Derby } /** * Assign the same "captain" role again, this time with a slightly different assignment parameters. */ @Test public void test103AssignRoleCaptainAgain() throws Exception { final String TEST_NAME = "test103AssignRoleCaptainAgain"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid()); // Check if shadow is still in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadow = aObject.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadow); assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid()); // check if account is still in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignments (both of them) OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); // TODO: Derby } @Test public void test105ModifyAccount() throws Exception { final String TEST_NAME = "test105ModifyAccount"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_ACCOUNT_MODIFY_ATTRS_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidGuybrushOpendj); // WHEN ObjectTypes.SHADOW.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); Task task = taskManager.createTaskInstance(); OperationResult parentResult = new OperationResult(TEST_NAME + "-get after first modify"); PrismObject<ShadowType> shadow= modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult); assertNotNull("shadow must not be null", shadow); ShadowType shadowType = shadow.asObjectable(); QName employeeTypeQName = new QName(resourceTypeOpenDjrepo.getNamespace(), "employeeType"); ItemPath employeeTypePath = ItemPath.create(ShadowType.F_ATTRIBUTES, employeeTypeQName); PrismProperty item = shadow.findProperty(employeeTypePath); PropertyDelta deleteDelta = prismContext.deltaFactory().property().create(ShadowType.F_ATTRIBUTES, item.getDefinition().getItemName(), item.getDefinition()); // PropertyDelta deleteDelta = PropertyDelta.createDelta(employeeTypePath, shadow.getDefinition()); // PrismPropertyValue valToDelte = new PrismPropertyValue("A"); // valToDelte.setParent(deleteDelta); Collection<PrismPropertyValue> values= item.getValues(); for (PrismPropertyValue val : values){ if ("A".equals(val.getValue())){ deleteDelta.addValueToDelete(val.clone()); } } ObjectDelta delta = prismContext.deltaFactory().object().create(ShadowType.class, ChangeType.MODIFY); delta.addModification(deleteDelta); delta.setOid(accountShadowOidGuybrushOpendj); Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>(); deltas.add(delta); LOGGER.info("-------->>EXECUTE DELETE MODIFICATION<<------------"); modelService.executeChanges(deltas, null, task, parentResult); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // check if LDAP account was modified Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); OpenDJController.assertAttribute(entry, "roomNumber", "captain's cabin"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise", "fighting", "capsize"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignments (both of them) OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); } /** * Judge role excludes pirate role. This assignment should fail. */ @Test public void test104AssignRoleJudge() throws Exception { final String TEST_NAME = "test104AssignRoleJudge"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(result); Holder<String> oidHolder = new Holder<>(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME, ObjectDeltaType.class); try { // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN AssertJUnit.fail("Expected a failure after assigning conflicting roles but nothing happened and life goes on"); } catch (FaultMessage f) { // This is expected // TODO: check if the fault is the right one } assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object remain unmodified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals("Unexpected number or accountRefs", 1, accountRefs.size()); } @Test public void test107UnassignRolePirate() throws Exception { final String TEST_NAME = "test107UnassignRolePirate"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid()); // Check if shadow is still in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadow = aObject.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadow); assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid()); // check if account is still in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "cruise", "fighting", "capsize"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignments (both of them) OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); // TODO: Derby } @Test public void test108UnassignRoleCaptain() throws Exception { final String TEST_NAME = "test108UnassignRoleCaptain"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid()); // Check if shadow is still in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check if account is still in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "cruise", "fighting", "capsize"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignments (both of them) OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Dainty Lady"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); // TODO: Derby } /** * Captain role was assigned twice. It has to also be unassigned twice. */ @Test public void test109UnassignRoleCaptainAgain() throws Exception { final String TEST_NAME = "test109UnassignRoleCaptainAgain"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); //TODO TODO TODO TODO operation result from repostiory.getObject is unknown...find out why.. // assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PropertyReferenceListType resolve = new PropertyReferenceListType(); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUserType); List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(0, accountRefs.size()); // Check if shadow was deleted from the repo repoResult = new OperationResult("getObject"); try { PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); AssertJUnit.fail("Account shadow was not deleted from repo"); } catch (ObjectNotFoundException ex) { // This is expected } // check if account was deleted from LDAP Entry entry = openDJController.searchByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); assertNull("LDAP account was not deleted", entry); // TODO: Derby } // Synchronization tests /** * Test initialization of synchronization. It will create a cycle task and * check if the cycle executes No changes are synchronized yet. */ @Test public void test300LiveSyncInit() throws Exception { final String TEST_NAME = "test300LiveSyncInit"; displayTestTitle(TEST_NAME); // Now it is the right time to add task definition to the repository // We don't want it there any sooner, as it may interfere with the // previous tests checkAllShadows(); // IMPORTANT! Assignment enforcement is POSITIVE now setAssignmentEnforcement(AssignmentPolicyEnforcementType.POSITIVE); // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE); final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); repoAddObjectFromFile(TASK_OPENDJ_SYNC_FILENAME, result); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task waitFor("Waiting for task manager to pick up the task", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); display("Task while waiting for task manager to pick up the task", task); // wait until the task is picked up return task.getLastRunFinishTimestamp() != null; // if (TaskExclusivityStatus.CLAIMED == task.getExclusivityStatus()) { // // wait until the first run is finished // if (task.getLastRunFinishTimestamp() == null) { // return false; // } // return true; // } // return false; } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 20000); // Check task status Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, retrieveTaskResult(), result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); AssertJUnit.assertNotNull(task); display("Task after pickup", task); PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_OPENDJ_SYNC_OID, null, result); display("Task after pickup in the repository", o.asObjectable()); // .. it should be running AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus()); // .. and claimed // AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus()); // .. and last run should not be zero assertNotNull("No lastRunStartTimestamp", task.getLastRunStartTimestamp()); assertFalse("Zero lastRunStartTimestamp", task.getLastRunStartTimestamp().longValue() == 0); assertNotNull("No lastRunFinishedTimestamp", task.getLastRunFinishTimestamp()); assertFalse("Zero lastRunFinishedTimestamp", task.getLastRunFinishTimestamp().longValue() == 0); // Test for extension. This will also roughly test extension processor // and schema processor PrismContainer<?> taskExtension = task.getExtensionOrClone(); AssertJUnit.assertNotNull(taskExtension); display("Task extension", taskExtension); PrismProperty<String> shipStateProp = taskExtension.findProperty(MY_SHIP_STATE); AssertJUnit.assertEquals("Wrong 'shipState' property value", "capsized", shipStateProp.getValue().getValue()); PrismProperty<Integer> deadProp = taskExtension.findProperty(MY_DEAD); PrismPropertyValue<Integer> deadPVal = deadProp.getValues().iterator().next(); AssertJUnit.assertEquals("Wrong 'dead' property class", Integer.class, deadPVal.getValue().getClass()); AssertJUnit.assertEquals("Wrong 'dead' property value", Integer.valueOf(42), deadPVal.getValue()); // The progress should be 0, as there were no changes yet AssertJUnit.assertEquals(0, task.getProgress()); // Test for presence of a result. It should be there and it should // indicate success OperationResult taskResult = task.getResult(); AssertJUnit.assertNotNull(taskResult); assertTrue("Task result is not a success, it is "+taskResult, taskResult.isSuccess()); final Object tokenAfter = findSyncToken(task); display("Sync token after", tokenAfter.toString()); lastSyncToken = (Integer)tokenAfter; checkAllShadows(); // Try without options. The results should NOT be there // MID-4670 task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, null, result); taskResult = task.getResult(); AssertJUnit.assertNull("Unexpected task result", taskResult); } /** * Create LDAP object. That should be picked up by liveSync and a user * should be created in repo. */ @Test public void test301LiveSyncCreate() throws Exception { final String TEST_NAME = "test301LiveSyncCreate"; displayTestTitle(TEST_NAME); // Sync task should be running (tested in previous test), so just create // new LDAP object. final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); final Object tokenBefore = findSyncToken(syncCycle); display("Sync token before", tokenBefore.toString()); // WHEN displayWhen(TEST_NAME); Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_FILENAME); display("Entry from LDIF", entry); // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 2, result); // THEN displayThen(TEST_NAME); // Search for the user that should be created now UserType user = searchUserByName(WILL_NAME); PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); assertNotNull(user.getLinkRef()); assertFalse(user.getLinkRef().isEmpty()); // AssertJUnit.assertEquals(user.getName(), WILL_NAME); // TODO: more checks assertAndStoreSyncTokenIncrement(syncCycle, 2); checkAllShadows(); } @Test public void test302LiveSyncModify() throws Exception { final String TEST_NAME = "test302LiveSyncModify"; displayTestTitle(TEST_NAME); final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); display("Sync token before", tokenBefore); // WHEN display("Modifying LDAP entry"); ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_WILL_MODIFY_FILE); // THEN display("Entry from LDIF", entry); // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result); // Search for the user that should be created now UserType user = searchUserByName (WILL_NAME); // AssertJUnit.assertEquals(WILL_NAME, user.getName()); PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); PrismAsserts.assertEqualsPolyString("wrong givenName", "asdf", user.getGivenName()); assertAndStoreSyncTokenIncrement(syncCycle, 1); checkAllShadows(); } @Test public void test303LiveSyncLink() throws Exception { final String TEST_NAME = "test303LiveSyncLink"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); PrismObject<UserType> user = PrismTestUtil.parseObject(USER_E_LINK_ACTION_FILE); UserType userType = user.asObjectable(); final String userOid = userType.getOid(); // Encrypt e's password protector.encrypt(userType.getCredentials().getPassword().getValue()); // create user in repository OperationResultType resultType = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(resultType); Holder<String> oidHolder = new Holder<>(); display("Adding user object", userType); addObjectViaModelWS(userType, null, oidHolder, resultHolder); //check results assertNoRepoCache(); displayJaxb("addObject result:", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("addObject has failed", resultHolder.value); // AssertJUnit.assertEquals(userOid, oidHolder.value); //WHEN displayWhen(TEST_NAME); //create account for e which should be correlated final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); display("Sync token before", tokenBefore); Entry entry = openDJController.addEntryFromLdifFile(LDIF_E_FILENAME_LINK); display("Entry from LDIF", entry); // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result); // THEN displayThen(TEST_NAME); //check user and account ref userType = searchUserByName("e"); List<ObjectReferenceType> accountRefs = userType.getLinkRef(); assertEquals("Account ref not found, or found too many", 1, accountRefs.size()); //check account defined by account ref String accountOid = accountRefs.get(0).getOid(); ShadowType account = searchAccountByOid(accountOid); assertEqualsPolyString("Name doesn't match", "uid=e,ou=People,dc=example,dc=com", account.getName()); assertAndStoreSyncTokenIncrement(syncCycle, 1); checkAllShadows(); } /** * Create LDAP object. That should be picked up by liveSync and a user * should be created in repo. * Also location (ldap l) should be updated through outbound */ @Test public void test304LiveSyncCreateNoLocation() throws Exception { final String TEST_NAME = "test304LiveSyncCreateNoLocation"; displayTestTitle(TEST_NAME); // Sync task should be running (tested in previous test), so just create // new LDAP object. final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); display("Sync token before", tokenBefore); // WHEN Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_WITHOUT_LOCATION_FILENAME); display("Entry from LDIF", entry); // THEN // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 3, result, 60000); // Search for the user that should be created now final String userName = "wturner1"; UserType user = searchUserByName(userName); List<ObjectReferenceType> accountRefs = user.getLinkRef(); assertEquals("Account ref not found, or found too many", 1, accountRefs.size()); //check account defined by account ref String accountOid = accountRefs.get(0).getOid(); ShadowType account = searchAccountByOid(accountOid); assertEqualsPolyString("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName()); // assertEquals("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName()); Collection<String> localities = getAttributeValues(account, new QName(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS.getNamespaceURI(), "l")); assertNotNull("null value list for attribute 'l'", localities); assertEquals("unexpected number of values of attribute 'l'", 1, localities.size()); assertEquals("Locality doesn't match", "middle of nowhere", localities.iterator().next()); assertAndStoreSyncTokenIncrement(syncCycle, 3); checkAllShadows(); } private void assertAndStoreSyncTokenIncrement(Task syncCycle, int increment) { final Object tokenAfter = findSyncToken(syncCycle); display("Sync token after", tokenAfter.toString()); int tokenAfterInt = (Integer)tokenAfter; int expectedToken = lastSyncToken + increment; lastSyncToken = tokenAfterInt; assertEquals("Unexpected sync toke value", expectedToken, tokenAfterInt); } private int findSyncToken(Task syncCycle) { return (Integer)findSyncTokenObject(syncCycle); } private Object findSyncTokenObject(Task syncCycle) { Object token = null; PrismProperty<?> tokenProperty = syncCycle.getExtensionOrClone().findProperty(SchemaConstants.SYNC_TOKEN); if (tokenProperty != null) { Collection<?> values = tokenProperty.getRealValues(); if (values.size() > 1) { throw new IllegalStateException("Too must values in token "+tokenProperty); } token = values.iterator().next(); } return token; } /** * Not really a test. Just cleans up after live sync. */ @Test public void test399LiveSyncCleanup() throws Exception { final String TEST_NAME = "test399LiveSyncCleanup"; displayTestTitle(TEST_NAME); final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); taskManager.deleteTask(TASK_OPENDJ_SYNC_OID, result); // TODO: check if the task is really stopped } @Test public void test400ImportFromResource() throws Exception { final String TEST_NAME = "test400ImportFromResource"; displayTestTitle(TEST_NAME); // GIVEN checkAllShadows(); assertNoRepoCache(); OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); // Make sure Mr. Gibbs has "l" attribute set to the same value as an outbound expression is setting ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_GIBBS_MODIFY_FILE); display("Entry from LDIF", entry); // Let's add an entry with multiple uids. Entry addEntry = openDJController.addEntryFromLdifFile(LDIF_HERMAN_FILENAME); display("Entry from LDIF", addEntry); // WHEN displayWhen(TEST_NAME); TaskType taskType = modelWeb.importFromResource(RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS); // THEN displayThen(TEST_NAME); assertNoRepoCache(); displayJaxb("importFromResource result", taskType.getResult(), SchemaConstants.C_RESULT); AssertJUnit.assertEquals("importFromResource has failed", OperationResultStatusType.IN_PROGRESS, taskType.getResult().getStatus()); // Convert the returned TaskType to a more usable Task Task task = taskManager.createTaskInstance(taskType.asPrismObject(), result); AssertJUnit.assertNotNull(task); assertNotNull(task.getOid()); AssertJUnit.assertTrue(task.isAsynchronous()); AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus()); // AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus()); display("Import task after launch", task); PrismObject<TaskType> tObject = repositoryService.getObject(TaskType.class, task.getOid(), null, result); TaskType taskAfter = tObject.asObjectable(); display("Import task in repo after launch", taskAfter); result.computeStatus(); TestUtil.assertSuccess("getObject has failed", result); final String taskOid = task.getOid(); waitFor("Waiting for import to complete", new Checker() { @Override public boolean check() throws CommonException { Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); OperationResult opResult = new OperationResult("import check"); assertNoRepoCache(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); try { modelWeb.getObject(ObjectTypes.TASK.getTypeQName(), taskOid, options, objectHolder, resultHolder); } catch (FaultMessage faultMessage) { throw new SystemException(faultMessage); } assertNoRepoCache(); // display("getObject result (wait loop)",resultHolder.value); TestUtil.assertSuccess("getObject has failed", resultHolder.value); Task task = taskManager.createTaskInstance((PrismObject<TaskType>) objectHolder.value.asPrismObject(), opResult); System.out.println(new Date() + ": Import task status: " + task.getExecutionStatus() + ", progress: " + task.getProgress()); if (task.getExecutionStatus() == TaskExecutionStatus.CLOSED) { // Task closed, wait finished return true; } // IntegrationTestTools.display("Task result while waiting: ", task.getResult()); return false; } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 180000); // wait a second until the task will be definitely saved Thread.sleep(1000); //### Check task state after the task is finished ### Holder<ObjectType> objectHolder = new Holder<>(); Holder<OperationResultType> resultHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); assertNoRepoCache(); modelWeb.getObject(ObjectTypes.TASK.getTypeQName(), task.getOid(), options, objectHolder, resultHolder); assertNoRepoCache(); TestUtil.assertSuccess("getObject has failed", resultHolder.value); task = taskManager.createTaskInstance((PrismObject<TaskType>) objectHolder.value.asPrismObject(), result); display("Import task after finish (fetched from model)", task); AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus()); assertNotNull("Null lastRunStartTimestamp in "+task, task.getLastRunStartTimestamp()); assertNotNull("Null lastRunFinishTimestamp in "+task, task.getLastRunFinishTimestamp()); long importDuration = task.getLastRunFinishTimestamp() - task.getLastRunStartTimestamp(); double usersPerSec = (task.getProgress() * 1000) / importDuration; display("Imported " + task.getProgress() + " users in " + importDuration + " milliseconds (" + usersPerSec + " users/sec)"); OperationResultStatusType taskResultStatus = task.getResultStatus(); AssertJUnit.assertNotNull("Task has no result status", taskResultStatus); assertEquals("Import task result is not success", OperationResultStatusType.SUCCESS, taskResultStatus); AssertJUnit.assertTrue("No progress", task.getProgress() > 0); //### Check if the import created users and shadows ### // Listing of shadows is not supported by the provisioning. So we need // to look directly into repository List<PrismObject<ShadowType>> sobjects = repositoryService.searchObjects(ShadowType.class, null, null, result); result.computeStatus(); TestUtil.assertSuccess("listObjects has failed", result); AssertJUnit.assertFalse("No shadows created", sobjects.isEmpty()); for (PrismObject<ShadowType> aObject : sobjects) { ShadowType shadow = aObject.asObjectable(); display("Shadow object after import (repo)", shadow); assertNotEmpty("No OID in shadow", shadow.getOid()); // This would be really strange ;-) assertNotEmpty("No name in shadow", shadow.getName()); AssertJUnit.assertNotNull("No objectclass in shadow", shadow.getObjectClass()); AssertJUnit.assertNotNull("Null attributes in shadow", shadow.getAttributes()); String resourceOid = shadow.getResourceRef().getOid(); if (resourceOid.equals(RESOURCE_OPENDJ_OID)) { assertAttributeNotNull("No identifier in shadow", shadow, getOpenDjPrimaryIdentifierQName()); } else { assertAttributeNotNull("No UID in shadow", shadow, SchemaConstants.ICFS_UID); } } Holder<ObjectListType> listHolder = new Holder<>(); assertNoRepoCache(); modelWeb.searchObjects(ObjectTypes.USER.getTypeQName(), null, null, listHolder, resultHolder); assertNoRepoCache(); ObjectListType uobjects = listHolder.value; TestUtil.assertSuccess("listObjects has failed", resultHolder.value); AssertJUnit.assertFalse("No users created", uobjects.getObject().isEmpty()); // TODO: use another account, not guybrush display("Users after import "+uobjects.getObject().size()); for (ObjectType oo : uobjects.getObject()) { UserType user = (UserType) oo; if (SystemObjectsType.USER_ADMINISTRATOR.value().equals(user.getOid())) { //skip administrator check continue; } display("User after import (repo)", user); assertNotEmpty("No OID in user", user.getOid()); // This would be // really // strange ;-) assertNotEmpty("No name in user", user.getName()); assertNotNull("No fullName in user", user.getFullName()); assertNotEmpty("No fullName in user", user.getFullName().getOrig()); assertNotEmpty("No familyName in user", user.getFamilyName().getOrig()); // givenName is not mandatory in LDAP, therefore givenName may not // be present on user if (user.getName().getOrig().equals(USER_GUYBRUSH_USERNAME)) { // skip the rest of checks for guybrush, he does not have LDAP account now continue; } assertTrue("User "+user.getName()+" is disabled ("+user.getActivation().getAdministrativeStatus()+")", user.getActivation() == null || user.getActivation().getAdministrativeStatus() == ActivationStatusType.ENABLED); List<ObjectReferenceType> accountRefs = user.getLinkRef(); AssertJUnit.assertEquals("Wrong accountRef for user " + user.getName(), 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); boolean found = false; for (PrismObject<ShadowType> aObject : sobjects) { ShadowType acc = aObject.asObjectable(); if (accountRef.getOid().equals(acc.getOid())) { found = true; break; } } if (!found) { AssertJUnit.fail("accountRef does not point to existing account " + accountRef.getOid()); } PrismObject<ShadowType> aObject = modelService.getObject(ShadowType.class, accountRef.getOid(), null, task, result); ShadowType account = aObject.asObjectable(); display("Account after import ", account); String attributeValueL = ShadowUtil.getMultiStringAttributeValueAsSingle(account, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "l")); // assertEquals("Unexcpected value of l", "middle of nowhere", attributeValueL); assertEquals("Unexcpected value of l", getUserLocality(user), attributeValueL); } // This also includes "idm" user imported from LDAP. Later we need to ignore that one. assertEquals("Wrong number of users after import", 10, uobjects.getObject().size()); checkAllShadows(); } private String getUserLocality(UserType user){ return user.getLocality() != null ? user.getLocality().getOrig() :"middle of nowhere"; } @Test public void test420RecomputeUsers() throws Exception { final String TEST_NAME = "test420RecomputeUsers"; displayTestTitle(TEST_NAME); // GIVEN final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); // Assign role to a user, but we do this using a repository instead of model. // The role assignment will not be executed and this created an inconsistent state. ObjectDeltaType changeAddRoleCaptain = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); Collection<? extends ItemDelta> modifications = DeltaConvertor.toModifications(changeAddRoleCaptain.getItemDelta(), getUserDefinition()); repositoryService.modifyObject(UserType.class, changeAddRoleCaptain.getOid(), modifications, result); // TODO: setup more "inconsistent" state // Add reconciliation task. This will trigger reconciliation importObjectFromFile(TASK_USER_RECOMPUTE_FILENAME, result); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task waitFor("Waiting for task to finish", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, result); //display("Task while waiting for task manager to pick up the task", task); // wait until the task is finished if (TaskExecutionStatus.CLOSED == task.getExecutionStatus()) { return true; } return false; } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 40000); // wait a second until the task will be definitely saved Thread.sleep(1000); // Check task status Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, retrieveTaskResult(), result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); AssertJUnit.assertNotNull(task); display("Task after finish", task); AssertJUnit.assertNotNull(task.getTaskIdentifier()); assertFalse(task.getTaskIdentifier().isEmpty()); PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_USER_RECOMPUTE_OID, null, result); display("Task after pickup in the repository", o.asObjectable()); AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus()); // .. and last run should not be zero assertNotNull(task.getLastRunStartTimestamp()); AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0); assertNotNull(task.getLastRunFinishTimestamp()); AssertJUnit.assertFalse(task.getLastRunFinishTimestamp().longValue() == 0); AssertJUnit.assertEquals(10, task.getProgress()); // Test for presence of a result. It should be there and it should // indicate success OperationResult taskResult = task.getResult(); display("Recompute task result", taskResult); AssertJUnit.assertNotNull(taskResult); TestUtil.assertSuccess("Recompute task result", taskResult); // STOP the task. We don't need it any more and we don't want to give it a chance to run more than once taskManager.deleteTask(TASK_USER_RECOMPUTE_OID, result); // CHECK RESULT: account created for user guybrush // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> object = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = object.asObjectable(); repoResult.computeStatus(); displayJaxb("User (repository)", repoUser, new QName("user")); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals("Wrong number of accountRefs after recompute for user "+repoUser.getName(), 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidGuybrushOpendj = accountRef.getOid(); assertFalse(accountShadowOidGuybrushOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow")); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow); // check if account was created in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "cruise"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", guybrushPassword); checkAllShadows(); } @Test public void test440ReconcileResourceOpenDj() throws Exception { final String TEST_NAME = "test440ReconcileResourceOpenDj"; displayTestTitle(TEST_NAME); // GIVEN final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); // Create LDAP account without an owner. The liveSync is off, so it will not be picked up Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ELAINE_FILENAME); display("Entry from LDIF", ldifEntry); // Guybrush's attributes were set up by a role in the previous test. Let's mess the up a bit. Recon should sort it out. List<RawModification> modifications = new ArrayList<>(); // Expect that a correct title will be added to this one RawModification titleMod = RawModification.create(ModificationType.REPLACE, "title", "Scurvy earthworm"); modifications.add(titleMod); // Expect that the correct location will replace this one RawModification lMod = RawModification.create(ModificationType.REPLACE, "l", "Davie Jones' locker"); modifications.add(lMod); // Expect that this will be untouched RawModification poMod = RawModification.create(ModificationType.REPLACE, "postOfficeBox", "X marks the spot"); modifications.add(poMod); ModifyOperation modifyOperation = openDJController.getInternalConnection().processModify(USER_GUYBRUSH_LDAP_DN, modifications); if (ResultCode.SUCCESS != modifyOperation.getResultCode()) { AssertJUnit.fail("LDAP operation failed: " + modifyOperation.getErrorMessage()); } // TODO: setup more "inconsistent" state // Add reconciliation task. This will trigger reconciliation repoAddObjectFromFile(TASK_OPENDJ_RECON_FILENAME, result); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task waitFor("Waiting for task to finish first run", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result); display("Task while waiting for task manager to pick up the task", task); // wait until the task is finished return task.getLastRunFinishTimestamp() != null; } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 180000); // Check task status Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); AssertJUnit.assertNotNull(task); display("Task after pickup", task); PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_OPENDJ_RECON_OID, null, result); display("Task after pickup in the repository", o.asObjectable()); // .. it should be running AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus()); // .. and claimed // AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus()); // .. and last run should not be zero assertNotNull("Null last run start in recon task", task.getLastRunStartTimestamp()); AssertJUnit.assertFalse("Zero last run start in recon task", task.getLastRunStartTimestamp().longValue() == 0); assertNotNull("Null last run finish in recon task", task.getLastRunFinishTimestamp()); AssertJUnit.assertFalse("Zero last run finish in recon task", task.getLastRunFinishTimestamp().longValue() == 0); // The progress should be 0, as there were no changes yet // [pm] commented out, as progress in recon task is now determined not only using # of changes //AssertJUnit.assertEquals(0, task.getProgress()); // Test for presence of a result. It was not fetched - so it should NOT be there OperationResult taskResult = task.getResult(); AssertJUnit.assertNull(taskResult); // However, the task should indicate success AssertJUnit.assertEquals(OperationResultStatusType.SUCCESS, task.getResultStatus()); // STOP the task. We don't need it any more and we don't want to give it a chance to run more than once taskManager.deleteTask(TASK_OPENDJ_RECON_OID, result); // CHECK RESULT: account for user guybrush should be still there and unchanged // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); displayJaxb("User (repository)", repoUser, new QName("user")); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals("Guybrush has wrong number of accounts", 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidGuybrushOpendj = accountRef.getOid(); assertFalse(accountShadowOidGuybrushOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow")); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow); // check if account was created in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object. It is not tolerant, therefore the other value should be gone now OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); // "title" is tolerant, so it will retain the original value as well as the one provided by the role OpenDJController.assertAttribute(entry, "title", "Scurvy earthworm", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "cruise"); // No setting for "postOfficeBox", so the value should be unchanged OpenDJController.assertAttribute(entry, "postOfficeBox", "X marks the spot"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", guybrushPassword); // QueryType query = QueryUtil.createNameQuery(ELAINE_NAME); // ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(UserType.class, prismContext, UserType.F_NAME, ELAINE_NAME)); ObjectQuery query = ObjectQueryUtil.createNameQuery(ELAINE_NAME, prismContext); List<PrismObject<UserType>> users = repositoryService.searchObjects(UserType.class, query, null, repoResult); assertEquals("Wrong number of Elaines", 1, users.size()); repoUser = users.get(0).asObjectable(); repoResult.computeStatus(); displayJaxb("User Elaine (repository)", repoUser, new QName("user")); assertNotNull(repoUser.getOid()); assertEquals(PrismTestUtil.createPolyStringType(ELAINE_NAME), repoUser.getName()); PrismAsserts.assertEqualsPolyString("wrong repo givenName", "Elaine", repoUser.getGivenName()); PrismAsserts.assertEqualsPolyString("wrong repo familyName", "Marley", repoUser.getFamilyName()); PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Elaine Marley", repoUser.getFullName()); accountRefs = repoUser.getLinkRef(); assertEquals("Elaine has wrong number of accounts", 1, accountRefs.size()); accountRef = accountRefs.get(0); String accountShadowOidElaineOpendj = accountRef.getOid(); assertFalse(accountShadowOidElaineOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidElaineOpendj, null, repoResult); repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow")); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); String accountElainehOpendjEntryUuuid = checkRepoShadow(repoShadow); // check if account is still in LDAP entry = openDJController.searchAndAssertByEntryUuid(accountElainehOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", ELAINE_NAME); OpenDJController.assertAttribute(entry, "givenName", "Elaine"); OpenDJController.assertAttribute(entry, "sn", "Marley"); OpenDJController.assertAttribute(entry, "cn", "Elaine Marley"); OpenDJController.assertAttribute(entry, "displayName", "Elaine Marley"); // The "l" attribute is assigned indirectly through schemaHandling and // config object // FIXME //OpenDJController.assertAttribute(entry, "l", "middle of nowhere"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "governor"); OpenDJController.assertAttribute(entry, "title", "Governor"); OpenDJController.assertAttribute(entry, "businessCategory", "state"); String elainePassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Password of Elaine has disappeared", elainePassword); checkAllShadows(); } @Test public void test480ListResources() throws Exception { final String TEST_NAME = "test480ListResources"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(result); Holder<ObjectListType> objectListHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); // WHEN modelWeb.searchObjects(ObjectTypes.RESOURCE.getTypeQName(), null, options, objectListHolder, resultHolder); // THEN display("Resources", objectListHolder.value); assertEquals("Unexpected number of resources", 4, objectListHolder.value.getObject().size()); // TODO for(ObjectType object: objectListHolder.value.getObject()) { // Marshalling may fail even though the Java object is OK so test for it String xml = prismContext.serializeObjectToString(object.asPrismObject(), PrismContext.LANG_XML); } } @Test public void test485ListResourcesWithBrokenResource() throws Exception { TestUtil.displayTestTitle("test485ListResourcesWithBrokenResource"); // GIVEN Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test410ListResourcesWithBrokenResource"); final OperationResult result = task.getResult(); // WHEN List<PrismObject<ResourceType>> resources = modelService.searchObjects(ResourceType.class, null, null, task, result); // THEN assertNotNull("listObjects returned null list", resources); for (PrismObject<ResourceType> object : resources) { ResourceType resource = object.asObjectable(); //display("Resource found",resource); display("Found " + ObjectTypeUtil.toShortString(resource) + ", result " + (resource.getFetchResult() == null ? "null" : resource.getFetchResult().getStatus())); assertNotNull(resource.getOid()); assertNotNull(resource.getName()); if (resource.getOid().equals(RESOURCE_BROKEN_OID)) { assertTrue("No error in fetchResult in " + ObjectTypeUtil.toShortString(resource), resource.getFetchResult() != null && (resource.getFetchResult().getStatus() == OperationResultStatusType.PARTIAL_ERROR || resource.getFetchResult().getStatus() == OperationResultStatusType.FATAL_ERROR)); } else { assertTrue("Unexpected error in fetchResult in " + ObjectTypeUtil.toShortString(resource), resource.getFetchResult() == null || resource.getFetchResult().getStatus() == OperationResultStatusType.SUCCESS); } } } @Test public void test500NotifyChangeCreateAccount() throws Exception{ final String TEST_NAME = "test500NotifyChangeCreateAccount"; displayTestTitle(TEST_NAME); Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ANGELIKA_FILENAME); display("Entry from LDIF", ldifEntry); List<Attribute> attributes = ldifEntry.getAttributes(); List<Attribute> attrs = ldifEntry.getAttribute("entryUUID"); AttributeValue val = null; if (attrs == null){ for (Attribute a : attributes){ if (a.getName().equals("entryUUID")){ val = a.iterator().next(); } } } else{ val = attrs.get(0).iterator().next(); } String entryUuid = val.toString(); ShadowType anglicaAccount = parseObjectType(new File(ACCOUNT_ANGELIKA_FILENAME), ShadowType.class); PrismProperty<String> prop = anglicaAccount.asPrismObject().findContainer(ShadowType.F_ATTRIBUTES).getValue().createProperty( prismContext.definitionFactory().createPropertyDefinition(getOpenDjPrimaryIdentifierQName(), DOMUtil.XSD_STRING)); prop.setRealValue(entryUuid); anglicaAccount.setResourceRef(ObjectTypeUtil.createObjectRef(RESOURCE_OPENDJ_OID, ObjectTypes.RESOURCE)); display("Angelica shadow: ", anglicaAccount.asPrismObject().debugDump()); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.ADD); delta.setObjectToAdd(anglicaAccount); delta.setObjectType(ShadowType.COMPLEX_TYPE); changeDescription.setObjectDelta(delta); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); // WHEN TaskType task = modelWeb.notifyChange(changeDescription); // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); PrismObject<ShadowType> modelShadow = modelService.getObject(ShadowType.class, oid, null, taskManager.createTaskInstance(), result); assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(modelShadow, "uid", "angelika"); assertAttribute(modelShadow, "givenName", "Angelika"); assertAttribute(modelShadow, "sn", "Marley"); assertAttribute(modelShadow, "cn", "Angelika Marley"); } @Test public void test501NotifyChangeModifyAccount() throws Exception{ final String TEST_NAME = "test501NotifyChangeModifyAccount"; displayTestTitle(TEST_NAME); OperationResult parentResult = new OperationResult(TEST_NAME); PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.MODIFY); delta.setObjectType(ShadowType.COMPLEX_TYPE); ItemDeltaType mod1 = new ItemDeltaType(); mod1.setModificationType(ModificationTypeType.REPLACE); ItemPathType path = new ItemPathType(ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(resourceTypeOpenDjrepo.getNamespace(), "givenName"))); mod1.setPath(path); RawType value = new RawType(prismContext.xnodeFactory().primitive("newAngelika"), prismContext); mod1.getValue().add(value); delta.getItemDelta().add(mod1); delta.setOid(oid); LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(mod1)); LOGGER.info("delta: {}", DebugUtil.dump(mod1)); changeDescription.setObjectDelta(delta); changeDescription.setOldShadowOid(oid); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); // WHEN TaskType task = modelWeb.notifyChange(changeDescription); // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); UserType userAfterSync = userAngelikaAfterSync.asObjectable(); PrismAsserts.assertEqualsPolyString("wrong given name in user angelika", PrismTestUtil.createPolyStringType("newAngelika"), userAfterSync.getGivenName()); } @Test public void test502NotifyChangeModifyAccountPassword() throws Exception{ final String TEST_NAME = "test502NotifyChangeModifyAccountPassword"; displayTestTitle(TEST_NAME); PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); String newPassword = "newPassword"; openDJController.modifyReplace("uid="+ANGELIKA_NAME+","+openDJController.getSuffixPeople(), "userPassword", newPassword); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.MODIFY); delta.setObjectType(ShadowType.COMPLEX_TYPE); ItemDeltaType passwordDelta = new ItemDeltaType(); passwordDelta.setModificationType(ModificationTypeType.REPLACE); passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value", prismContext)); RawType passwordValue = new RawType(prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(ModelClientUtil.createProtectedString(newPassword)).getSubnode(), prismContext); passwordDelta.getValue().add(passwordValue); delta.getItemDelta().add(passwordDelta); delta.setOid(oid); LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(passwordDelta)); LOGGER.info("delta: {}", DebugUtil.dump(passwordDelta)); changeDescription.setObjectDelta(delta); changeDescription.setOldShadowOid(oid); // changeDescription.setCurrentShadow(angelicaShadowType); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); // WHEN TaskType task = modelWeb.notifyChange(changeDescription); // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); assertUserLdapPassword(userAngelikaAfterSync, newPassword); } @Test public void test503NotifyChangeDeleteAccount() throws Exception{ final String TEST_NAME = "test503NotifyChangeDeleteAccount"; displayTestTitle(TEST_NAME); PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.DELETE); delta.setObjectType(ShadowType.COMPLEX_TYPE); delta.setOid(oid); changeDescription.setObjectDelta(delta); changeDescription.setOldShadowOid(oid); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); // WHEN TaskType task = modelWeb.notifyChange(changeDescription); // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertTrue(result.isAcceptable()); PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); display("User after", userAngelikaAfterSync); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); UserType userType = userAngelikaAfterSync.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", userType.getLinkRef()); assertEquals("Expected no account ref in user", 0, userType.getLinkRef().size()); } @Test public void test999Shutdown() throws Exception { taskManager.shutdown(); waitFor("waiting for task manager shutdown", new Checker() { @Override public boolean check() { return taskManager.getLocallyRunningTasks(new OperationResult("dummy")).isEmpty(); } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 10000); AssertJUnit.assertEquals("Some tasks left running after shutdown", new HashSet<Task>(), new HashSet<>(taskManager.getLocallyRunningTasks(new OperationResult("dummy")))); } // TODO: test for missing/corrupt system configuration // TODO: test for missing sample config (bad reference in expression // arguments) private String checkRepoShadow(PrismObject<ShadowType> repoShadow) { ShadowType repoShadowType = repoShadow.asObjectable(); String uid = null; boolean hasOthers = false; List<Object> xmlAttributes = repoShadowType.getAttributes().getAny(); for (Object element : xmlAttributes) { if (SchemaConstants.ICFS_UID.equals(JAXBUtil.getElementQName(element)) || getOpenDjPrimaryIdentifierQName().equals(JAXBUtil.getElementQName(element))) { if (uid != null) { AssertJUnit.fail("Multiple values for ICF UID in shadow attributes"); } else { uid = ((Element) element).getTextContent(); } } else if (SchemaConstants.ICFS_NAME.equals(JAXBUtil.getElementQName(element)) || getOpenDjSecondaryIdentifierQName().equals(JAXBUtil.getElementQName(element))) { // This is OK } else { hasOthers = true; } } assertFalse("Shadow "+repoShadow+" has unexpected elements", hasOthers); assertNotNull(uid); return uid; } private QName getOpenDjPrimaryIdentifierQName() { return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME); } private QName getOpenDjSecondaryIdentifierQName() { return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME); } private ShadowType searchAccountByOid(final String accountOid) throws Exception { OperationResultType resultType = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(resultType); Holder<ObjectType> accountHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountOid, options, accountHolder, resultHolder); ObjectType object = accountHolder.value; TestUtil.assertSuccess("searchObjects has failed", resultHolder.value); assertNotNull("Account is null", object); if (!(object instanceof ShadowType)) { fail("Object is not account."); } ShadowType account = (ShadowType) object; assertEquals(accountOid, account.getOid()); return account; } private UserType searchUserByName(String name) throws Exception { // Document doc = DOMUtil.getDocument(); // Element nameElement = doc.createElementNS(SchemaConstants.C_NAME.getNamespaceURI(), // SchemaConstants.C_NAME.getLocalPart()); // nameElement.setTextContent(name); // Element filter = QueryUtil.createEqualFilter(doc, null, nameElement); // // QueryType query = new QueryType(); // query.setFilter(filter); ObjectQuery q = ObjectQueryUtil.createNameQuery(UserType.class, prismContext, name); QueryType query = prismContext.getQueryConverter().createQueryType(q); OperationResultType resultType = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(resultType); Holder<ObjectListType> listHolder = new Holder<>(); assertNoRepoCache(); modelWeb.searchObjects(ObjectTypes.USER.getTypeQName(), query, null, listHolder, resultHolder); assertNoRepoCache(); ObjectListType objects = listHolder.value; TestUtil.assertSuccess("searchObjects has failed", resultHolder.value); AssertJUnit.assertEquals("User not found (or found too many)", 1, objects.getObject().size()); UserType user = (UserType) objects.getObject().get(0); AssertJUnit.assertEquals(user.getName(), PrismTestUtil.createPolyStringType(name)); return user; } private void basicWaitForSyncChangeDetection(Task syncCycle, Object tokenBefore, int increment, final OperationResult result) throws Exception { basicWaitForSyncChangeDetection(syncCycle, (int)((Integer)tokenBefore), increment, result); } private void basicWaitForSyncChangeDetection(Task syncCycle, int tokenBefore, int increment, final OperationResult result) throws Exception { basicWaitForSyncChangeDetection(syncCycle, tokenBefore, increment, result, 40000); } private void basicWaitForSyncChangeDetection(final Task syncCycle, final int tokenBefore, final int increment, final OperationResult result, int timeout) throws Exception { waitFor("Waiting for sync cycle to detect change", new Checker() { @Override public boolean check() throws CommonException { syncCycle.refresh(result); display("SyncCycle while waiting for sync cycle to detect change", syncCycle); if (syncCycle.getExecutionStatus() != TaskExecutionStatus.RUNNABLE) { throw new IllegalStateException("Task not runnable: "+syncCycle.getExecutionStatus()+"; "+syncCycle); } int tokenNow = findSyncToken(syncCycle); display("tokenNow = " + tokenNow); if (tokenNow >= tokenBefore + increment) { return true; } else { return false; } } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, timeout, WAIT_FOR_LOOP_SLEEP_MILIS); } private void setAssignmentEnforcement(AssignmentPolicyEnforcementType enforcementType) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(enforcementType); // AccountSynchronizationSettingsType syncSettings = new AccountSynchronizationSettingsType(); // syncSettings.setAssignmentPolicyEnforcement(enforcementType); // applySyncSettings(SystemConfigurationType.class, syncSettings); } private void assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType assignmentPolicy) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult("Asserting sync settings"); PrismObject<SystemConfigurationType> systemConfigurationType = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result); result.computeStatus(); TestUtil.assertSuccess("Asserting sync settings failed (result)", result); ProjectionPolicyType globalAccountSynchronizationSettings = systemConfigurationType.asObjectable().getGlobalAccountSynchronizationSettings(); assertNotNull("globalAccountSynchronizationSettings is null", globalAccountSynchronizationSettings); AssignmentPolicyEnforcementType assignmentPolicyEnforcement = globalAccountSynchronizationSettings.getAssignmentPolicyEnforcement(); assertNotNull("assignmentPolicyEnforcement is null", assignmentPolicyEnforcement); assertEquals("Assignment policy mismatch", assignmentPolicy, assignmentPolicyEnforcement); } private void checkAllShadows() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { LOGGER.trace("Checking all shadows"); System.out.println("Checking all shadows"); ObjectChecker<ShadowType> checker = null; IntegrationTestTools.checkAllShadows(resourceTypeOpenDjrepo, repositoryService, checker, prismContext); } public static String getNormalizedAttributeValue(ShadowType repoShadow, RefinedObjectClassDefinition objClassDef, QName name) { String value = getAttributeValue(repoShadow, name); RefinedAttributeDefinition idDef = objClassDef.getPrimaryIdentifiers().iterator().next(); if (idDef.getMatchingRuleQName() != null && idDef.getMatchingRuleQName().equals(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME)){ return value.toLowerCase(); } return value; } protected <T> void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadowType, attrName, expectedValues); } protected <T> void assertAttribute(PrismObject<ShadowType> shadow, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadow.asObjectable(), attrName, expectedValues); } }
bshp/midPoint
testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java
Java
apache-2.0
199,213
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2230, 1011, 2418, 19852, 2819, 1998, 16884, 1008, 1008, 2023, 2147, 2003, 7037, 1011, 7000, 2104, 1996, 15895, 6105, 1016, 1012, 1014, 1008, 1998, 2647, 2586, 2270, 6105, 1012, 2156, 6105, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * 删除用户同时删除用户的相关禁止信息. * * @author xiaoxia.xu <xiaoxia.xuxx@aliyun-inc.com> * @copyright ©2003-2103 phpwind.com * @license http://www.windframework.com * * @version $Id: PwUserDoBan.php 16415 2012-08-23 07:53:40Z xiaoxia.xuxx $ */ class PwUserDoBan { /** * 根据用户ID删除用户信息. * * @param int $uid * * @return bool|PwError */ public function deleteBan($uid) { /* @var $banDs PwUserBan */ $banDs = Wekit::load('user.PwUserBan'); return $banDs->deleteByUid($uid); } /** * 根据用户ID列表批量删除用户数据. * * @param array $uids * * @return bolean|PwError */ public function batchDeleteBan($uids) { /* @var $banDs PwUserBan */ $banDs = Wekit::load('user.PwUserBan'); return $banDs->batchDeleteByUids($uids); } }
beautifultable/phpwind
phpwind9/src/hooks/PwUser/PwUserDoBan.php
PHP
apache-2.0
929
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 100, 100, 100, 100, 1794, 100, 100, 100, 100, 100, 1916, 1919, 100, 100, 1887, 1767, 100, 1012, 1008, 1008, 1030, 3166, 19523, 14787, 1012, 15990, 1026, 19523, 14787, 1012, 15990, 20348, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * <h2>Form Controller</h2> * * *General idea* * * The form controller is responsible for connecting a form with a model. If no * model is given, a model can be created. This created model will fit exactly * to the given form and can be used for serialization. All the connections * between the form items and the model are handled by an internal * {@link qx.data.controller.Object}. * * *Features* * * * Connect a form to a model (bidirectional) * * Create a model for a given form * * *Usage* * * The controller only works if both a controller and a model are set. * Creating a model will automatically set the created model. * * *Cross reference* * * * If you want to bind single values, use {@link qx.data.controller.Object} * * If you want to bind a list like widget, use {@link qx.data.controller.List} * * If you want to bind a tree widget, use {@link qx.data.controller.Tree} */ qx.Class.define("qx.data.controller.Form", { extend : qx.core.Object, /** * @param model {qx.core.Object | null} The model to bind the target to. The * given object will be set as {@link #model} property. * @param target {qx.ui.form.Form | null} The form which contains the form * items. The given form will be set as {@link #target} property. * @param selfUpdate {Boolean?false} If set to true, you need to call the * {@link #updateModel} method to get the data in the form to the model. * Otherwise, the data will be synced automatically on every change of * the form. */ construct : function(model, target, selfUpdate) { this.base(arguments); this._selfUpdate = !!selfUpdate; this.__bindingOptions = {}; if (model != null) { this.setModel(model); } if (target != null) { this.setTarget(target); } }, properties : { /** Data object containing the data which should be shown in the target. */ model : { check: "qx.core.Object", apply: "_applyModel", event: "changeModel", nullable: true, dereference: true }, /** The target widget which should show the data. */ target : { check: "qx.ui.form.Form", apply: "_applyTarget", event: "changeTarget", nullable: true, init: null, dereference: true } }, members : { __objectController : null, __bindingOptions : null, /** * The form controller uses for setting up the bindings the fundamental * binding layer, the {@link qx.data.SingleValueBinding}. To achieve a * binding in both directions, two bindings are neede. With this method, * you have the opportunity to set the options used for the bindings. * * @param name {String} The name of the form item for which the options * should be used. * @param model2target {Map} Options map used for the binding from model * to target. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. * @param target2model {Map} Options map used for the binding from target * to model. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. */ addBindingOptions : function(name, model2target, target2model) { this.__bindingOptions[name] = [model2target, target2model]; // return if not both, model and target are given if (this.getModel() == null || this.getTarget() == null) { return; } // renew the affected binding var item = this.getTarget().getItems()[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; // remove the binding this.__objectController.removeTarget(item, targetProperty, name); // set up the new binding with the options this.__objectController.addTarget( item, targetProperty, name, !this._selfUpdate, model2target, target2model ); }, /** * Creates and sets a model using the {@link qx.data.marshal.Json} object. * Remember that this method can only work if the form is set. The created * model will fit exactly that form. Changing the form or adding an item to * the form will need a new model creation. * * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. * @return {qx.core.Object} The created model. */ createModel : function(includeBubbleEvents) { var target = this.getTarget(); // throw an error if no target is set if (target == null) { throw new Error("No target is set."); } var items = target.getItems(); var data = {}; for (var name in items) { var names = name.split("."); var currentData = data; for (var i = 0; i < names.length; i++) { // if its the last item if (i + 1 == names.length) { // check if the target is a selection var clazz = items[name].constructor; var itemValue = null; if (qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection)) { // use the first element of the selection because passed to the // marshaler (and its single selection anyway) [BUG #3541] itemValue = items[name].getModelSelection().getItem(0) || null; } else { itemValue = items[name].getValue(); } // call the converter if available [BUG #4382] if (this.__bindingOptions[name] && this.__bindingOptions[name][1]) { itemValue = this.__bindingOptions[name][1].converter(itemValue); } currentData[names[i]] = itemValue; } else { // if its not the last element, check if the object exists if (!currentData[names[i]]) { currentData[names[i]] = {}; } currentData = currentData[names[i]]; } } } var model = qx.data.marshal.Json.createModel(data, includeBubbleEvents); this.setModel(model); return model; }, /** * Responsible for synching the data from entered in the form to the model. * Please keep in mind that this method only works if you create the form * with <code>selfUpdate</code> set to true. Otherwise, this method will * do nothing because updates will be synched automatically on every * change. */ updateModel: function(){ // only do stuff if self update is enabled and a model or target is set if (!this._selfUpdate || !this.getModel() || !this.getTarget()) { return; } var items = this.getTarget().getItems(); for (var name in items) { var item = items[name]; var sourceProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; var options = this.__bindingOptions[name]; options = options && this.__bindingOptions[name][1]; qx.data.SingleValueBinding.updateTarget( item, sourceProperty, this.getModel(), name, options ); } }, // apply method _applyTarget : function(value, old) { // if an old target is given, remove the binding if (old != null) { this.__tearDownBinding(old); } // do nothing if no target is set if (this.getModel() == null) { return; } // target and model are available if (value != null) { this.__setUpBinding(); } }, // apply method _applyModel : function(value, old) { // first, get rid off all bindings (avoids whong data population) if (this.__objectController != null) { var items = this.getTarget().getItems(); for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; this.__objectController.removeTarget(item, targetProperty, name); } } // set the model of the object controller if available if (this.__objectController != null) { this.__objectController.setModel(value); } // do nothing is no target is set if (this.getTarget() == null) { return; } // model and target are available if (value != null) { this.__setUpBinding(); } }, /** * Internal helper for setting up the bindings using * {@link qx.data.controller.Object#addTarget}. All bindings are set * up bidirectional. */ __setUpBinding : function() { // create the object controller if (this.__objectController == null) { this.__objectController = new qx.data.controller.Object(this.getModel()); } // get the form items var items = this.getTarget().getItems(); // connect all items for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; var options = this.__bindingOptions[name]; // try to bind all given items in the form try { if (options == null) { this.__objectController.addTarget(item, targetProperty, name, !this._selfUpdate); } else { this.__objectController.addTarget( item, targetProperty, name, !this._selfUpdate, options[0], options[1] ); } // ignore not working items } catch (ex) { if (qx.core.Environment.get("qx.debug")) { this.warn("Could not bind property " + name + " of " + this.getModel()); } } } }, /** * Internal helper for removing all set up bindings using * {@link qx.data.controller.Object#removeTarget}. * * @param oldTarget {qx.ui.form.Form} The form which has been removed. */ __tearDownBinding : function(oldTarget) { // do nothing if the object controller has not been created if (this.__objectController == null) { return; } // get the items var items = oldTarget.getItems(); // disconnect all items for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; this.__objectController.removeTarget(item, targetProperty, name); } }, /** * Returns whether the given item implements * {@link qx.ui.core.ISingleSelection} and * {@link qx.ui.form.IModelSelection}. * * @param item {qx.ui.form.IForm} The form item to check. * * @return {true} true, if given item fits. */ __isModelSelectable : function(item) { return qx.Class.hasInterface(item.constructor, qx.ui.core.ISingleSelection) && qx.Class.hasInterface(item.constructor, qx.ui.form.IModelSelection); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // dispose the object controller because the bindings need to be removed if (this.__objectController) { this.__objectController.dispose(); } } });
Seldaiendil/meyeOS
devtools/qooxdoo-1.5-sdk/framework/source/class/qx/data/controller/Form.js
JavaScript
agpl-3.0
11,935
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// $Revision$ $Author$ $Date$ /* Copyright (C) 2004 Kurt Schwehr This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /// \file /// \brief Non-graphical rendering engine for waypoints, iv files, and /// SIM Voleon models /// This describes how to do animation: /// file:///sw/share/Coin/html/classSoOffscreenRenderer.html /*************************************************************************** * INCLUDES ***************************************************************************/ // c includes #include <cstdio> #include <cassert> // C++ includes #include <iostream> #include <fstream> #include <sstream> // string stream // STL includes #include <vector> #include <string> // // Inventor/Coin // // Top level includes #include <Inventor/SoInteraction.h> #include <Inventor/SoOffscreenRenderer.h> #include <Inventor/SoOutput.h> // Sensors //#include <Inventor/sensors/SoTimerSensor.h> // Actions #include <Inventor/actions/SoWriteAction.h> // Events #include <Inventor/events/SoMouseButtonEvent.h> #include <Inventor/events/SoLocation2Event.h> #include <Inventor/events/SoKeyboardEvent.h> // Nodes #include <Inventor/nodes/SoEventCallback.h> #include <Inventor/nodes/SoNode.h> #include <Inventor/nodes/SoCamera.h> #include <Inventor/nodes/SoPerspectiveCamera.h> #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoSwitch.h> #include <Inventor/nodes/SoPointLight.h> #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoLineSet.h> #include <Inventor/nodes/SoCoordinate3.h> // Draggers //#include <Inventor/draggers/SoTranslate1Dragger.h> #include <Inventor/draggers/SoSpotLightDragger.h> // Voleon Includes #ifndef NO_VOLEON #include <VolumeViz/nodes/SoVolumeRendering.h> #endif // local includes #include "render_cmd.h" #include "InventorUtilities.H" using namespace std; /*************************************************************************** * MACROS, DEFINES, GLOBALS ***************************************************************************/ // FIX: this needs to be a separate header SoSeparator *MakeSoLineSet (vector<SoSpotLightDragger *> &draggerVec); #include "debug.H" // provides FAILED_HERE, UNUSED, DebugPrintf int debug_level=0; /// Let the debugger find out which version is being used. static const UNUSED char* RCSid ="$Id$"; /*************************************************************************** * SCENEINFO - the big global variable ***************************************************************************/ //#include <Inventor/nodes/SoDirectionalLight.h> class SceneInfo { public: SceneInfo(); SoCamera *camera; SoSeparator *root; vector<SoSpotLightDragger *> draggerVec; ///< All of the draggers that have been added. SoSwitch *draggerSwitch; ///< On/off of the separators. May add code to show one at a time //SoDirectionalLight *headlight; SoPointLight *headlight; ///< if this is not NULL, then move with camera gengetopt_args_info *a; ///< a for args. These are the command line arguments /// Use magic numbers to make sure you actually get this class when you /// must do a cast to/from void pointer static uint8_t nominalMagicNumber() {return(178);} bool magicOk() const {return(nominalMagicNumber()==magicNumber);} ///< Test the class integrity private: uint8_t magicNumber; ///< Help make sure we have a valid SceneInfo structure }; /// Make a SceneInfo object with all pointers set to zero and not animating SceneInfo::SceneInfo() { magicNumber = nominalMagicNumber(); camera = 0; root = 0; draggerSwitch = 0; draggerSwitch = 0; a = 0; headlight=0; } /*************************************************************************** * UTILITUES ***************************************************************************/ void Print (const SoCamera *camera) { assert (camera); const SoSFVec3f *p = &camera->position; SbVec3f p_sb= p->getValue(); float x,y,z; p_sb.getValue(x,y,z); const SoSFRotation *o = &camera->orientation; SbRotation o_sb = o->getValue(); SbVec3f axis; float radians; o_sb.getValue(axis,radians); float ax,ay,az; axis.getValue(ax,ay,az); cout << "Camera -> pos: " << x << " " << y << " " << y << " -- rot: " << ax << " " << ay << " " << az << " " << radians << endl; } /*************************************************************************** * TIMER FOR ANIMATION ***************************************************************************/ /// \brief Return a lineset that does through all the dragger waypoints /// /// Would be better if I did what Alex did back in `98 and use engines with /// the draggers so the line gets automatically updated with drags SoSeparator *MakeSoLineSet (vector<SoSpotLightDragger *> &draggerVec) { DebugPrintf(TRACE,("MakeSoLineSet with %d waypoints\n",int(draggerVec.size()))); SoLineSet *lines = new SoLineSet; if (!lines) {cerr << "ERROR: Unable to allocate lines"<<endl;return 0;} SoCoordinate3 *coords = new SoCoordinate3; if (!coords) {cerr << "ERROR: Unable to allocate lines"<<endl; lines->ref(); lines->unref();return 0;} SoSeparator *sep = new SoSeparator; // FIX error check sep->addChild(coords); sep->addChild(lines); for (size_t i=0;i<draggerVec.size();i++) { SbVec3f xyz(draggerVec[i]->translation.getValue()); float x, y, z; xyz.getValue(x,y,z); coords->point.set1Value(i,x,y,z); } lines->numVertices.setValue(draggerVec.size()); return(sep); } /// \brief Tell if a value is between 2 numbers, inclusive /// \return \a true if v1<=check<=v2 or v2<=check<=v1 bool InRange (const float check, const float v1, const float v2) { float a,b; if (v1<v2) {a=v1;b=v2;} else {a=v2;b=v1;} if (check < a || check > b) return (false); return (true); } /// \brief interpolate between two draggers and render a frame to disk bool WaypointRenderFrameToDisk (const SoSpotLightDragger *d1, const SoSpotLightDragger *d2, const float cur_percent, SoCamera *camera, const string &basename, const string &typeStr, const int width, const int height, SoNode *root, size_t &frame_num, SoPointLight *headlight ) { assert(d1); assert(d2); assert(camera); assert(root); SbVec3f pos1 = d1->translation.getValue(); SbVec3f pos2 = d2->translation.getValue(); vector<float> v1 = ToVector(pos1); vector<float> v2 = ToVector(pos2); vector<float> v3 = InterpolatePos (v1,v2,cur_percent); SbVec3f pos3 = ToSbVec3f (v3); camera->position = pos3; SbRotation rot1 = d1->rotation.getValue(); SbRotation rot2 = d2->rotation.getValue(); SbRotation newRot = SbRotation::slerp (rot1, rot2, cur_percent); camera->orientation = newRot; if (headlight) { headlight->location = pos3; } #ifndef NDEBUG if (debug_level >= VERBOSE) Print(camera); // Show some camera locations! #endif DebugPrintf (TRACE,("ANIMATION: Rendering frame to disk file\n")); SbColor background(0,0,0); // FIX: do background colors! if (!RenderFrameToDisk (basename,typeStr, width, height, root, frame_num, background) ) { cerr << "ERROR: unable to write frame" << endl; return (false); } DebugPrintf(VERBOSE,("ANIMATION: Finished writing frame number %04d\n",int(frame_num))); return (true); } /*************************************************************************** * MAIN ***************************************************************************/ int main(int argc, char *argv[]) { bool ok=true; gengetopt_args_info a; // a == args if (0!=cmdline_parser(argc,argv,&a)){cerr<<"MELT DOWN: should never get here"<<endl;return (EXIT_FAILURE);} #ifdef NDEBUG if (a.verbosity_given) { cerr << "Verbosity is totally ignored for optimized code. Continuing in silent mode" << endl; } #else // debugging debug_level = a.verbosity_arg; DebugPrintf(TRACE,("Debug level = %d\n",debug_level)); #endif if (!CheckLibraryPath()) { cerr << "Bailing. Library path check failed." << endl; return(EXIT_FAILURE);} if (a.list_given) { ListWriteFileTypes(); return (EXIT_SUCCESS); } // // Check range of arguments // if (a.percent_given) if (!InRange(a.percent_arg,0.0,1.0)) {cerr<<"ERROR: Interval must be 0.0<=i<=1.0"<<endl; return (EXIT_FAILURE);} // // Init the SoDB and SimVoleon - no SoQT! // SoDB::init(); SoInteraction::init(); // Initialize for draggers #ifndef NO_VOLEON SoVolumeRendering::init(); #endif if (a.type_given) if (!CheckTypeValid(string(a.type_arg))) { cerr << "File type not valid: --type=" << a.type_arg << endl; return (EXIT_FAILURE); } DebugPrintf(VERBOSE,("FIX: check the range on width and height!\n")); SceneInfo *si = new SceneInfo; si->a=&a; si->root = new SoSeparator; si->root->ref(); { // Need a camera in the scene for the SoOffscreenRender to work si->camera = new SoPerspectiveCamera; si->root->addChild(si->camera); si->camera->nearDistance=a.near_arg; si->camera-> farDistance=a.far_arg; } if (a.headlight_flag) { //si->headlight = new SoDirectionalLight; si->headlight = new SoPointLight; si->root->addChild(si->headlight); } // FIX: do something better with the lights // TOP light { SoPointLight *pl = new SoPointLight; si->root->addChild(pl); pl->location = SbVec3f(0.0f,0.0f,50.0f); } // BOT light { SoPointLight *pl = new SoPointLight; si->root->addChild(pl); pl->location = SbVec3f(0.0f,0.0f,-50.0f); } for (size_t i=0;i<a.inputs_num;i++) { DebugPrintf (TRACE,("Adding file: %s\n",a.inputs[i])); SoInput mySceneInput; if ( !mySceneInput.openFile( a.inputs[i] )) return (EXIT_FAILURE); SoSeparator* node = SoDB::readAll(&mySceneInput); if ( !node ) {cerr << "failed to load iv file: "<<a.inputs[i] << endl; return (EXIT_FAILURE);} mySceneInput.closeFile(); si->root->addChild(node); } // Move this to the SceneInfo constructor { SoSwitch *s = new SoSwitch(40); // We expect a lot of children. assert(s); s->setName ("draggerSwitch"); s->whichChild = SO_SWITCH_ALL; // SO_SWITCH_NONE si->root->addChild(s); si->draggerSwitch=s; } if (!LoadSpotLightDraggers(string(a.waypoints_arg), (SoSeparator *)si->draggerSwitch, si->draggerVec)) { cerr << "ERROR: failed to load waypoints. We're toast." << endl; exit (EXIT_FAILURE); } si->draggerSwitch->whichChild = SO_SWITCH_NONE; // don't show our path if (2>si->draggerVec.size()) { cerr << "ERROR: you must have at least two waypoints in your .wpt file" << endl; exit (EXIT_FAILURE); } if (a.loop_flag) { cout << "Adding first waypoint to the end to form a loop" << endl; si->draggerVec.push_back(si->draggerVec[0]); } ////////////////////////////// // ANIMATE - no timer needed! ////////////////////////////// const string basenameStr(a.basename_arg); const string typeStr(a.type_arg); // -1 cause we do not want to render past last waypoint // we are going from the current way point in wpt to the next waypoint // FIX: don't miss last frame for (size_t wpt=0;wpt<si->draggerVec.size()-1; wpt++) { cout << "Now at waypoint " << wpt << " going to " << wpt+1 << endl; SoSpotLightDragger *d1 = si->draggerVec[wpt]; SoSpotLightDragger *d2 = si->draggerVec[wpt+1]; assert (d1); assert(d2); for (float cur_percent=0.; cur_percent < 1.0; cur_percent += a.percent_arg) { cout << "percent: " << cur_percent << endl; size_t frame_num; const bool r = WaypointRenderFrameToDisk (d1,d2, cur_percent, si->camera, basenameStr, typeStr, a.width_arg, a.height_arg, si->root, frame_num, si->headlight ); if (!r) { cerr << "ERROR: failed to write a frame. I give up." << endl; exit(EXIT_FAILURE); } } // for cur_percent } // for wpt // Render that last missing frame. If looping to start, we do not need this frame if (!a.loop_flag) { DebugPrintf (TRACE,("Rendering final frame.\n")); size_t frame_num; const bool r = WaypointRenderFrameToDisk (si->draggerVec[si->draggerVec.size()-1], si->draggerVec[si->draggerVec.size()-1], 0., si->camera, basenameStr, typeStr, a.width_arg, a.height_arg, si->root, frame_num, si->headlight ); if (!r) { cerr << "ERROR: failed to write a frame. I give up." << endl; exit(EXIT_FAILURE); } } return (ok?EXIT_SUCCESS:EXIT_FAILURE); }
schwehr/density
render.C
C++
gpl-2.0
13,140
[ 30522, 1013, 1013, 1002, 13921, 1002, 1002, 3166, 1002, 1002, 3058, 1002, 1013, 1008, 9385, 1006, 1039, 1007, 2432, 9679, 8040, 2232, 27156, 2023, 2565, 2003, 2489, 4007, 1025, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (c) 2012-2018 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.api.search.server.impl; import java.util.List; import org.eclipse.che.api.search.server.OffsetData; /** Single item in {@code SearchResult}. */ public class SearchResultEntry { private final String filePath; private final List<OffsetData> data; public SearchResultEntry(String filePath, List<OffsetData> data) { this.filePath = filePath; this.data = data; } public List<OffsetData> getData() { return data; } /** Path of file that matches the search criteria. */ public String getFilePath() { return filePath; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof SearchResultEntry)) { return false; } SearchResultEntry that = (SearchResultEntry) o; if (getFilePath() != null ? !getFilePath().equals(that.getFilePath()) : that.getFilePath() != null) { return false; } return getData() != null ? getData().equals(that.getData()) : that.getData() == null; } @Override public int hashCode() { int result = getFilePath() != null ? getFilePath().hashCode() : 0; result = 31 * result + (getData() != null ? getData().hashCode() : 0); return result; } @Override public String toString() { return "SearchResultEntry{" + "filePath='" + filePath + '\'' + ", data=" + data + '}'; } }
sleshchenko/che
wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/search/server/impl/SearchResultEntry.java
Java
epl-1.0
1,751
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2262, 1011, 2760, 2417, 6045, 1010, 4297, 1012, 1008, 2035, 2916, 9235, 1012, 2023, 2565, 1998, 1996, 10860, 4475, 1008, 2024, 2081, 2800, 2104, 1996, 3408, 1997, 1996, 13232, 2270, 6105, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (c) 2011, Luca Barbato * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file generic segmenter * M3U8 specification can be find here: * @url{http://tools.ietf.org/id/draft-pantos-http-live-streaming} */ #include <float.h> #include <time.h> #include "avformat.h" #include "avio_internal.h" #include "internal.h" #include "libavutil/avassert.h" #include "libavutil/internal.h" #include "libavutil/log.h" #include "libavutil/opt.h" #include "libavutil/avstring.h" #include "libavutil/parseutils.h" #include "libavutil/mathematics.h" #include "libavutil/time.h" #include "libavutil/timecode.h" #include "libavutil/time_internal.h" #include "libavutil/timestamp.h" typedef struct SegmentListEntry { int index; double start_time, end_time; int64_t start_pts; int64_t offset_pts; char *filename; struct SegmentListEntry *next; int64_t last_duration; } SegmentListEntry; typedef enum { LIST_TYPE_UNDEFINED = -1, LIST_TYPE_FLAT = 0, LIST_TYPE_CSV, LIST_TYPE_M3U8, LIST_TYPE_EXT, ///< deprecated LIST_TYPE_FFCONCAT, LIST_TYPE_NB, } ListType; #define SEGMENT_LIST_FLAG_CACHE 1 #define SEGMENT_LIST_FLAG_LIVE 2 typedef struct SegmentContext { const AVClass *class; /**< Class for private options. */ int segment_idx; ///< index of the segment file to write, starting from 0 int segment_idx_wrap; ///< number after which the index wraps int segment_idx_wrap_nb; ///< number of time the index has wraped int segment_count; ///< number of segment files already written ff_const59 AVOutputFormat *oformat; AVFormatContext *avf; char *format; ///< format to use for output segment files AVDictionary *format_options; char *list; ///< filename for the segment list file int list_flags; ///< flags affecting list generation int list_size; ///< number of entries for the segment list file int use_clocktime; ///< flag to cut segments at regular clock time int64_t clocktime_offset; //< clock offset for cutting the segments at regular clock time int64_t clocktime_wrap_duration; //< wrapping duration considered for starting a new segment int64_t last_val; ///< remember last time for wrap around detection int cut_pending; int header_written; ///< whether we've already called avformat_write_header char *entry_prefix; ///< prefix to add to list entry filenames int list_type; ///< set the list type AVIOContext *list_pb; ///< list file put-byte context char *time_str; ///< segment duration specification string int64_t time; ///< segment duration int use_strftime; ///< flag to expand filename with strftime int increment_tc; ///< flag to increment timecode if found char *times_str; ///< segment times specification string int64_t *times; ///< list of segment interval specification int nb_times; ///< number of elments in the times array char *frames_str; ///< segment frame numbers specification string int *frames; ///< list of frame number specification int nb_frames; ///< number of elments in the frames array int frame_count; ///< total number of reference frames int segment_frame_count; ///< number of reference frames in the segment int64_t time_delta; int individual_header_trailer; /**< Set by a private option. */ int write_header_trailer; /**< Set by a private option. */ char *header_filename; ///< filename to write the output header to int reset_timestamps; ///< reset timestamps at the beginning of each segment int64_t initial_offset; ///< initial timestamps offset, expressed in microseconds char *reference_stream_specifier; ///< reference stream specifier int reference_stream_index; int break_non_keyframes; int write_empty; int use_rename; char temp_list_filename[1024]; SegmentListEntry cur_entry; SegmentListEntry *segment_list_entries; SegmentListEntry *segment_list_entries_end; } SegmentContext; static void print_csv_escaped_str(AVIOContext *ctx, const char *str) { int needs_quoting = !!str[strcspn(str, "\",\n\r")]; if (needs_quoting) avio_w8(ctx, '"'); for (; *str; str++) { if (*str == '"') avio_w8(ctx, '"'); avio_w8(ctx, *str); } if (needs_quoting) avio_w8(ctx, '"'); } static int segment_mux_init(AVFormatContext *s) { SegmentContext *seg = s->priv_data; AVFormatContext *oc; int i; int ret; ret = avformat_alloc_output_context2(&seg->avf, seg->oformat, NULL, NULL); if (ret < 0) return ret; oc = seg->avf; oc->interrupt_callback = s->interrupt_callback; oc->max_delay = s->max_delay; av_dict_copy(&oc->metadata, s->metadata, 0); oc->opaque = s->opaque; oc->io_close = s->io_close; oc->io_open = s->io_open; oc->flags = s->flags; for (i = 0; i < s->nb_streams; i++) { AVStream *st; AVCodecParameters *ipar, *opar; if (!(st = avformat_new_stream(oc, NULL))) return AVERROR(ENOMEM); ipar = s->streams[i]->codecpar; opar = st->codecpar; avcodec_parameters_copy(opar, ipar); if (!oc->oformat->codec_tag || av_codec_get_id (oc->oformat->codec_tag, ipar->codec_tag) == opar->codec_id || av_codec_get_tag(oc->oformat->codec_tag, ipar->codec_id) <= 0) { opar->codec_tag = ipar->codec_tag; } else { opar->codec_tag = 0; } st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio; st->time_base = s->streams[i]->time_base; st->avg_frame_rate = s->streams[i]->avg_frame_rate; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS if (s->streams[i]->codecpar->codec_tag == MKTAG('t','m','c','d')) st->codec->time_base = s->streams[i]->codec->time_base; FF_ENABLE_DEPRECATION_WARNINGS #endif av_dict_copy(&st->metadata, s->streams[i]->metadata, 0); } return 0; } static int set_segment_filename(AVFormatContext *s) { SegmentContext *seg = s->priv_data; AVFormatContext *oc = seg->avf; size_t size; int ret; char buf[1024]; char *new_name; if (seg->segment_idx_wrap) seg->segment_idx %= seg->segment_idx_wrap; if (seg->use_strftime) { time_t now0; struct tm *tm, tmpbuf; time(&now0); tm = localtime_r(&now0, &tmpbuf); if (!strftime(buf, sizeof(buf), s->url, tm)) { av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n"); return AVERROR(EINVAL); } } else if (av_get_frame_filename(buf, sizeof(buf), s->url, seg->segment_idx) < 0) { av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->url); return AVERROR(EINVAL); } new_name = av_strdup(buf); if (!new_name) return AVERROR(ENOMEM); ff_format_set_url(oc, new_name); /* copy modified name in list entry */ size = strlen(av_basename(oc->url)) + 1; if (seg->entry_prefix) size += strlen(seg->entry_prefix); if ((ret = av_reallocp(&seg->cur_entry.filename, size)) < 0) return ret; snprintf(seg->cur_entry.filename, size, "%s%s", seg->entry_prefix ? seg->entry_prefix : "", av_basename(oc->url)); return 0; } static int segment_start(AVFormatContext *s, int write_header) { SegmentContext *seg = s->priv_data; AVFormatContext *oc = seg->avf; int err = 0; if (write_header) { avformat_free_context(oc); seg->avf = NULL; if ((err = segment_mux_init(s)) < 0) return err; oc = seg->avf; } seg->segment_idx++; if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0)) seg->segment_idx_wrap_nb++; if ((err = set_segment_filename(s)) < 0) return err; if ((err = s->io_open(s, &oc->pb, oc->url, AVIO_FLAG_WRITE, NULL)) < 0) { av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->url); return err; } if (!seg->individual_header_trailer) oc->pb->seekable = 0; if (oc->oformat->priv_class && oc->priv_data) av_opt_set(oc->priv_data, "mpegts_flags", "+resend_headers", 0); if (write_header) { AVDictionary *options = NULL; av_dict_copy(&options, seg->format_options, 0); av_dict_set(&options, "fflags", "-autobsf", 0); err = avformat_write_header(oc, &options); av_dict_free(&options); if (err < 0) return err; } seg->segment_frame_count = 0; return 0; } static int segment_list_open(AVFormatContext *s) { SegmentContext *seg = s->priv_data; int ret; snprintf(seg->temp_list_filename, sizeof(seg->temp_list_filename), seg->use_rename ? "%s.tmp" : "%s", seg->list); ret = s->io_open(s, &seg->list_pb, seg->temp_list_filename, AVIO_FLAG_WRITE, NULL); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Failed to open segment list '%s'\n", seg->list); return ret; } if (seg->list_type == LIST_TYPE_M3U8 && seg->segment_list_entries) { SegmentListEntry *entry; double max_duration = 0; avio_printf(seg->list_pb, "#EXTM3U\n"); avio_printf(seg->list_pb, "#EXT-X-VERSION:3\n"); avio_printf(seg->list_pb, "#EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index); avio_printf(seg->list_pb, "#EXT-X-ALLOW-CACHE:%s\n", seg->list_flags & SEGMENT_LIST_FLAG_CACHE ? "YES" : "NO"); av_log(s, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%d\n", seg->segment_list_entries->index); for (entry = seg->segment_list_entries; entry; entry = entry->next) max_duration = FFMAX(max_duration, entry->end_time - entry->start_time); avio_printf(seg->list_pb, "#EXT-X-TARGETDURATION:%"PRId64"\n", (int64_t)ceil(max_duration)); } else if (seg->list_type == LIST_TYPE_FFCONCAT) { avio_printf(seg->list_pb, "ffconcat version 1.0\n"); } return ret; } static void segment_list_print_entry(AVIOContext *list_ioctx, ListType list_type, const SegmentListEntry *list_entry, void *log_ctx) { switch (list_type) { case LIST_TYPE_FLAT: avio_printf(list_ioctx, "%s\n", list_entry->filename); break; case LIST_TYPE_CSV: case LIST_TYPE_EXT: print_csv_escaped_str(list_ioctx, list_entry->filename); avio_printf(list_ioctx, ",%f,%f\n", list_entry->start_time, list_entry->end_time); break; case LIST_TYPE_M3U8: avio_printf(list_ioctx, "#EXTINF:%f,\n%s\n", list_entry->end_time - list_entry->start_time, list_entry->filename); break; case LIST_TYPE_FFCONCAT: { char *buf; if (av_escape(&buf, list_entry->filename, NULL, AV_ESCAPE_MODE_AUTO, AV_ESCAPE_FLAG_WHITESPACE) < 0) { av_log(log_ctx, AV_LOG_WARNING, "Error writing list entry '%s' in list file\n", list_entry->filename); return; } avio_printf(list_ioctx, "file %s\n", buf); av_free(buf); break; } default: av_assert0(!"Invalid list type"); } } static int segment_end(AVFormatContext *s, int write_trailer, int is_last) { SegmentContext *seg = s->priv_data; AVFormatContext *oc = seg->avf; int ret = 0; AVTimecode tc; AVRational rate; AVDictionaryEntry *tcr; char buf[AV_TIMECODE_STR_SIZE]; int i; int err; if (!oc || !oc->pb) return AVERROR(EINVAL); av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */ if (write_trailer) ret = av_write_trailer(oc); if (ret < 0) av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n", oc->url); if (seg->list) { if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) { SegmentListEntry *entry = av_mallocz(sizeof(*entry)); if (!entry) { ret = AVERROR(ENOMEM); goto end; } /* append new element */ memcpy(entry, &seg->cur_entry, sizeof(*entry)); entry->filename = av_strdup(entry->filename); if (!seg->segment_list_entries) seg->segment_list_entries = seg->segment_list_entries_end = entry; else seg->segment_list_entries_end->next = entry; seg->segment_list_entries_end = entry; /* drop first item */ if (seg->list_size && seg->segment_count >= seg->list_size) { entry = seg->segment_list_entries; seg->segment_list_entries = seg->segment_list_entries->next; av_freep(&entry->filename); av_freep(&entry); } if ((ret = segment_list_open(s)) < 0) goto end; for (entry = seg->segment_list_entries; entry; entry = entry->next) segment_list_print_entry(seg->list_pb, seg->list_type, entry, s); if (seg->list_type == LIST_TYPE_M3U8 && is_last) avio_printf(seg->list_pb, "#EXT-X-ENDLIST\n"); ff_format_io_close(s, &seg->list_pb); if (seg->use_rename) ff_rename(seg->temp_list_filename, seg->list, s); } else { segment_list_print_entry(seg->list_pb, seg->list_type, &seg->cur_entry, s); avio_flush(seg->list_pb); } } av_log(s, AV_LOG_VERBOSE, "segment:'%s' count:%d ended\n", seg->avf->url, seg->segment_count); seg->segment_count++; if (seg->increment_tc) { tcr = av_dict_get(s->metadata, "timecode", NULL, 0); if (tcr) { /* search the first video stream */ for (i = 0; i < s->nb_streams; i++) { if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { rate = s->streams[i]->avg_frame_rate;/* Get fps from the video stream */ err = av_timecode_init_from_string(&tc, rate, tcr->value, s); if (err < 0) { av_log(s, AV_LOG_WARNING, "Could not increment global timecode, error occurred during timecode creation.\n"); break; } tc.start += (int)((seg->cur_entry.end_time - seg->cur_entry.start_time) * av_q2d(rate));/* increment timecode */ av_dict_set(&s->metadata, "timecode", av_timecode_make_string(&tc, buf, 0), 0); break; } } } else { av_log(s, AV_LOG_WARNING, "Could not increment global timecode, no global timecode metadata found.\n"); } for (i = 0; i < s->nb_streams; i++) { if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { char st_buf[AV_TIMECODE_STR_SIZE]; AVTimecode st_tc; AVRational st_rate = s->streams[i]->avg_frame_rate; AVDictionaryEntry *st_tcr = av_dict_get(s->streams[i]->metadata, "timecode", NULL, 0); if (st_tcr) { if ((av_timecode_init_from_string(&st_tc, st_rate, st_tcr->value, s) < 0)) { av_log(s, AV_LOG_WARNING, "Could not increment stream %d timecode, error occurred during timecode creation.\n", i); continue; } st_tc.start += (int)((seg->cur_entry.end_time - seg->cur_entry.start_time) * av_q2d(st_rate)); // increment timecode av_dict_set(&s->streams[i]->metadata, "timecode", av_timecode_make_string(&st_tc, st_buf, 0), 0); } } } } end: ff_format_io_close(oc, &oc->pb); return ret; } static int parse_times(void *log_ctx, int64_t **times, int *nb_times, const char *times_str) { char *p; int i, ret = 0; char *times_str1 = av_strdup(times_str); char *saveptr = NULL; if (!times_str1) return AVERROR(ENOMEM); #define FAIL(err) ret = err; goto end *nb_times = 1; for (p = times_str1; *p; p++) if (*p == ',') (*nb_times)++; *times = av_malloc_array(*nb_times, sizeof(**times)); if (!*times) { av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced times array\n"); FAIL(AVERROR(ENOMEM)); } p = times_str1; for (i = 0; i < *nb_times; i++) { int64_t t; char *tstr = av_strtok(p, ",", &saveptr); p = NULL; if (!tstr || !tstr[0]) { av_log(log_ctx, AV_LOG_ERROR, "Empty time specification in times list %s\n", times_str); FAIL(AVERROR(EINVAL)); } ret = av_parse_time(&t, tstr, 1); if (ret < 0) { av_log(log_ctx, AV_LOG_ERROR, "Invalid time duration specification '%s' in times list %s\n", tstr, times_str); FAIL(AVERROR(EINVAL)); } (*times)[i] = t; /* check on monotonicity */ if (i && (*times)[i-1] > (*times)[i]) { av_log(log_ctx, AV_LOG_ERROR, "Specified time %f is greater than the following time %f\n", (float)((*times)[i])/1000000, (float)((*times)[i-1])/1000000); FAIL(AVERROR(EINVAL)); } } end: av_free(times_str1); return ret; } static int parse_frames(void *log_ctx, int **frames, int *nb_frames, const char *frames_str) { char *p; int i, ret = 0; char *frames_str1 = av_strdup(frames_str); char *saveptr = NULL; if (!frames_str1) return AVERROR(ENOMEM); #define FAIL(err) ret = err; goto end *nb_frames = 1; for (p = frames_str1; *p; p++) if (*p == ',') (*nb_frames)++; *frames = av_malloc_array(*nb_frames, sizeof(**frames)); if (!*frames) { av_log(log_ctx, AV_LOG_ERROR, "Could not allocate forced frames array\n"); FAIL(AVERROR(ENOMEM)); } p = frames_str1; for (i = 0; i < *nb_frames; i++) { long int f; char *tailptr; char *fstr = av_strtok(p, ",", &saveptr); p = NULL; if (!fstr) { av_log(log_ctx, AV_LOG_ERROR, "Empty frame specification in frame list %s\n", frames_str); FAIL(AVERROR(EINVAL)); } f = strtol(fstr, &tailptr, 10); if (*tailptr || f <= 0 || f >= INT_MAX) { av_log(log_ctx, AV_LOG_ERROR, "Invalid argument '%s', must be a positive integer <= INT64_MAX\n", fstr); FAIL(AVERROR(EINVAL)); } (*frames)[i] = f; /* check on monotonicity */ if (i && (*frames)[i-1] > (*frames)[i]) { av_log(log_ctx, AV_LOG_ERROR, "Specified frame %d is greater than the following frame %d\n", (*frames)[i], (*frames)[i-1]); FAIL(AVERROR(EINVAL)); } } end: av_free(frames_str1); return ret; } static int open_null_ctx(AVIOContext **ctx) { int buf_size = 32768; uint8_t *buf = av_malloc(buf_size); if (!buf) return AVERROR(ENOMEM); *ctx = avio_alloc_context(buf, buf_size, AVIO_FLAG_WRITE, NULL, NULL, NULL, NULL); if (!*ctx) { av_free(buf); return AVERROR(ENOMEM); } return 0; } static void close_null_ctxp(AVIOContext **pb) { av_freep(&(*pb)->buffer); avio_context_free(pb); } static int select_reference_stream(AVFormatContext *s) { SegmentContext *seg = s->priv_data; int ret, i; seg->reference_stream_index = -1; if (!strcmp(seg->reference_stream_specifier, "auto")) { /* select first index of type with highest priority */ int type_index_map[AVMEDIA_TYPE_NB]; static const enum AVMediaType type_priority_list[] = { AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_DATA, AVMEDIA_TYPE_ATTACHMENT }; enum AVMediaType type; for (i = 0; i < AVMEDIA_TYPE_NB; i++) type_index_map[i] = -1; /* select first index for each type */ for (i = 0; i < s->nb_streams; i++) { type = s->streams[i]->codecpar->codec_type; if ((unsigned)type < AVMEDIA_TYPE_NB && type_index_map[type] == -1 /* ignore attached pictures/cover art streams */ && !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC)) type_index_map[type] = i; } for (i = 0; i < FF_ARRAY_ELEMS(type_priority_list); i++) { type = type_priority_list[i]; if ((seg->reference_stream_index = type_index_map[type]) >= 0) break; } } else { for (i = 0; i < s->nb_streams; i++) { ret = avformat_match_stream_specifier(s, s->streams[i], seg->reference_stream_specifier); if (ret < 0) return ret; if (ret > 0) { seg->reference_stream_index = i; break; } } } if (seg->reference_stream_index < 0) { av_log(s, AV_LOG_ERROR, "Could not select stream matching identifier '%s'\n", seg->reference_stream_specifier); return AVERROR(EINVAL); } return 0; } static void seg_free(AVFormatContext *s) { SegmentContext *seg = s->priv_data; ff_format_io_close(seg->avf, &seg->list_pb); avformat_free_context(seg->avf); seg->avf = NULL; } static int seg_init(AVFormatContext *s) { SegmentContext *seg = s->priv_data; AVFormatContext *oc = seg->avf; AVDictionary *options = NULL; int ret; int i; seg->segment_count = 0; if (!seg->write_header_trailer) seg->individual_header_trailer = 0; if (seg->header_filename) { seg->write_header_trailer = 1; seg->individual_header_trailer = 0; } if (seg->initial_offset > 0) { av_log(s, AV_LOG_WARNING, "NOTE: the option initial_offset is deprecated," "you can use output_ts_offset instead of it\n"); } if (!!seg->time_str + !!seg->times_str + !!seg->frames_str > 1) { av_log(s, AV_LOG_ERROR, "segment_time, segment_times, and segment_frames options " "are mutually exclusive, select just one of them\n"); return AVERROR(EINVAL); } if (seg->times_str) { if ((ret = parse_times(s, &seg->times, &seg->nb_times, seg->times_str)) < 0) return ret; } else if (seg->frames_str) { if ((ret = parse_frames(s, &seg->frames, &seg->nb_frames, seg->frames_str)) < 0) return ret; } else { /* set default value if not specified */ if (!seg->time_str) seg->time_str = av_strdup("2"); if ((ret = av_parse_time(&seg->time, seg->time_str, 1)) < 0) { av_log(s, AV_LOG_ERROR, "Invalid time duration specification '%s' for segment_time option\n", seg->time_str); return ret; } if (seg->use_clocktime) { if (seg->time <= 0) { av_log(s, AV_LOG_ERROR, "Invalid negative segment_time with segment_atclocktime option set\n"); return AVERROR(EINVAL); } seg->clocktime_offset = seg->time - (seg->clocktime_offset % seg->time); } } if (seg->list) { if (seg->list_type == LIST_TYPE_UNDEFINED) { if (av_match_ext(seg->list, "csv" )) seg->list_type = LIST_TYPE_CSV; else if (av_match_ext(seg->list, "ext" )) seg->list_type = LIST_TYPE_EXT; else if (av_match_ext(seg->list, "m3u8")) seg->list_type = LIST_TYPE_M3U8; else if (av_match_ext(seg->list, "ffcat,ffconcat")) seg->list_type = LIST_TYPE_FFCONCAT; else seg->list_type = LIST_TYPE_FLAT; } if (!seg->list_size && seg->list_type != LIST_TYPE_M3U8) { if ((ret = segment_list_open(s)) < 0) return ret; } else { const char *proto = avio_find_protocol_name(seg->list); seg->use_rename = proto && !strcmp(proto, "file"); } } if (seg->list_type == LIST_TYPE_EXT) av_log(s, AV_LOG_WARNING, "'ext' list type option is deprecated in favor of 'csv'\n"); if ((ret = select_reference_stream(s)) < 0) return ret; av_log(s, AV_LOG_VERBOSE, "Selected stream id:%d type:%s\n", seg->reference_stream_index, av_get_media_type_string(s->streams[seg->reference_stream_index]->codecpar->codec_type)); seg->oformat = av_guess_format(seg->format, s->url, NULL); if (!seg->oformat) return AVERROR_MUXER_NOT_FOUND; if (seg->oformat->flags & AVFMT_NOFILE) { av_log(s, AV_LOG_ERROR, "format %s not supported.\n", seg->oformat->name); return AVERROR(EINVAL); } if ((ret = segment_mux_init(s)) < 0) return ret; if ((ret = set_segment_filename(s)) < 0) return ret; oc = seg->avf; if (seg->write_header_trailer) { if ((ret = s->io_open(s, &oc->pb, seg->header_filename ? seg->header_filename : oc->url, AVIO_FLAG_WRITE, NULL)) < 0) { av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", oc->url); return ret; } if (!seg->individual_header_trailer) oc->pb->seekable = 0; } else { if ((ret = open_null_ctx(&oc->pb)) < 0) return ret; } av_dict_copy(&options, seg->format_options, 0); av_dict_set(&options, "fflags", "-autobsf", 0); ret = avformat_init_output(oc, &options); if (av_dict_count(options)) { av_log(s, AV_LOG_ERROR, "Some of the provided format options are not recognized\n"); av_dict_free(&options); return AVERROR(EINVAL); } av_dict_free(&options); if (ret < 0) { ff_format_io_close(oc, &oc->pb); return ret; } seg->segment_frame_count = 0; av_assert0(s->nb_streams == oc->nb_streams); if (ret == AVSTREAM_INIT_IN_WRITE_HEADER) { ret = avformat_write_header(oc, NULL); if (ret < 0) return ret; seg->header_written = 1; } for (i = 0; i < s->nb_streams; i++) { AVStream *inner_st = oc->streams[i]; AVStream *outer_st = s->streams[i]; avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den); } if (oc->avoid_negative_ts > 0 && s->avoid_negative_ts < 0) s->avoid_negative_ts = 1; return ret; } static int seg_write_header(AVFormatContext *s) { SegmentContext *seg = s->priv_data; AVFormatContext *oc = seg->avf; int ret, i; if (!seg->header_written) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = oc->streams[i]; AVCodecParameters *ipar, *opar; ipar = s->streams[i]->codecpar; opar = oc->streams[i]->codecpar; avcodec_parameters_copy(opar, ipar); if (!oc->oformat->codec_tag || av_codec_get_id (oc->oformat->codec_tag, ipar->codec_tag) == opar->codec_id || av_codec_get_tag(oc->oformat->codec_tag, ipar->codec_id) <= 0) { opar->codec_tag = ipar->codec_tag; } else { opar->codec_tag = 0; } st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio; st->time_base = s->streams[i]->time_base; } ret = avformat_write_header(oc, NULL); if (ret < 0) return ret; } if (!seg->write_header_trailer || seg->header_filename) { if (seg->header_filename) { av_write_frame(oc, NULL); ff_format_io_close(oc, &oc->pb); } else { close_null_ctxp(&oc->pb); } if ((ret = oc->io_open(oc, &oc->pb, oc->url, AVIO_FLAG_WRITE, NULL)) < 0) return ret; if (!seg->individual_header_trailer) oc->pb->seekable = 0; } return 0; } static int seg_write_packet(AVFormatContext *s, AVPacket *pkt) { SegmentContext *seg = s->priv_data; AVStream *st = s->streams[pkt->stream_index]; int64_t end_pts = INT64_MAX, offset; int start_frame = INT_MAX; int ret; struct tm ti; int64_t usecs; int64_t wrapped_val; if (!seg->avf || !seg->avf->pb) return AVERROR(EINVAL); if (!st->codecpar->extradata_size) { int pkt_extradata_size = 0; uint8_t *pkt_extradata = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &pkt_extradata_size); if (pkt_extradata && pkt_extradata_size > 0) { ret = ff_alloc_extradata(st->codecpar, pkt_extradata_size); if (ret < 0) { av_log(s, AV_LOG_WARNING, "Unable to add extradata to stream. Output segments may be invalid.\n"); goto calc_times; } memcpy(st->codecpar->extradata, pkt_extradata, pkt_extradata_size); } } calc_times: if (seg->times) { end_pts = seg->segment_count < seg->nb_times ? seg->times[seg->segment_count] : INT64_MAX; } else if (seg->frames) { start_frame = seg->segment_count < seg->nb_frames ? seg->frames[seg->segment_count] : INT_MAX; } else { if (seg->use_clocktime) { int64_t avgt = av_gettime(); time_t sec = avgt / 1000000; localtime_r(&sec, &ti); usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000); wrapped_val = (usecs + seg->clocktime_offset) % seg->time; if (wrapped_val < seg->last_val && wrapped_val < seg->clocktime_wrap_duration) seg->cut_pending = 1; seg->last_val = wrapped_val; } else { end_pts = seg->time * (seg->segment_count + 1); } } ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n", pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), av_ts2timestr(pkt->duration, &st->time_base), pkt->flags & AV_PKT_FLAG_KEY, pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1); if (pkt->stream_index == seg->reference_stream_index && (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) && (seg->segment_frame_count > 0 || seg->write_empty) && (seg->cut_pending || seg->frame_count >= start_frame || (pkt->pts != AV_NOPTS_VALUE && av_compare_ts(pkt->pts, st->time_base, end_pts - seg->time_delta, AV_TIME_BASE_Q) >= 0))) { /* sanitize end time in case last packet didn't have a defined duration */ if (seg->cur_entry.last_duration == 0) seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base); if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0) goto fail; if ((ret = segment_start(s, seg->individual_header_trailer)) < 0) goto fail; seg->cut_pending = 0; seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb; seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base); seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q); seg->cur_entry.end_time = seg->cur_entry.start_time; if (seg->times || (!seg->frames && !seg->use_clocktime) && seg->write_empty) goto calc_times; } if (pkt->stream_index == seg->reference_stream_index) { if (pkt->pts != AV_NOPTS_VALUE) seg->cur_entry.end_time = FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base)); seg->cur_entry.last_duration = pkt->duration; } if (seg->segment_frame_count == 0) { av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n", seg->avf->url, pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count); } av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s", pkt->stream_index, av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q), av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base)); /* compute new timestamps */ offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0), AV_TIME_BASE_Q, st->time_base); if (pkt->pts != AV_NOPTS_VALUE) pkt->pts += offset; if (pkt->dts != AV_NOPTS_VALUE) pkt->dts += offset; av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n", av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base)); ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps || seg->avf->oformat->interleave_packet); fail: if (pkt->stream_index == seg->reference_stream_index) { seg->frame_count++; seg->segment_frame_count++; } return ret; } static int seg_write_trailer(struct AVFormatContext *s) { SegmentContext *seg = s->priv_data; AVFormatContext *oc = seg->avf; SegmentListEntry *cur, *next; int ret = 0; if (!oc) goto fail; if (!seg->write_header_trailer) { if ((ret = segment_end(s, 0, 1)) < 0) goto fail; if ((ret = open_null_ctx(&oc->pb)) < 0) goto fail; ret = av_write_trailer(oc); close_null_ctxp(&oc->pb); } else { ret = segment_end(s, 1, 1); } fail: if (seg->list) ff_format_io_close(s, &seg->list_pb); av_opt_free(seg); av_freep(&seg->times); av_freep(&seg->frames); av_freep(&seg->cur_entry.filename); cur = seg->segment_list_entries; while (cur) { next = cur->next; av_freep(&cur->filename); av_free(cur); cur = next; } avformat_free_context(oc); seg->avf = NULL; return ret; } static int seg_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { SegmentContext *seg = s->priv_data; AVFormatContext *oc = seg->avf; if (oc->oformat->check_bitstream) { int ret = oc->oformat->check_bitstream(oc, pkt); if (ret == 1) { AVStream *st = s->streams[pkt->stream_index]; AVStream *ost = oc->streams[pkt->stream_index]; st->internal->bsfc = ost->internal->bsfc; ost->internal->bsfc = NULL; } return ret; } return 1; } #define OFFSET(x) offsetof(SegmentContext, x) #define E AV_OPT_FLAG_ENCODING_PARAM static const AVOption options[] = { { "reference_stream", "set reference stream", OFFSET(reference_stream_specifier), AV_OPT_TYPE_STRING, {.str = "auto"}, 0, 0, E }, { "segment_format", "set container format used for the segments", OFFSET(format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E }, { "segment_format_options", "set list of options for the container format used for the segments", OFFSET(format_options), AV_OPT_TYPE_DICT, {.str = NULL}, 0, 0, E }, { "segment_list", "set the segment list filename", OFFSET(list), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E }, { "segment_header_filename", "write a single file containing the header", OFFSET(header_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E }, { "segment_list_flags","set flags affecting segment list generation", OFFSET(list_flags), AV_OPT_TYPE_FLAGS, {.i64 = SEGMENT_LIST_FLAG_CACHE }, 0, UINT_MAX, E, "list_flags"}, { "cache", "allow list caching", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_CACHE }, INT_MIN, INT_MAX, E, "list_flags"}, { "live", "enable live-friendly list generation (useful for HLS)", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_LIST_FLAG_LIVE }, INT_MIN, INT_MAX, E, "list_flags"}, { "segment_list_size", "set the maximum number of playlist entries", OFFSET(list_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E }, { "segment_list_type", "set the segment list type", OFFSET(list_type), AV_OPT_TYPE_INT, {.i64 = LIST_TYPE_UNDEFINED}, -1, LIST_TYPE_NB-1, E, "list_type" }, { "flat", "flat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FLAT }, INT_MIN, INT_MAX, E, "list_type" }, { "csv", "csv format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_CSV }, INT_MIN, INT_MAX, E, "list_type" }, { "ext", "extended format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_EXT }, INT_MIN, INT_MAX, E, "list_type" }, { "ffconcat", "ffconcat format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_FFCONCAT }, INT_MIN, INT_MAX, E, "list_type" }, { "m3u8", "M3U8 format", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" }, { "hls", "Apple HTTP Live Streaming compatible", 0, AV_OPT_TYPE_CONST, {.i64=LIST_TYPE_M3U8 }, INT_MIN, INT_MAX, E, "list_type" }, { "segment_atclocktime", "set segment to be cut at clocktime", OFFSET(use_clocktime), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E}, { "segment_clocktime_offset", "set segment clocktime offset", OFFSET(clocktime_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, 86400000000LL, E}, { "segment_clocktime_wrap_duration", "set segment clocktime wrapping duration", OFFSET(clocktime_wrap_duration), AV_OPT_TYPE_DURATION, {.i64 = INT64_MAX}, 0, INT64_MAX, E}, { "segment_time", "set segment duration", OFFSET(time_str),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E }, { "segment_time_delta","set approximation value used for the segment times", OFFSET(time_delta), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, E }, { "segment_times", "set segment split time points", OFFSET(times_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E }, { "segment_frames", "set segment split frame numbers", OFFSET(frames_str),AV_OPT_TYPE_STRING,{.str = NULL}, 0, 0, E }, { "segment_wrap", "set number after which the index wraps", OFFSET(segment_idx_wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E }, { "segment_list_entry_prefix", "set base url prefix for segments", OFFSET(entry_prefix), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E }, { "segment_start_number", "set the sequence number of the first segment", OFFSET(segment_idx), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E }, { "segment_wrap_number", "set the number of wrap before the first segment", OFFSET(segment_idx_wrap_nb), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E }, { "strftime", "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E }, { "increment_tc", "increment timecode between each segment", OFFSET(increment_tc), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E }, { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E }, { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E }, { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E }, { "reset_timestamps", "reset timestamps at the beginning of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E }, { "initial_offset", "set initial timestamp offset", OFFSET(initial_offset), AV_OPT_TYPE_DURATION, {.i64 = 0}, -INT64_MAX, INT64_MAX, E }, { "write_empty_segments", "allow writing empty 'filler' segments", OFFSET(write_empty), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E }, { NULL }, }; #if CONFIG_SEGMENT_MUXER static const AVClass seg_class = { .class_name = "segment muxer", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVOutputFormat ff_segment_muxer = { .name = "segment", .long_name = NULL_IF_CONFIG_SMALL("segment"), .priv_data_size = sizeof(SegmentContext), .flags = AVFMT_NOFILE|AVFMT_GLOBALHEADER, .init = seg_init, .write_header = seg_write_header, .write_packet = seg_write_packet, .write_trailer = seg_write_trailer, .deinit = seg_free, .check_bitstream = seg_check_bitstream, .priv_class = &seg_class, }; #endif #if CONFIG_STREAM_SEGMENT_MUXER static const AVClass sseg_class = { .class_name = "stream_segment muxer", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVOutputFormat ff_stream_segment_muxer = { .name = "stream_segment,ssegment", .long_name = NULL_IF_CONFIG_SMALL("streaming segment muxer"), .priv_data_size = sizeof(SegmentContext), .flags = AVFMT_NOFILE, .init = seg_init, .write_header = seg_write_header, .write_packet = seg_write_packet, .write_trailer = seg_write_trailer, .deinit = seg_free, .check_bitstream = seg_check_bitstream, .priv_class = &sseg_class, }; #endif
endlessm/chromium-browser
third_party/ffmpeg/libavformat/segment.c
C
bsd-3-clause
43,151
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2249, 1010, 15604, 3347, 14479, 2080, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 21461, 8737, 13910, 1012, 1008, 1008, 21461, 8737, 13910, 2003, 2489, 4007, 1025, 2017, 2064, 2417, 2923, 3089,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package base import ( "container/list" "encoding/json" "fmt" "html/template" "runtime" "strings" "time" "golang.org/x/net/html/charset" "golang.org/x/text/transform" "github.com/gogits/chardet" "github.com/pecastro/gogs/modules/setting" ) func Safe(raw string) template.HTML { return template.HTML(raw) } func Str2html(raw string) template.HTML { return template.HTML(Sanitizer.Sanitize(raw)) } func Range(l int) []int { return make([]int, l) } func List(l *list.List) chan interface{} { e := l.Front() c := make(chan interface{}) go func() { for e != nil { c <- e.Value e = e.Next() } close(c) }() return c } func Sha1(str string) string { return EncodeSha1(str) } func ShortSha(sha1 string) string { if len(sha1) == 40 { return sha1[:10] } return sha1 } func DetectEncoding(content []byte) (string, error) { detector := chardet.NewTextDetector() result, err := detector.DetectBest(content) if result.Charset != "UTF-8" && len(setting.AnsiCharset) > 0 { return setting.AnsiCharset, err } return result.Charset, err } func ToUtf8WithErr(content []byte) (error, string) { charsetLabel, err := DetectEncoding(content) if err != nil { return err, "" } if charsetLabel == "UTF-8" { return nil, string(content) } encoding, _ := charset.Lookup(charsetLabel) if encoding == nil { return fmt.Errorf("unknow char decoder %s", charsetLabel), string(content) } result, n, err := transform.String(encoding.NewDecoder(), string(content)) // If there is an error, we concatenate the nicely decoded part and the // original left over. This way we won't loose data. if err != nil { result = result + string(content[n:]) } return err, result } func ToUtf8(content string) string { _, res := ToUtf8WithErr([]byte(content)) return res } // RenderCommitMessage renders commit message with XSS-safe and special links. func RenderCommitMessage(msg, urlPrefix string) template.HTML { return template.HTML(string(RenderIssueIndexPattern([]byte(template.HTMLEscapeString(msg)), urlPrefix))) } var mailDomains = map[string]string{ "gmail.com": "gmail.com", } var TemplateFuncs template.FuncMap = map[string]interface{}{ "GoVer": func() string { return strings.Title(runtime.Version()) }, "AppName": func() string { return setting.AppName }, "AppSubUrl": func() string { return setting.AppSubUrl }, "AppVer": func() string { return setting.AppVer }, "AppDomain": func() string { return setting.Domain }, "DisableGravatar": func() bool { return setting.DisableGravatar }, "LoadTimes": func(startTime time.Time) string { return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms" }, "AvatarLink": AvatarLink, "Safe": Safe, "Str2html": Str2html, "TimeSince": TimeSince, "RawTimeSince": RawTimeSince, "FileSize": FileSize, "Subtract": Subtract, "Add": func(a, b int) int { return a + b }, "ActionIcon": ActionIcon, "DateFmtLong": func(t time.Time) string { return t.Format(time.RFC1123Z) }, "DateFmtShort": func(t time.Time) string { return t.Format("Jan 02, 2006") }, "List": List, "Mail2Domain": func(mail string) string { if !strings.Contains(mail, "@") { return "try.gogs.io" } suffix := strings.SplitN(mail, "@", 2)[1] domain, ok := mailDomains[suffix] if !ok { return "mail." + suffix } return domain }, "SubStr": func(str string, start, length int) string { if len(str) == 0 { return "" } end := start + length if length == -1 { end = len(str) } if len(str) < end { return str } return str[start:end] }, "DiffTypeToStr": DiffTypeToStr, "DiffLineTypeToStr": DiffLineTypeToStr, "Sha1": Sha1, "ShortSha": ShortSha, "Md5": EncodeMd5, "ActionContent2Commits": ActionContent2Commits, "Oauth2Icon": Oauth2Icon, "Oauth2Name": Oauth2Name, "ToUtf8": ToUtf8, "EscapePound": func(str string) string { return strings.Replace(strings.Replace(str, "%", "%25", -1), "#", "%23", -1) }, "RenderCommitMessage": RenderCommitMessage, } type Actioner interface { GetOpType() int GetActUserName() string GetActEmail() string GetRepoUserName() string GetRepoName() string GetRepoPath() string GetRepoLink() string GetBranch() string GetContent() string GetCreate() time.Time GetIssueInfos() []string } // ActionIcon accepts a int that represents action operation type // and returns a icon class name. func ActionIcon(opType int) string { switch opType { case 1, 8: // Create, transfer repository. return "repo" case 5, 9: // Commit repository. return "git-commit" case 6: // Create issue. return "issue-opened" case 10: // Comment issue. return "comment" default: return "invalid type" } } type PushCommit struct { Sha1 string Message string AuthorEmail string AuthorName string } type PushCommits struct { Len int Commits []*PushCommit CompareUrl string } func ActionContent2Commits(act Actioner) *PushCommits { var push *PushCommits if err := json.Unmarshal([]byte(act.GetContent()), &push); err != nil { return nil } return push } func DiffTypeToStr(diffType int) string { diffTypes := map[int]string{ 1: "add", 2: "modify", 3: "del", } return diffTypes[diffType] } func DiffLineTypeToStr(diffType int) string { switch diffType { case 2: return "add" case 3: return "del" case 4: return "tag" } return "same" } func Oauth2Icon(t int) string { switch t { case 1: return "fa-github-square" case 2: return "fa-google-plus-square" case 3: return "fa-twitter-square" case 4: return "fa-qq" case 5: return "fa-weibo" } return "" } func Oauth2Name(t int) string { switch t { case 1: return "GitHub" case 2: return "Google+" case 3: return "Twitter" case 4: return "腾讯 QQ" case 5: return "Weibo" } return "" }
pecastro/gogs
modules/base/template.go
GO
mit
6,062
[ 30522, 1013, 1013, 9385, 2297, 1996, 2175, 5620, 6048, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1037, 10210, 1011, 2806, 1013, 1013, 6105, 2008, 2064, 2022, 2179, 1999, 1996, 6105, 5371, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# encoding: utf-8 Factory.define :user do |u| u.nickname "One user" u.email "mail@email.com" u.locale "fr" u.password "password" u.password_confirmation "password" u.posts_count 12 end Factory.define :invited, :class => "user" do |u| u.nickname "Invited member" u.email "newmail@email.com" u.locale "fr" u.password "password" u.password_confirmation "password" u.posts_count 0 end Factory.define :creator, :class => "user" do |u| u.nickname "creator" u.email "email@email.com" u.locale "fr" u.password "password" u.password_confirmation "password" u.posts_count 12 end Factory.define :post do |p| p.creator Factory.build(:creator) p.body "Some content" end Factory.define :topic do |t| t.title "One topic" t.creator "creator" t.user Factory.build(:creator) t.after_build do |tp| tp.posts.push(Factory.build(:post)) end end Factory.define :member do |s| s.nickname "Member" end Factory.define:smiley do |s| s.code "doc" s.added_by "One user" s.height 20 s.width 20 s.image File.open(Rails.root.join("image.jpg")) end
chatgris/blabbr
spec/factories.rb
Ruby
mit
1,577
[ 30522, 1001, 17181, 1024, 21183, 2546, 1011, 1022, 4713, 1012, 9375, 1024, 5310, 2079, 1064, 1057, 1064, 1057, 1012, 8367, 1000, 2028, 5310, 1000, 1057, 1012, 10373, 1000, 5653, 1030, 10373, 1012, 4012, 1000, 1057, 1012, 2334, 2063, 1000, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#ifndef __UI_EDITOR_INTROSPECTION_PROPERTY__ #define __UI_EDITOR_INTROSPECTION_PROPERTY__ #include "ValueProperty.h" namespace DAVA { class UIControl; class UIDataBindingComponent; class UILayoutSourceRectComponent; } class IntrospectionProperty : public ValueProperty { public: IntrospectionProperty(DAVA::BaseObject* object, const DAVA::Type* componentType, const DAVA::String& name, const DAVA::Reflection& ref, const IntrospectionProperty* prototypeProperty); protected: IntrospectionProperty(DAVA::BaseObject* object, DAVA::int32 componentType, const DAVA::String& name, const DAVA::Reflection& ref, const IntrospectionProperty* prototypeProperty); virtual ~IntrospectionProperty(); public: static IntrospectionProperty* Create(DAVA::BaseObject* object, const DAVA::Type* componentType, const DAVA::String& name, const DAVA::Reflection& ref, const IntrospectionProperty* sourceProperty); void Accept(PropertyVisitor* visitor) override; DAVA::uint32 GetFlags() const override; ePropertyType GetType() const override; const EnumMap* GetEnumMap() const override; const DAVA::String& GetDisplayName() const override; DAVA::Any GetValue() const override; DAVA::Any GetSerializationValue() const override; DAVA::BaseObject* GetBaseObject() const { return object; } void DisableResetFeature(); void ResetValue() override; void Refresh(DAVA::int32 refreshFlags) override; bool IsBindable() const override; bool IsBound() const override; DAVA::int32 GetBindingUpdateMode() const override; DAVA::String GetBindingExpression() const override; void SetBindingExpression(const DAVA::String& expression, DAVA::int32 bindingUpdateMode) override; DAVA::String GetFullFieldName() const; bool HasError() const override; DAVA::String GetErrorString() const override; bool IsReadOnly() const override; void ComponentWithPropertyWasInstalled(); void ComponentWithPropertyWasUninstalled(); protected: void SetBindingExpressionImpl(const DAVA::String& expression, DAVA::int32 bindingUpdateMode); void ResetBindingExpression(); void ApplyValue(const DAVA::Any& value) override; DAVA::BaseObject* object = nullptr; DAVA::Reflection reflection; DAVA::int32 flags; DAVA::String bindingExpression; DAVA::int32 bindingMode = 0; bool forceReadOnly = false; private: DAVA::UIControl* GetLinkedControl(); bool bindable = false; bool bound = false; const DAVA::Type* componentType = nullptr; DAVA::RefPtr<DAVA::UIDataBindingComponent> bindingComponent; void SetLayoutSourceRectValue(const DAVA::Any& value); DAVA::RefPtr<DAVA::UILayoutSourceRectComponent> sourceRectComponent; }; #endif //__UI_EDITOR_INTROSPECTION_PROPERTY__
dava/dava.engine
Programs/QuickEd/Classes/Model/ControlProperties/IntrospectionProperty.h
C
bsd-3-clause
2,801
[ 30522, 1001, 2065, 13629, 2546, 1035, 1035, 21318, 1035, 3559, 1035, 17174, 13102, 18491, 1035, 3200, 1035, 1035, 1001, 9375, 1035, 1035, 21318, 1035, 3559, 1035, 17174, 13102, 18491, 1035, 3200, 1035, 1035, 1001, 2421, 1000, 3643, 21572, 4...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2014 Google Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. package internal // This file implements a network dialer that limits the number of concurrent connections. // It is only used for API calls. import ( "log" "net" "runtime" "sync" "time" ) var limitSem = make(chan int, 100) // TODO(dsymonds): Use environment variable. func limitRelease() { // non-blocking select { case <-limitSem: default: // This should not normally happen. log.Print("appengine: unbalanced limitSem release!") } } func limitDial(network, addr string) (net.Conn, error) { limitSem <- 1 // Dial with a timeout in case the API host is MIA. // The connection should normally be very fast. conn, err := net.DialTimeout(network, addr, 500*time.Millisecond) if err != nil { limitRelease() return nil, err } lc := &limitConn{Conn: conn} runtime.SetFinalizer(lc, (*limitConn).Close) // shouldn't usually be required return lc, nil } type limitConn struct { close sync.Once net.Conn } func (lc *limitConn) Close() error { defer lc.close.Do(func() { limitRelease() runtime.SetFinalizer(lc, nil) }) return lc.Conn.Close() }
ae6rt/decap
web/vendor/google.golang.org/appengine/internal/net.go
GO
mit
1,236
[ 30522, 1013, 1013, 9385, 2297, 8224, 4297, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1996, 15895, 1016, 1012, 1014, 1013, 1013, 6105, 2008, 2064, 2022, 2179, 1999, 1996, 6105, 5371, 1012, 74...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- title: drive layout: category section-type: category --- ## Category
masachi/masachi.github.io
categories/drive.html
HTML
mit
73
[ 30522, 1011, 1011, 1011, 2516, 1024, 3298, 9621, 1024, 4696, 2930, 1011, 2828, 1024, 4696, 1011, 1011, 1011, 1001, 1001, 4696, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Rails helper module for navigation module Fabl module Assets module NavHelper # Breadcrumbs def breadcrumbs breadcrumbs = [] if breadcrumbs.empty? breadcrumbs << link_to(views["breadcrumbs"]["title"], views["breadcrumbs"]["url"]) breadcrumbs << link_to('CLIO', bobcat_breadcrumb_root) end end # Login link and icon def login(params={}) (current_user) ? link_to_logout(params) : link_to_login(params) end # Link to logout def link_to_logout(params={}) icon_tag(:logout) + link_to("Log-out #{username}", logout_url(params), class: "logout") end # Link to login def link_to_login(params={}) icon_tag(:login) + link_to("Login", login_url(params), class: "login") end def username if current_user.respond_to?(:firstname) && current_user.firstname.present? current_user.firstname else current_user.username end end def bobcat_breadcrumb_root "#{bobcat_breadcrumb_base_url}/#{bobcat_breadcrumb_alias}" end # Ensure there is always a bobcat url to show even if it isn't set anywhere def bobcat_breadcrumb_base_url (current_institution.bobcat_url) ? current_institution.bobcat_url : default_institution.bobcat_url rescue default_institution.bobcat_url end # Ensure there is always an alias to show even if it isn't set anywhere def bobcat_breadcrumb_alias (current_institution.bobcat_alias) ? current_institution.bobcat_alias : views["dir"] rescue views["dir"] end end end end
cul/fabl-assets
app/helpers/fabl/assets/nav_helper.rb
Ruby
mit
1,708
[ 30522, 1001, 15168, 2393, 2121, 30524, 7045, 11336, 6583, 2615, 16001, 4842, 1001, 7852, 26775, 25438, 2015, 13366, 7852, 26775, 25438, 2015, 7852, 26775, 25438, 2015, 1027, 1031, 1033, 2065, 7852, 26775, 25438, 2015, 1012, 4064, 1029, 7852, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
function ChangeTo(to) { if (to == "text") { $('#admincommentlinks').ghide(); $('#admincomment').gshow(); resize('admincomment'); var buttons = document.getElementsByName('admincommentbutton'); for (var i = 0; i < buttons.length; i++) { buttons[i].setAttribute('onclick',"ChangeTo('links'); return false;"); } } else if (to == "links") { ajax.post("ajax.php?action=preview","form", function(response) { $('#admincommentlinks').raw().innerHTML = response; $('#admincomment').ghide(); $('#admincommentlinks').gshow(); var buttons = document.getElementsByName('admincommentbutton'); for (var i = 0; i < buttons.length; i++) { buttons[i].setAttribute('onclick',"ChangeTo('text'); return false;"); } }) } } function UncheckIfDisabled(checkbox) { if (checkbox.disabled) { checkbox.checked = false; } } function AlterParanoia() { // Required Ratio is almost deducible from downloaded, the count of seeding and the count of snatched // we will "warn" the user by automatically checking the required ratio box when they are // revealing that information elsewhere if (!$('input[name=p_ratio]').raw()) { return; } var showDownload = $('input[name=p_downloaded]').raw().checked || ($('input[name=p_uploaded]').raw().checked && $('input[name=p_ratio]').raw().checked); if (($('input[name=p_seeding_c]').raw().checked) && ($('input[name=p_snatched_c]').raw().checked) && showDownload) { $('input[type=checkbox][name=p_requiredratio]').raw().checked = true; $('input[type=checkbox][name=p_requiredratio]').raw().disabled = true; } else { $('input[type=checkbox][name=p_requiredratio]').raw().disabled = false; } $('input[name=p_torrentcomments_l]').raw().disabled = !$('input[name=p_torrentcomments_c]').raw().checked; $('input[name=p_collagecontribs_l]').raw().disabled = !$('input[name=p_collagecontribs_c]').raw().checked; $('input[name=p_requestsfilled_list]').raw().disabled = !($('input[name=p_requestsfilled_count]').raw().checked && $('input[name=p_requestsfilled_bounty]').raw().checked); $('input[name=p_requestsvoted_list]').raw().disabled = !($('input[name=p_requestsvoted_count]').raw().checked && $('input[name=p_requestsvoted_bounty]').raw().checked); $('input[name=p_uploads_l]').raw().disabled = !$('input[name=p_uploads_c]').raw().checked; $('input[name=p_uniquegroups_l]').raw().disabled = !$('input[name=p_uniquegroups_c]').raw().checked; $('input[name=p_perfectflacs_l]').raw().disabled = !$('input[name=p_perfectflacs_c]').raw().checked; $('input[name=p_seeding_l]').raw().disabled = !$('input[name=p_seeding_c]').raw().checked; $('input[name=p_leeching_l]').raw().disabled = !$('input[name=p_leeching_c]').raw().checked; $('input[name=p_snatched_l]').raw().disabled = !$('input[name=p_snatched_c]').raw().checked; UncheckIfDisabled($('input[name=p_torrentcomments_l]').raw()); UncheckIfDisabled($('input[name=p_collagecontribs_l]').raw()); UncheckIfDisabled($('input[name=p_requestsfilled_list]').raw()); UncheckIfDisabled($('input[name=p_requestsvoted_list]').raw()); UncheckIfDisabled($('input[name=p_uploads_l]').raw()); UncheckIfDisabled($('input[name=p_uniquegroups_l]').raw()); UncheckIfDisabled($('input[name=p_perfectflacs_l]').raw()); UncheckIfDisabled($('input[name=p_seeding_l]').raw()); UncheckIfDisabled($('input[name=p_leeching_l]').raw()); UncheckIfDisabled($('input[name=p_snatched_l]').raw()); // unique groups, "Perfect" FLACs and artists added are deducible from the list of uploads if ($('input[name=p_uploads_l]').raw().checked) { $('input[name=p_uniquegroups_c]').raw().checked = true; $('input[name=p_uniquegroups_l]').raw().checked = true; $('input[name=p_uniquegroups_c]').raw().disabled = true; $('input[name=p_uniquegroups_l]').raw().disabled = true; $('input[name=p_perfectflacs_c]').raw().checked = true; $('input[name=p_perfectflacs_l]').raw().checked = true; $('input[name=p_perfectflacs_c]').raw().disabled = true; $('input[name=p_perfectflacs_l]').raw().disabled = true; $('input[type=checkbox][name=p_artistsadded]').raw().checked = true; $('input[type=checkbox][name=p_artistsadded]').raw().disabled = true; } else { $('input[name=p_uniquegroups_c]').raw().disabled = false; $('input[name=p_uniquegroups_l]').raw().checked = false; $('input[name=p_uniquegroups_l]').raw().disabled = true; $('input[name=p_perfectflacs_c]').raw().disabled = false; $('input[type=checkbox][name=p_artistsadded]').raw().disabled = false; } if ($('input[name=p_collagecontribs_l]').raw().checked) { $('input[name=p_collages_c]').raw().disabled = true; $('input[name=p_collages_l]').raw().disabled = true; $('input[name=p_collages_c]').raw().checked = true; $('input[name=p_collages_l]').raw().checked = true; } else { $('input[name=p_collages_c]').raw().disabled = false; $('input[name=p_collages_l]').raw().disabled = !$('input[name=p_collages_c]').raw().checked; UncheckIfDisabled($('input[name=p_collages_l]').raw()); } } function ParanoiaReset(checkbox, drops) { var selects = $('select'); for (var i = 0; i < selects.results(); i++) { if (selects.raw(i).name.match(/^p_/)) { if (drops == 0) { selects.raw(i).selectedIndex = 0; } else if (drops == 1) { selects.raw(i).selectedIndex = selects.raw(i).options.length - 2; } else if (drops == 2) { selects.raw(i).selectedIndex = selects.raw(i).options.length - 1; } AlterParanoia(); } } var checkboxes = $(':checkbox'); for (var i = 0; i < checkboxes.results(); i++) { if (checkboxes.raw(i).name.match(/^p_/) && (checkboxes.raw(i).name != 'p_lastseen')) { if (checkbox == 3) { checkboxes.raw(i).checked = !(checkboxes.raw(i).name.match(/_list$/) || checkboxes.raw(i).name.match(/_l$/)); } else { checkboxes.raw(i).checked = checkbox; } AlterParanoia(); } } } function ParanoiaResetOff() { ParanoiaReset(true, 0); } function ParanoiaResetStats() { ParanoiaReset(3, 0); $('input[name=p_collages_l]').raw().checked = false; } function ParanoiaResetOn() { ParanoiaReset(false, 0); $('input[name=p_collages_c]').raw().checked = false; $('input[name=p_collages_l]').raw().checked = false; } addDOMLoadEvent(AlterParanoia); function ToggleWarningAdjust(selector) { if (selector.options[selector.selectedIndex].value == '---') { $('#ReduceWarningTR').gshow(); $('#ReduceWarning').raw().disabled = false; } else { $('#ReduceWarningTR').ghide(); $('#ReduceWarning').raw().disabled = true; } } addDOMLoadEvent(ToggleIdenticons); function ToggleIdenticons() { var disableAvatars = $('#disableavatars'); if (disableAvatars.size()) { var selected = disableAvatars[0].selectedIndex; if (selected == 2 || selected == 3) { $('#identicons').gshow(); } else { $('#identicons').ghide(); } } } function userform_submit() { if ($('#resetpasskey').is(':checked')) { if (!confirm('Are you sure you want to reset your passkey?')) { return false; } } return formVal(); } function togglePassKey(key) { if ($('#passkey').raw().innerHTML == 'View') { $('#passkey').raw().innerHTML = key; } else { $('#passkey').raw().innerHTML = 'View'; } } function commStats(userid) { $('.user_commstats').html('Loading...'); ajax.get('ajax.php?action=community_stats&userid=' + userid, function(JSONresponse) { var response = JSON.parse(JSONresponse) || false; if (!response || response.status == 'failure') { $('.user_commstats').html('An error occurred'); return; } displayCommStats(response.response); }); } function displayCommStats(stats) { var baseid = '#user_commstats_'; for (x in stats) { if (stats[x] === false) { continue; } switch (x) { case 'leeching': $(baseid + x).html(stats[x]); break; case 'seeding': $(baseid + x).html(stats[x]); break; case 'downloaded': $(baseid + x).html(stats[x]); break; case 'snatched': $(baseid + x).html(stats[x]); break; case 'usnatched': $(baseid + x).html('(' + stats[x] + ')'); break; case 'udownloaded': $(baseid + x).html('(' + stats[x] + ')'); break; case 'seedingperc': $(baseid + x).html('(' + stats[x] + '%)'); break; } } } $(document).ready(function() { $("#random_password").click(function() { var length = 15, charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=<>?", password = ""; for (var i = 0, n = charset.length; i < length; ++i) { password += charset.charAt(Math.floor(Math.random() * n)); } $('#change_password').val(password); }); });
tisnats/tisnats.com
static/functions/user.js
JavaScript
apache-2.0
8,556
[ 30522, 3853, 2689, 3406, 1006, 2000, 1007, 1063, 2065, 1006, 2000, 1027, 1027, 1000, 3793, 1000, 1007, 1063, 1002, 1006, 1005, 1001, 4748, 10020, 9006, 3672, 13767, 2015, 1005, 1007, 1012, 1043, 26100, 1006, 1007, 1025, 1002, 1006, 1005, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Dipyrena wilsonia F.Phil. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Verbenaceae/Dipyrena/Dipyrena wilsonia/README.md
Markdown
apache-2.0
175
[ 30522, 1001, 16510, 16363, 2532, 4267, 2401, 1042, 1012, 6316, 1012, 2427, 1001, 1001, 1001, 1001, 3570, 3970, 1001, 1001, 1001, 1001, 2429, 2000, 2248, 3269, 3415, 5950, 1001, 1001, 1001, 1001, 2405, 1999, 19701, 1001, 1001, 1001, 1001, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * issue.h * * Created on: 2015年3月16日 * Author: Fifi Lyu */ #ifndef ISSUE_H_ #define ISSUE_H_ #include <linux/stddef.h> // 0 off // 1 on #define DEBUG 0 #define HTTP_PORT 80 #define WL_HOST "/etc/http_whitelist/host" #define WL_NETWORK "/etc/http_whitelist/network" #define MODOUBLE_NAME "http_whitelist" #define LICENSE "Dual MIT/GPL"; #define AUTHOR "Fifi Lyu"; #define DESCRIPTION "HTTP Whitelist"; #endif /* ISSUE_H_ */
millken/module-http-whitelist
issue.h
C
mit
452
[ 30522, 1013, 1008, 1008, 3277, 1012, 1044, 1008, 1008, 2580, 2006, 1024, 2325, 1840, 1017, 1872, 2385, 1864, 1008, 3166, 1024, 10882, 8873, 1048, 10513, 1008, 1013, 1001, 2065, 13629, 2546, 3277, 1035, 1044, 1035, 1001, 9375, 3277, 1035, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
namespace FleetManagmentSystem.Web.ViewModels.Manufacture { using System.Web.Mvc; using FleetManagmentSystem.Web.Infrastructure.Mapping; using FleetManagmentSystem.Web.ViewModels.Base; using FleetManagmentSystem.Models; public class ManufactureDropDownListViewModel : BaseViewModel, IMapFrom<Manufacture> { [HiddenInput(DisplayValue = false)] public int Id { get; set; } public string Name { get; set; } } }
gdavidkov/Fleet-management-system
Source/FleetManagmentSystem/Web/FleetManagmentSystem.Web/ViewModels/Manufacture/ManufactureDropDownListViewModel.cs
C#
mit
467
[ 30522, 3415, 15327, 4170, 24805, 21693, 11187, 27268, 6633, 1012, 4773, 1012, 3193, 5302, 9247, 2015, 1012, 9922, 1063, 2478, 2291, 1012, 4773, 1012, 19842, 2278, 1025, 2478, 4170, 24805, 21693, 11187, 27268, 6633, 1012, 30524, 4170, 24805, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
Gem.find_files('slackbot_frd/**/*.rb').each do |path| require path.gsub(/\.rb$/, '') unless path =~ /bot.*cli/ end
FreedomBen/slackbot_frd
lib/slackbot_frd.rb
Ruby
mit
117
[ 30522, 17070, 1012, 2424, 1035, 6764, 1006, 1005, 19840, 18384, 1035, 10424, 2094, 1013, 1008, 1008, 1013, 1008, 1012, 21144, 1005, 1007, 1012, 2169, 2079, 1064, 4130, 1064, 5478, 4130, 1012, 28177, 12083, 1006, 1013, 1032, 1012, 21144, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// RUN: %clang_cc1 -verify %s -std=c++11 // A function that is explicitly defaulted shall struct A { // -- be a special member function, A(int) = default; // expected-error {{only special member functions may be defaulted}} // -- have the same declared function type as if it had been implicitly // declared void operator=(const A &) = default; // expected-error {{must return 'A &'}} A(...) = default; // expected-error {{cannot be variadic}} A(const A &, ...) = default; // expected-error {{cannot be variadic}} // (except for possibly differing ref-qualifiers A &operator=(A &&) & = default; // and except that in the case of a copy constructor or copy assignment // operator, the parameter type may be "reference to non-const T") A(A &) = default; A &operator=(A &) = default; // -- not have default arguments A(double = 0.0) = default; // expected-error {{cannot have default arguments}} A(const A & = 0) = default; // expected-error {{cannot have default arguments}} };
cd80/UtilizedLLVM
tools/clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.default/p1.cpp
C++
unlicense
1,025
[ 30522, 1013, 1013, 2448, 1024, 1003, 6338, 2290, 1035, 10507, 2487, 1011, 20410, 1003, 1055, 1011, 2358, 2094, 1027, 1039, 1009, 1009, 2340, 1013, 1013, 1037, 3853, 2008, 2003, 12045, 17265, 4618, 2358, 6820, 6593, 1037, 1063, 1013, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* ResidualVM - A 3D game interpreter * * ResidualVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #ifndef GRIM_MODEL_COMPONENT_H #define GRIM_MODEL_COMPONENT_H #include "engines/grim/costume/component.h" namespace Grim { class Model; class AnimManager; class ModelComponent : public Component { public: ModelComponent(Component *parent, int parentID, const char *filename, Component *prevComponent, tag32 tag); ~ModelComponent(); void init(); void setKey(int val); void animate(); void reset(); void resetColormap(); void setMatrix(const Math::Matrix4 &matrix) { _matrix = matrix; }; void restoreState(SaveGame *state); void translateObject(bool reset); static void translateObject(ModelNode *node, bool reset); AnimManager *getAnimManager() const; ModelNode *getHierarchy() { return _hier; } int getNumNodes(); Model *getModel() { return _obj; } void draw(); void getBoundingBox(int *x1, int *y1, int *x2, int *y2); protected: Model *_obj; ModelNode *_hier; Math::Matrix4 _matrix; AnimManager *_animation; Component *_prevComp; }; } // end of namespace Grim #endif
clone2727/residual
engines/grim/costume/model_component.h
C
gpl-2.0
1,970
[ 30522, 1013, 1008, 21961, 2615, 2213, 1011, 1037, 7605, 2208, 19555, 1008, 1008, 21961, 2615, 2213, 2003, 1996, 3423, 3200, 1997, 2049, 9797, 1010, 3005, 3415, 1008, 2024, 2205, 3365, 2000, 2862, 2182, 1012, 3531, 6523, 2000, 1996, 9385, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
'use strict'; /** * Module dependencies. */ var fs = require('fs'), http = require('http'), https = require('https'), express = require('express'), morgan = require('morgan'), logger = require('./logger'), bodyParser = require('body-parser'), session = require('express-session'), compress = require('compression'), methodOverride = require('method-override'), cookieParser = require('cookie-parser'), helmet = require('helmet'), passport = require('passport'), mongoStore = require('connect-mongo')({ session: session }), flash = require('connect-flash'), config = require('./config'), consolidate = require('consolidate'), path = require('path'); // multer = require('multer') module.exports = function(db) { // Initialize express app var app = express(); // Globbing model files config.getGlobbedFiles('./models/**/*.js').forEach(function(modelPath) { require(path.resolve(modelPath)); }); // Setting application local variables app.locals.title = config.app.title; app.locals.description = config.app.description; app.locals.keywords = config.app.keywords; // app.locals.facebookAppId = config.facebook.clientID; if (!fs.existsSync(config.uploadDir)){ fs.mkdirSync(config.uploadDir); fs.mkdirSync(config.uploadDirTmp); } // Passing the request url to environment locals app.use(function(req, res, next) { res.locals.url = req.protocol + '://' + req.headers.host + req.url; next(); }); // Should be placed before express.static app.use(compress({ filter: function(req, res) { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, level: 9 })); // Showing stack errors app.set('showStackError', true); // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); // TODO: Review this. // Set views path and view engine app.set('view engine', 'server.view.html'); // TODO: Review this. // app.set('views', './app/views'); // TODO: Review this. app.set('views', './templates'); // TODO: Review this. // Enable logger (morgan) app.use(morgan(logger.getLogFormat(), logger.getLogOptions())); // Environment dependent middleware if (process.env.NODE_ENV === 'development') { // Disable views cache app.set('view cache', false); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } // app.use(multer({ // dest: './uploads/', // limits: { // files: 10, // fileSize: 2, // parts: 10 // }, // rename: function(fieldname, filename) { // return filename.replace(/\W+/g, '-').toLowerCase(); // }, // onFileUploadStart: function(file) { // console.log(file.fieldname + ' is starting ...'); // }, // onFileUploadComplete: function(file) { // console.log(file.fieldname + ' uploaded to ' + file.path); // }, // onError: function(error, next) { // console.log(error); // next(error); // }, // onFileSizeLimit: function(file) { // console.log('Failed: ', file.originalname); // fs.unlink('./' + file.path); // delete the partially written file // }, // onFilesLimit: function() { // console.log('Crossed file limit!'); // } // })); // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); // CookieParser should be above session app.use(cookieParser()); // Express MongoDB session storage app.use(session({ saveUninitialized: true, resave: true, secret: config.sessionSecret, store: new mongoStore({ db: db.connection.db, collection: config.sessionCollection }), cookie: config.sessionCookie, name: config.sessionName })); // use passport session app.use(passport.initialize()); app.use(passport.session()); // connect flash for flash messages app.use(flash()); // Use helmet to secure Express headers app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.ienoopen()); app.disable('x-powered-by'); // Setting the app router and static folder app.use(express.static(path.resolve(config.root))); // Globbing routing files config.getGlobbedFiles('./routers/**/*.js').forEach(function(routePath) { require(path.resolve(routePath))(app); }); // require('../routers/routes'); // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use(function(err, req, res, next) { // If the error object doesn't exists if (!err) return next(); // Log it console.error(err.stack); res.status(500).json({ error: err.stack }); }); // Assume 404 since no middleware responded app.use(function(req, res) { res.status(404).json({ msg: 'Not Found' }); }); if (process.env.NODE_ENV === 'secure') { // Load SSL key and certificate var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'); var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'); // Create HTTPS Server var httpsServer = https.createServer({ key: privateKey, cert: certificate }, app); // Return HTTPS server instance return httpsServer; } // Return Express server instance return app; };
mauroBus/element
server/config/express.js
JavaScript
apache-2.0
5,566
[ 30522, 1005, 2224, 9384, 1005, 1025, 1013, 1008, 1008, 1008, 11336, 12530, 15266, 1012, 1008, 1013, 13075, 1042, 2015, 1027, 5478, 1006, 1005, 1042, 2015, 1005, 1007, 1010, 8299, 1027, 5478, 1006, 1005, 8299, 1005, 1007, 1010, 16770, 1027, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
jsonp({"cep":"30730230","logradouro":"Rua Padre N\u00f3brega","bairro":"Minas Brasil","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/30730230.jsonp.js
JavaScript
cc0-1.0
149
[ 30522, 1046, 3385, 2361, 1006, 1063, 1000, 8292, 2361, 1000, 1024, 1000, 24559, 14142, 21926, 2692, 1000, 1010, 1000, 8833, 12173, 8162, 2080, 1000, 1024, 1000, 21766, 2050, 28612, 1050, 1032, 1057, 8889, 2546, 2509, 13578, 3654, 1000, 1010...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php use app\components\Common; use app\rbac\OwnPostRule; use yii\helpers\Html; ?> <article class="post hentry"> <header class="post-header"> <h3 class="content-title">Blog post title</h3> <div class="blog-entry-meta"> <div class="blog-entry-meta-date"> <i class="fa fa-clock-o"></i> <span class="blog-entry-meta-date-month"> <?= date('F', $model->updated_at); ?> </span> <span class="blog-entry-meta-date-day"> <?= date('d', $model->updated_at); ?>, </span> <span class="blog-entry-meta-date-year"> <?= date('Y', $model->updated_at); ?> </span> </div> <div class="blog-entry-meta-author"> <i class="fa fa-user"></i> <a href="#" class="blog-entry-meta-author"><?= $model->author->username ?></a> </div> <div class="blog-entry-meta-tags"> <i class="fa fa-tags"></i> <a href="#">Web Design</a>, <a href="#">Branding</a> </div> <div class="blog-entry-meta-comments"> <i class="fa fa-comments"></i> <a href="#" class="blog-entry-meta-comments">4 comments</a> </div> <?php $canEdit = \Yii::$app->user->can('updatePost') || \Yii::$app->user->can('updateOwnPost',['post'=>$model]); $canDelete = \Yii::$app->user->can('deletePost') || \Yii::$app->user->can('deleteOwnPost',['post'=>$model]); if($canEdit || $canDelete) { ?> <div class="blog-entry-admin"> <?php if($canEdit) { $options = [ 'title' => Yii::t('yii', 'Update'), 'aria-label' => Yii::t('yii', 'Update'), 'data-pjax' => '0', ]; echo Html::a('<i class="fa fa-edit"></i>', '/post/update/'.$model->id, $options); } if($canDelete) { $options = [ 'title' => Yii::t('yii', 'Delete'), 'aria-label' => Yii::t('yii', 'Delete'), 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-method' => 'post', 'data-pjax' => '0', 'class' => 'blog-entry-admin-delete', ]; echo Html::a('<i class="fa fa-remove"></i>', '/post/delete/'.$model->id, $options); } ?> </div> <?php } ?> </div> </header> <div class="post-content"> <p> <?= Common::substrBoundary($model->content, 600); ?> </p> </div> <footer class="post-footer"> <a class="btn-small btn-color">Read More</a> </footer> </article> <div class="blog-divider"></div>
svd222/blog
themes/lamar/views/post/_post.php
PHP
bsd-3-clause
2,933
[ 30522, 1026, 1029, 25718, 2224, 10439, 1032, 6177, 1032, 2691, 1025, 2224, 10439, 1032, 21144, 6305, 1032, 2219, 19894, 6820, 2571, 1025, 2224, 12316, 2072, 1032, 2393, 2545, 1032, 16129, 1025, 1029, 1028, 1026, 3720, 2465, 1027, 1000, 2695...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function int(x) { return x|0; } function pointer(src, offset, length) { offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, offset, length); } else { return new src.constructor(src.buffer, offset); } } var uint8 = 0; var int32 = 1; function calloc(n, type) { switch (type) { case uint8: return new Uint8Array(n); case int32: return new Int32Array(n); } throw new Error("calloc failed."); } function realloc(src, newSize) { var ret = new src.constructor(newSize); ret.set(src); return ret; } function copy(dst, src, offset) { dst.set(src, offset||0); }
mohayonao/libogg.js
include/stdlib.js
JavaScript
mit
777
[ 30522, 13075, 19701, 1027, 19701, 1025, 3853, 2053, 2361, 1006, 1007, 1063, 1065, 3853, 2025, 1035, 7528, 1006, 1007, 1063, 5466, 2047, 7561, 1006, 1000, 2025, 7528, 1012, 1000, 1007, 1025, 1065, 3853, 20014, 1006, 1060, 1007, 1063, 2709, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
class dximagetransform_microsoft_crblinds_1 { constructor() { // short bands () {get} {set} this.bands = undefined; // int Capabilities () {get} this.Capabilities = undefined; // string Direction () {get} {set} this.Direction = undefined; // float Duration () {get} {set} this.Duration = undefined; // float Progress () {get} {set} this.Progress = undefined; // float StepResolution () {get} this.StepResolution = undefined; } } module.exports = dximagetransform_microsoft_crblinds_1;
mrpapercut/wscript
testfiles/COMobjects/JSclasses/DXImageTransform.Microsoft.CrBlinds.1.js
JavaScript
mit
598
[ 30522, 2465, 1040, 9048, 26860, 6494, 3619, 14192, 1035, 7513, 1035, 13675, 16558, 22254, 2015, 1035, 1015, 1063, 9570, 2953, 1006, 1007, 1063, 1013, 1013, 2460, 4996, 1006, 1007, 1063, 2131, 1065, 1063, 2275, 1065, 2023, 1012, 4996, 1027, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
///<reference path="app.js" /> define(['Dexie', 'Dexie.Observable', './console'], function (Dexie, DexieObservable, console) { // Declare Dexie instance and explicitely apply the addon: var db = new Dexie("appdb2", { addons: [DexieObservable] }); // Define database schema db.version(1).stores({ contacts: '++id,first,last' }); // Populate ground data db.on('populate', function () { console.log("Populating data first time"); // Populate a contact db.contacts.add({ first: 'Arnold', last: 'Fitzgerald' }); }); // Open database db.open(); return db; });
YuriSolovyov/Dexie.js
samples/requirejs-with-addons/scripts/db.js
JavaScript
apache-2.0
643
[ 30522, 1013, 1013, 1013, 1026, 4431, 4130, 1027, 1000, 10439, 1012, 1046, 2015, 1000, 1013, 1028, 9375, 1006, 1031, 1005, 20647, 2666, 1005, 1010, 1005, 20647, 2666, 1012, 27885, 8043, 12423, 1005, 1010, 1005, 1012, 1013, 10122, 1005, 1033,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/************************************************************************************* Extended WPF Toolkit Copyright (C) 2007-2013 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at http://xceed.com/wpf_toolkit Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using Xceed.Wpf.Toolkit.Primitives; using System.Windows.Media; using Xceed.Wpf.Toolkit.Core.Utilities; namespace Xceed.Wpf.Toolkit { [TemplatePart( Name = PART_DropDownButton, Type = typeof( ToggleButton ) )] [TemplatePart( Name = PART_ContentPresenter, Type = typeof( ContentPresenter ) )] [TemplatePart( Name = PART_Popup, Type = typeof( Popup ) )] public class DropDownButton : ContentControl, ICommandSource { private const string PART_DropDownButton = "PART_DropDownButton"; private const string PART_ContentPresenter = "PART_ContentPresenter"; private const string PART_Popup = "PART_Popup"; #region Members private ContentPresenter _contentPresenter; private Popup _popup; #endregion #region Constructors static DropDownButton() { DefaultStyleKeyProperty.OverrideMetadata( typeof( DropDownButton ), new FrameworkPropertyMetadata( typeof( DropDownButton ) ) ); } public DropDownButton() { Keyboard.AddKeyDownHandler( this, OnKeyDown ); Mouse.AddPreviewMouseDownOutsideCapturedElementHandler( this, OnMouseDownOutsideCapturedElement ); } #endregion //Constructors #region Properties private System.Windows.Controls.Primitives.ButtonBase _button; protected System.Windows.Controls.Primitives.ButtonBase Button { get { return _button; } set { if( _button != null ) _button.Click -= DropDownButton_Click; _button = value; if( _button != null ) _button.Click += DropDownButton_Click; } } #region DropDownContent public static readonly DependencyProperty DropDownContentProperty = DependencyProperty.Register( "DropDownContent", typeof( object ), typeof( DropDownButton ), new UIPropertyMetadata( null, OnDropDownContentChanged ) ); public object DropDownContent { get { return ( object )GetValue( DropDownContentProperty ); } set { SetValue( DropDownContentProperty, value ); } } private static void OnDropDownContentChanged( DependencyObject o, DependencyPropertyChangedEventArgs e ) { DropDownButton dropDownButton = o as DropDownButton; if( dropDownButton != null ) dropDownButton.OnDropDownContentChanged( ( object )e.OldValue, ( object )e.NewValue ); } protected virtual void OnDropDownContentChanged( object oldValue, object newValue ) { // TODO: Add your property changed side-effects. Descendants can override as well. } #endregion //DropDownContent #region IsOpen public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register( "IsOpen", typeof( bool ), typeof( DropDownButton ), new UIPropertyMetadata( false, OnIsOpenChanged ) ); public bool IsOpen { get { return ( bool )GetValue( IsOpenProperty ); } set { SetValue( IsOpenProperty, value ); } } private static void OnIsOpenChanged( DependencyObject o, DependencyPropertyChangedEventArgs e ) { DropDownButton dropDownButton = o as DropDownButton; if( dropDownButton != null ) dropDownButton.OnIsOpenChanged( ( bool )e.OldValue, ( bool )e.NewValue ); } protected virtual void OnIsOpenChanged( bool oldValue, bool newValue ) { if( newValue ) RaiseRoutedEvent( DropDownButton.OpenedEvent ); else RaiseRoutedEvent( DropDownButton.ClosedEvent ); } #endregion //IsOpen #endregion //Properties #region Base Class Overrides public override void OnApplyTemplate() { base.OnApplyTemplate(); Button = GetTemplateChild( PART_DropDownButton ) as ToggleButton; _contentPresenter = GetTemplateChild( PART_ContentPresenter ) as ContentPresenter; if( _popup != null ) _popup.Opened -= Popup_Opened; _popup = GetTemplateChild( PART_Popup ) as Popup; if( _popup != null ) _popup.Opened += Popup_Opened; } #endregion //Base Class Overrides #region Events public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent( "Click", RoutingStrategy.Bubble, typeof( RoutedEventHandler ), typeof( DropDownButton ) ); public event RoutedEventHandler Click { add { AddHandler( ClickEvent, value ); } remove { RemoveHandler( ClickEvent, value ); } } public static readonly RoutedEvent OpenedEvent = EventManager.RegisterRoutedEvent( "Opened", RoutingStrategy.Bubble, typeof( RoutedEventHandler ), typeof( DropDownButton ) ); public event RoutedEventHandler Opened { add { AddHandler( OpenedEvent, value ); } remove { RemoveHandler( OpenedEvent, value ); } } public static readonly RoutedEvent ClosedEvent = EventManager.RegisterRoutedEvent( "Closed", RoutingStrategy.Bubble, typeof( RoutedEventHandler ), typeof( DropDownButton ) ); public event RoutedEventHandler Closed { add { AddHandler( ClosedEvent, value ); } remove { RemoveHandler( ClosedEvent, value ); } } #endregion //Events #region Event Handlers private void OnKeyDown( object sender, KeyEventArgs e ) { if( !IsOpen ) { if( KeyboardUtilities.IsKeyModifyingPopupState( e ) ) { IsOpen = true; // ContentPresenter items will get focus in Popup_Opened(). e.Handled = true; } } else { if( KeyboardUtilities.IsKeyModifyingPopupState( e ) ) { CloseDropDown( true ); e.Handled = true; } else if( e.Key == Key.Escape ) { CloseDropDown( true ); e.Handled = true; } } } private void OnMouseDownOutsideCapturedElement( object sender, MouseButtonEventArgs e ) { CloseDropDown( false ); } private void DropDownButton_Click( object sender, RoutedEventArgs e ) { OnClick(); } void CanExecuteChanged( object sender, EventArgs e ) { CanExecuteChanged(); } private void Popup_Opened( object sender, EventArgs e ) { // Set the focus on the content of the ContentPresenter. if( _contentPresenter != null ) { _contentPresenter.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); } } #endregion //Event Handlers #region Methods private void CanExecuteChanged() { if( Command != null ) { RoutedCommand command = Command as RoutedCommand; // If a RoutedCommand. if( command != null ) IsEnabled = command.CanExecute( CommandParameter, CommandTarget ) ? true : false; // If a not RoutedCommand. else IsEnabled = Command.CanExecute( CommandParameter ) ? true : false; } } /// <summary> /// Closes the drop down. /// </summary> private void CloseDropDown( bool isFocusOnButton ) { if( IsOpen ) IsOpen = false; ReleaseMouseCapture(); if( isFocusOnButton ) Button.Focus(); } protected virtual void OnClick() { RaiseRoutedEvent( DropDownButton.ClickEvent ); RaiseCommand(); } /// <summary> /// Raises routed events. /// </summary> private void RaiseRoutedEvent( RoutedEvent routedEvent ) { RoutedEventArgs args = new RoutedEventArgs( routedEvent, this ); RaiseEvent( args ); } /// <summary> /// Raises the command's Execute event. /// </summary> private void RaiseCommand() { if( Command != null ) { RoutedCommand routedCommand = Command as RoutedCommand; if( routedCommand == null ) ( ( ICommand )Command ).Execute( CommandParameter ); else routedCommand.Execute( CommandParameter, CommandTarget ); } } /// <summary> /// Unhooks a command from the Command property. /// </summary> /// <param name="oldCommand">The old command.</param> /// <param name="newCommand">The new command.</param> private void UnhookCommand( ICommand oldCommand, ICommand newCommand ) { EventHandler handler = CanExecuteChanged; oldCommand.CanExecuteChanged -= handler; } /// <summary> /// Hooks up a command to the CanExecuteChnaged event handler. /// </summary> /// <param name="oldCommand">The old command.</param> /// <param name="newCommand">The new command.</param> private void HookUpCommand( ICommand oldCommand, ICommand newCommand ) { EventHandler handler = new EventHandler( CanExecuteChanged ); canExecuteChangedHandler = handler; if( newCommand != null ) newCommand.CanExecuteChanged += canExecuteChangedHandler; } #endregion //Methods #region ICommandSource Members // Keeps a copy of the CanExecuteChnaged handler so it doesn't get garbage collected. private EventHandler canExecuteChangedHandler; #region Command public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( "Command", typeof( ICommand ), typeof( DropDownButton ), new PropertyMetadata( ( ICommand )null, OnCommandChanged ) ); [TypeConverter( typeof( CommandConverter ) )] public ICommand Command { get { return ( ICommand )GetValue( CommandProperty ); } set { SetValue( CommandProperty, value ); } } private static void OnCommandChanged( DependencyObject d, DependencyPropertyChangedEventArgs e ) { DropDownButton dropDownButton = d as DropDownButton; if( dropDownButton != null ) dropDownButton.OnCommandChanged( ( ICommand )e.OldValue, ( ICommand )e.NewValue ); } protected virtual void OnCommandChanged( ICommand oldValue, ICommand newValue ) { // If old command is not null, then we need to remove the handlers. if( oldValue != null ) UnhookCommand( oldValue, newValue ); HookUpCommand( oldValue, newValue ); CanExecuteChanged(); //may need to call this when changing the command parameter or target. } #endregion //Command public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register( "CommandParameter", typeof( object ), typeof( DropDownButton ), new PropertyMetadata( null ) ); public object CommandParameter { get { return GetValue( CommandParameterProperty ); } set { SetValue( CommandParameterProperty, value ); } } public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register( "CommandTarget", typeof( IInputElement ), typeof( DropDownButton ), new PropertyMetadata( null ) ); public IInputElement CommandTarget { get { return ( IInputElement )GetValue( CommandTargetProperty ); } set { SetValue( CommandTargetProperty, value ); } } #endregion //ICommandSource Members } }
BenInCOSprings/WpfDockingWindowsApplicationTemplate
wpftoolkit-110921/Main/Source/ExtendedWPFToolkitSolution_35/Src/Xceed.Wpf.Toolkit/DropDownButton/Implementation/DropDownButton.cs
C#
mit
12,391
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package seborama.demo2.kafka.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonIgnoreProperties(ignoreUnknown = true) public class Order { private String id; private boolean fulfilled; private boolean dispatched; private boolean completed; public void setId(String id) { this.id = id; } public void setFulfilled(Boolean fulfilled) { this.fulfilled = fulfilled; } public void setDispatched(Boolean dispatched) { this.dispatched = dispatched; } public void setCompleted(Boolean completed) { this.completed = completed; } public String getId() { return id; } public Boolean getFulfilled() { return fulfilled; } public Boolean getDispatched() { return dispatched; } public Boolean getCompleted() { return completed; } @Override public String toString() { return "Order{" + "id='" + id + '\'' + ", fulfilled=" + fulfilled + ", dispatched=" + dispatched + ", completed=" + completed + '}'; } }
seborama/demo1-kafka
src/main/java/seborama/demo2/kafka/model/Order.java
Java
apache-2.0
1,265
[ 30522, 7427, 7367, 12821, 8067, 1012, 9703, 2475, 1012, 10556, 24316, 2050, 1012, 2944, 1025, 12324, 4012, 1012, 5514, 2595, 19968, 1012, 4027, 1012, 5754, 17287, 3508, 1012, 1046, 3385, 23773, 5686, 21572, 4842, 7368, 1025, 12324, 4012, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* -*- C++ -*- */ #ifndef _COALESCEHEAP_H_ #define _COALESCEHEAP_H_ /* Heap Layers: An Extensible Memory Allocation Infrastructure Copyright (C) 2000-2003 by Emery Berger http://www.cs.umass.edu/~emery emery@cs.umass.edu This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <assert.h> #include "heaplayers.h" /** * @class CoalesceHeap * @brief Applies splitting and coalescing. * @see CoalesceableHeap * @see RequireCoalesceable */ namespace HL { template <class super> class CoalesceHeap : public super { public: inline void * malloc (const size_t sz) { void * ptr = super::malloc (sz); if (ptr != NULL) { super::markInUse (ptr); void * splitPiece = split (ptr, sz); if (splitPiece != NULL) { super::markFree (splitPiece); super::free (splitPiece); } } return ptr; } inline void free (void * ptr) { // Try to coalesce this object with its predecessor & successor. if ((super::getNext(super::getPrev(ptr)) != ptr) || (super::getPrev(super::getNext(ptr)) != ptr)) { // We're done with this object. super::free (ptr); return; } assert (super::getPrev(super::getNext(ptr)) == ptr); // Try to coalesce with the previous object.. void * prev = super::getPrev(ptr); void * next = super::getNext (ptr); assert (prev != ptr); if (super::isPrevFree(ptr)) { assert (super::isFree(prev)); super::remove (prev); coalesce (prev, ptr); ptr = prev; } if (super::isFree(next)) { super::remove (next); coalesce (ptr, next); } super::markFree (ptr); // We're done with this object. super::free (ptr); } private: // Combine the first object with the second. inline static void coalesce (void * first, const void * second) { // A few sanity checks first. assert (super::getNext(first) == second); assert (super::getPrev(second) == first); // Now coalesce. size_t newSize = ((size_t) second - (size_t) first) + super::getSize(second); super::setSize (first, newSize); setPrevSize (super::getNext(first), newSize); } // Split an object if it is big enough. inline static void * split (void * obj, const size_t requestedSize) { assert (super::getSize(obj) >= requestedSize); // We split aggressively (for now; this could be a parameter). const size_t actualSize = super::getSize(obj); if (actualSize - requestedSize >= sizeof(typename super::Header) + sizeof(double)) { // Split the object. super::setSize(obj, requestedSize); void * splitPiece = (char *) obj + requestedSize + sizeof(typename super::Header); super::makeObject ((void *) super::getHeader(splitPiece), requestedSize, actualSize - requestedSize - sizeof(typename super::Header)); assert (!super::isFree(splitPiece)); // Now that we have a new successor (splitPiece), we need to // mark obj as in use. (super::getHeader(splitPiece))->markPrevInUse(); assert (super::getSize(splitPiece) >= sizeof(double)); assert (super::getSize(obj) >= requestedSize); return splitPiece; } else { return NULL; } } }; }; #endif
andrei14vl/cubrid
src/heaplayers/coalesceheap.h
C
gpl-3.0
3,871
[ 30522, 1013, 1008, 1011, 1008, 1011, 1039, 1009, 1009, 1011, 1008, 1011, 1008, 1013, 1001, 2065, 13629, 2546, 1035, 5317, 2229, 3401, 20192, 2361, 1035, 1044, 1035, 1001, 9375, 1035, 5317, 2229, 3401, 20192, 2361, 1035, 1044, 1035, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
//<TunynetCopyright> //-------------------------------------------------------------- //<copyright>拓宇网络科技有限公司 2005-2012</copyright> //<version>V0.5</verion> //<createdate>2012-05-24</createdate> //<author>libsh</author> //<email>libsh@tunynet.com</email> //<log date="2012-05-24">创建</log> //-------------------------------------------------------------- //</TunynetCopyright> using System; using System.Collections.Generic; using System.IO; using System.Linq; using Tunynet.Common.Repositories; using Tunynet.Events; using Tunynet.Repositories; using System.Text; namespace Tunynet.Common { /// <summary> /// 敏感词业务逻辑类 /// </summary> public class SensitiveWordService { private ISensitiveWordRepository sensitiveWordRepository; private IRepository<SensitiveWordType> sensitiveWordTypeRepository; /// <summary> /// 构造器方法 /// </summary> public SensitiveWordService() : this(new SensitiveWordRepository(), new SensitiveWordTypeRepository()) { } /// <summary> /// 构造器方法 /// </summary> /// <param name="sensitiveWordRepository">敏感词数据访问</param> /// <param name="sensitiveWordTypeRepository">敏感词类型数据访问</param> public SensitiveWordService(ISensitiveWordRepository sensitiveWordRepository, IRepository<SensitiveWordType> sensitiveWordTypeRepository) { this.sensitiveWordRepository = sensitiveWordRepository; this.sensitiveWordTypeRepository = sensitiveWordTypeRepository; } #region SensitiveWord /// <summary> /// 添加敏感词 /// </summary> /// <param name="sensitiveWord">敏感词实体类型</param> public int Create(SensitiveWord sensitiveWord) { EventBus<SensitiveWord>.Instance().OnBefore(sensitiveWord, new CommonEventArgs(EventOperationType.Instance().Create())); int judge = sensitiveWordRepository.Create(sensitiveWord); EventBus<SensitiveWord>.Instance().OnAfter(sensitiveWord, new CommonEventArgs(EventOperationType.Instance().Create())); return judge; } /// <summary> /// 添加敏感词 /// </summary> /// <param name="stream">敏感词文件流</param> /// <param name="typeId">敏感词类型Id</param> public void BatchCreate(Stream stream, int? typeId) { List<string> words = new List<string>(); StreamReader sr = new StreamReader(stream, System.Text.Encoding.Default); string word = string.Empty; while (!string.IsNullOrEmpty(word = sr.ReadLine())) { if (string.IsNullOrEmpty(word)) continue; words.Add(word); } BatchCreate(words, typeId); } /// <summary> /// 添加敏感词 /// </summary> /// <param name="words">敏感词集合</param> /// <param name="typeId">敏感词类型Id</param> public void BatchCreate(IList<string> words, int? typeId) { if (words == null) { return; } words = words.Distinct().ToList(); List<SensitiveWord> sensitiveWords = new List<SensitiveWord>(); foreach (string word in words) { SensitiveWord sensitiveWord = SensitiveWord.New(); if (word.Contains("=")) { string[] parts = word.Split('='); if (parts.Count() == 2) { sensitiveWord.Word = parts[0]; sensitiveWord.Replacement = parts[1]; } } else { sensitiveWord.Word = word; sensitiveWord.Replacement = "*"; } if (typeId.HasValue) { sensitiveWord.TypeId = typeId.Value; } sensitiveWords.Add(sensitiveWord); } EventBus<SensitiveWord>.Instance().OnBatchBefore(sensitiveWords, new CommonEventArgs(EventOperationType.Instance().Create())); sensitiveWordRepository.BatchInsert(sensitiveWords); EventBus<SensitiveWord>.Instance().OnBatchAfter(sensitiveWords, new CommonEventArgs(EventOperationType.Instance().Create())); } /// <summary> /// 更新敏感词 /// </summary> /// <param name="sensitiveWord">待更新敏感词</param> /// <returns></returns> public int Update(SensitiveWord sensitiveWord) { EventBus<SensitiveWord>.Instance().OnBefore(sensitiveWord, new CommonEventArgs(EventOperationType.Instance().Update())); int judge = sensitiveWordRepository.Update(sensitiveWord); EventBus<SensitiveWord>.Instance().OnAfter(sensitiveWord, new CommonEventArgs(EventOperationType.Instance().Update())); return judge; } /// <summary> /// 删除敏感词 /// </summary> /// <param name="id">敏感词Id</param> public void Delete(int id) { SensitiveWord word = sensitiveWordRepository.Get(id); EventBus<SensitiveWord>.Instance().OnBefore(word, new CommonEventArgs(EventOperationType.Instance().Update())); sensitiveWordRepository.Delete(word); EventBus<SensitiveWord>.Instance().OnBefore(word, new CommonEventArgs(EventOperationType.Instance().Update())); } /// <summary> /// 获取敏感词实体 /// </summary> /// <param name="id">敏感词Id</param> public SensitiveWord Get(int id) { return sensitiveWordRepository.Get(id); } /// <summary> /// 获取敏感词集合(后台用) /// </summary> /// <param name="keyword">敏感词关键字</param> /// <param name="typeId">分类Id</param> public IEnumerable<SensitiveWord> Gets(string keyword = "", int? typeId = null) { return sensitiveWordRepository.GetSensitiveWords(keyword, typeId); } /// <summary> /// 导出敏感词 /// </summary> /// <returns></returns> public byte[] Export() { IEnumerable<SensitiveWord> sensitiveWords = Gets(); if (sensitiveWords == null) return null; byte[] bytes = new byte[65535]; int i = 0; foreach (SensitiveWord sensitiveWord in sensitiveWords) { foreach (byte b in System.Text.ASCIIEncoding.Default.GetBytes(sensitiveWord.Word + "=" + sensitiveWord.Replacement + "\r\n")) { bytes[i] = b; i++; } } return bytes; } #endregion #region SensitiveWordType /// <summary> /// 创建敏感词类型 /// </summary> public void CreateType(SensitiveWordType type) { sensitiveWordTypeRepository.Insert(type); } /// <summary> /// 删除敏感词类型 /// </summary> /// <param name="typeId">敏感词类型Id</param> public void DeleteType(object typeId) { sensitiveWordTypeRepository.DeleteByEntityId(typeId); } /// <summary> /// 更新敏感词类型 /// </summary> /// <param name="type">敏感词类型实体</param> public void UpdateType(SensitiveWordType type) { sensitiveWordTypeRepository.Update(type); } /// <summary> /// 获取敏感词类型集合 /// </summary> public IEnumerable<SensitiveWordType> GetAllSensitiveWordTypes() { return sensitiveWordTypeRepository.GetAll(); } /// <summary> /// 获取敏感词类型集合 /// </summary> /// <param name="id">敏感词类型Id</param> public SensitiveWordType GetSensitiveWordType(int id) { return sensitiveWordTypeRepository.Get(id); } #endregion } }
yesan/Spacebuilder
BusinessComponents/Common/SensitiveWord/SensitiveWordService.cs
C#
lgpl-3.0
8,458
[ 30522, 1013, 1013, 1026, 27112, 9654, 13535, 7361, 12541, 18743, 1028, 1013, 1013, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
-- luainspect.init - core LuaInspect source analysis. -- -- This module is a bit more high level than luainspect.ast. It deals more with -- interpretation/inference of semantics of an AST. It also uses luainspect.globals, -- which does the basic semantic interpretation of globals/locals. -- -- (c) 2010 David Manura, MIT License. local M = {} -- This is the API version. It is an ISO8601 date expressed as a fraction. M.APIVERSION = 0.20100805 local LA = require "luainspect.ast" local LD = require "luainspect.dump" local LG = require "luainspect.globals" local LS = require "luainspect.signatures" local T = require "luainspect.types" local COMPAT = require "luainspect.compat_env" --! require 'luainspect.typecheck' (context) local ENABLE_RETURN_ANALYSIS = true local DETECT_DEADCODE = false -- may require more validation (false positives) -- Functional forms of Lua operators. -- Note: variable names like _1 are intentional. These affect debug info and -- will display in any error messages. local ops = {} ops['add'] = function(_1,_2) return _1+_2 end ops['sub'] = function(_1,_2) return _1-_2 end ops['mul'] = function(_1,_2) return _1*_2 end ops['div'] = function(_1,_2) return _1/_2 end ops['mod'] = function(_1,_2) return _1%_2 end ops['pow'] = function(_1,_2) return _1^_2 end ops['concat'] = function(_1,_2) return _1.._2 end ops['eq'] = function(_1,_2) return _1==_2 end ops['lt'] = function(_1,_2) return _1<_2 end ops['le'] = function(_1,_2) return _1<=_2 end ops['and'] = function(_1,_2) return _1 and _2 end ops['or'] = function(_1,_2) return _1 or _2 end ops['not'] = function(_1) return not _1 end ops['len'] = function(_1) return #_1 end ops['unm'] = function(_1) return -_1 end -- Performs binary operation. Supports types. local function dobinop(opid, a, b) if (a == T.number or b == T.number) and (a == T.number or type(a) == 'number' ) and (b == T.number or type(b) == 'number' ) then if opid == 'eq' or opid == 'lt' or opid == 'le' then return T.boolean elseif opid == 'concat' then return T.string else return T.number end elseif (a == T.string or b == T.string) and (a == T.string or type(a) == 'string' ) and (b == T.string or type(b) == 'string' ) then if opid == 'concat' or opid == 'and' or opid == 'or' then return T.string elseif opid == 'eq' or opid == 'lt' or opid == 'le' then return T.boolean else return T.number end elseif (a == T.boolean or b == T.boolean) and (a == T.boolean or type(a) == 'boolean' ) and (b == T.boolean or type(b) == 'boolean' ) then if opid == 'eq' or opid == 'and' or opid == 'or' then return T.boolean else error('invalid operation on booleans: ' .. opid, 0) end elseif T.istype[a] or T.istype[b] then return T.universal else return ops[opid](a, b) end end -- Performs unary operation. Supports types. local function dounop(opid, a) if opid == 'not' then if T.istype[a] then return T.boolean else return ops[opid](a) end elseif a == T.number then if opid == 'unm' then return T.number else -- 'len' error('invalid operation on number: ' .. opid, 0) end elseif a == T.string then return T.number elseif a == T.boolean then error('invalid operation on boolean: ' .. opid, 0) elseif T.istype[a] then return nil, 'unknown' else return ops[opid](a) end end -- Like info in debug.getinfo but inferred by static analysis. -- object -> {fpos=fpos, source="@" .. source, fast=ast, tokenlist=tokenlist} -- Careful: value may reference key (affects pre-5.2 which lacks emphemerons). -- See also ast.nocollect. M.debuginfo = setmetatable({}, {__mode='v'}) -- Modules loaded via require_inspect. -- module name string -> {return value, AST node} -- note: AST node is maintained to prevent nocollect fields in ast being collected. -- note: not a weak table. M.package_loaded = {} -- Stringifies interpreted value for debugging. -- CATEGORY: debug local function debugvalue(ast) local s if ast then s = ast.value ~= T.universal and 'known:' .. tostring(ast.value) or 'unknown' else s = '?' end return s end -- Reads contents of text file in path, in binary mode. -- On error, returns nil and error message. local function readfile(path) local fh, err = io.open(path, 'rb') if fh then local data; data, err = fh:read'*a' if data then return data end end return nil, err end -- Similar to string.gsub but with plain replacement (similar to option in string.match) -- http://lua-users.org/lists/lua-l/2002-04/msg00118.html -- CATEGORY: utility/string local function plain_gsub(s, pattern, repl) repl = repl:gsub('(%%)', '%%%%') return s:gsub(pattern, repl) end -- Infer name of variable or literal that AST node represents. -- This is for debugging messages. local function infer_name(ast) if ast == nil then return nil elseif ast.tag == 'Id' then return "'"..ast[1].."'" elseif ast.tag == 'Number' then return 'number' elseif ast.tag == 'String' then return 'string' elseif ast.tag == 'True' then return 'true' elseif ast.tag == 'False' then return 'false' elseif ast.tag == 'Nil' then return 'nil' else return nil end end --[[ This is like `pcall` but any error string returned does not contain the "chunknamem:currentline: " prefix (based on luaL_where) if the error occurred in the current file. This avoids error messages in user code (f) being reported as being inside this module if this module calls user code. Also, local variable names _1, _2, etc. in error message are replaced with names inferred (if any) from corresponding AST nodes in list `asts` (note: nil's in asts skip replacement). --]] local _prefix local _clean local function pzcall(f, asts, ...) _prefix = _prefix or select(2, pcall(function() error'' end)):gsub(':%d+: *$', '') -- note: specific to current file. _clean = _clean or function(asts, ok, ...) if ok then return true, ... else local err = ... if type(err) == 'string' then if err:sub(1,#_prefix) == _prefix then local more = err:match('^:%d+: *(.*)', #_prefix+1) if more then err = more err = err:gsub([[local '_(%d+)']], function(name) return infer_name(asts[tonumber(name)]) end) end end end return ok, err end end return _clean(asts, pcall(f, ...)) end -- Loads source code of given module name. -- Returns code followed by path. -- note: will also search in the directory `spath` and its parents. -- This should preferrably be an absolute path or it might not work correctly. -- It must be slash terminated. -- CATEGORY: utility/package local function load_module_source(name, spath) -- Append parent directories to list of paths to search. local package_path = package.path local ppath = spath repeat package_path = package_path .. ';' .. ppath .. '?.lua;' .. ppath .. '?/init.lua' local nsub ppath, nsub = ppath:gsub('[^\\/]+[\\/]$', '') until nsub == 0 for spec in package_path:gmatch'[^;]+' do local testpath = plain_gsub(spec, '%?', (name:gsub('%.', '/'))) local src, err_ = readfile(testpath) if src then return src, testpath end end return nil end -- Clears global state. -- This includes cached inspected modules. function M.clear_cache() for k,v in pairs(M.package_loaded) do M.package_loaded[k] = nil end end -- Gets all keywords related to AST `ast`, where `top_ast` is the root of `ast` -- and `src` is source code of `top_ast` -- Related keywords are defined as all keywords directly associated with block containing node -- `ast`. Furthermore, break statements are related to containing loop statements, -- and return statements are related to containing function statement (if any). -- function declaration syntactic sugar is handled specially too to ensure the 'function' keyword -- is highlighted even though it may be outside of the `Function AST. -- -- Returns token list or nil if not applicable. Returned `ast` is AST containing related keywords. -- CATEGORY: keyword comprehension local iskeystat = {Do=true, While=true, Repeat=true, If=true, Fornum=true, Forin=true, Local=true, Localrec=true, Return=true, Break=true, Function=true, Set=true -- note: Set for `function name` } local isloop = {While=true, Repeat=true, Fornum=true, Forin=true} local isblock = {Do=true, While=true, Repeat=true, If=true, Fornum=true, Forin=true, Function=true} function M.related_keywords(ast, top_ast, tokenlist, src) -- Expand or contract AST for certain contained statements. local more if ast.tag == 'Return' then -- if `return` selected, that consider containing function selected (if any) if not ast.parent then LA.mark_parents(top_ast) end local ancestor_ast = ast.parent while ancestor_ast ~= nil and ancestor_ast.tag ~= 'Function' do ancestor_ast = ancestor_ast.parent end if ancestor_ast then ast = ancestor_ast end -- but only change if exists elseif ast.tag == 'Break' then -- if `break` selected, that consider containing loop selected if not ast.parent then LA.mark_parents(top_ast) end local ancestor_ast = ast.parent while ancestor_ast ~= nil and not isloop[ancestor_ast.tag] do ancestor_ast = ancestor_ast.parent end ast = ancestor_ast elseif ast.tag == 'Set' then local val1_ast = ast[2][1] if val1_ast.tag == 'Function' then local token = tokenlist[LA.ast_idx_range_in_tokenlist(tokenlist, ast)] if token.tag == 'Keyword' and token[1] == 'function' then -- function with syntactic sugar `function f` ast = ast[2][1] -- select `Function node else more = true end else more = true end elseif ast.tag == 'Localrec' and ast[2][1].tag == 'Function' then -- if `local function f` selected, which becomes a `Localrec, consider `Function node. ast = ast[2][1] --IMPROVE: only contract ast if `function` part of `local function` is selected. else more = true end if more then -- not yet handled -- Consider containing block. if not ast.parent then LA.mark_parents(top_ast) end local ancestor_ast = ast while ancestor_ast ~= top_ast and not isblock[ancestor_ast.tag] do ancestor_ast = ancestor_ast.parent end ast = ancestor_ast end -- keywords in statement/block. if iskeystat[ast.tag] then local keywords = {} for i=1,#tokenlist do local token = tokenlist[i] if token.ast == ast and token.tag == 'Keyword' then keywords[#keywords+1] = token end end -- Expand keywords for certaining statements. if ast.tag == 'Function' then -- if `Function, also select 'function' and 'return' keywords local function f(ast) for _,cast in ipairs(ast) do if type(cast) == 'table' then if cast.tag == 'Return' then local token = tokenlist[LA.ast_idx_range_in_tokenlist(tokenlist, cast)] keywords[#keywords+1] = token elseif cast.tag ~= 'Function' then f(cast) end end end end f(ast) if not ast.parent then LA.mark_parents(top_ast) end local grand_ast = ast.parent.parent if grand_ast.tag == 'Set' then local token = tokenlist[LA.ast_idx_range_in_tokenlist(tokenlist, grand_ast)] if token.tag == 'Keyword' and token[1] == 'function' then keywords[#keywords+1] = token end elseif grand_ast.tag == 'Localrec' then local tidx = LA.ast_idx_range_in_tokenlist(tokenlist, grand_ast) repeat tidx = tidx + 1 until not tokenlist[tidx] or (tokenlist[tidx].tag == 'Keyword' and tokenlist[tidx][1] == 'function') local token = tokenlist[tidx] keywords[#keywords+1] = token end elseif isloop[ast.tag] then -- if loop, also select 'break' keywords local function f(ast) for _,cast in ipairs(ast) do if type(cast) == 'table' then if cast.tag == 'Break' then local tidx = LA.ast_idx_range_in_tokenlist(tokenlist, cast) keywords[#keywords+1] = tokenlist[tidx] elseif not isloop[cast.tag] then f(cast) end end end end f(ast) end return keywords, ast end return nil, ast end -- Mark tokenlist (top_ast/tokenlist/src) with keywordid AST attributes. -- All keywords related to each other have the same keyword ID integer. -- NOTE: This is not done/undone by inspect/uninspect. -- CATEGORY: keyword comprehension function M.mark_related_keywords(top_ast, tokenlist, src) local id = 0 local idof = {} for _, token in ipairs(tokenlist) do if token.tag == 'Keyword' and not idof[token] then id = id + 1 local match_ast = LA.smallest_ast_containing_range(top_ast, tokenlist, token.fpos, token.lpos) local ktokenlist = M.related_keywords(match_ast, top_ast, tokenlist, src) if ktokenlist then for _, ktoken in ipairs(ktokenlist) do ktoken.keywordid = id idof[ktoken] = true end end -- note: related_keywords may return a keyword set not containing given keyword. end end end -- function for t[k] local function tindex(_1, _2) return _1[_2] end local unescape = {['d'] = '.'} -- Sets known value on ast to v if ast not pegged. -- CATEGORY: utility function for infer_values. local function set_value(ast, v) if not ast.isvaluepegged then ast.value = v end end local function known(o) return not T.istype[o] end local function unknown(o) return T.istype[o] end -- CATEGORY: utility function for infer_values. local function tastnewindex(t_ast, k_ast, v_ast) if known(t_ast.value) and known(k_ast.value) and known(v_ast.value) then local _1, _2, _3 = t_ast.value, k_ast.value, v_ast.value if _1[_2] ~= nil and _3 ~= _1[_2] then -- multiple values return T.universal else _1[_2] = _3 return _3 end else return T.universal end end -- Gets expected number of parameters for function (min, max) values. -- In case of vararg, max is unknown and set to nil. local function function_param_range(ast) local names_ast = ast[1] if #names_ast >= 1 and names_ast[#names_ast].tag == 'Dots' then return #names_ast-1, nil else return #names_ast, #names_ast end end -- Gets number of arguments to function call: (min, max) range. -- In case of trailing vararg or function call, max is unknown and set to nil. local function call_arg_range(ast) if ast.tag == 'Invoke' then if #ast >= 3 and (ast[#ast].tag == 'Dots' or ast[#ast].tag == 'Call' or ast[#ast].tag == 'Invoke') then return #ast-2, nil else return #ast-1, #ast-1 end else if #ast >= 2 and (ast[#ast].tag == 'Dots' or ast[#ast].tag == 'Call' or ast[#ast].tag == 'Invoke') then return #ast-2, nil else return #ast-1, #ast-1 end end end -- Reports warning. List of strings. local function warn(report, ...) report('warning: ' .. table.concat({...}, ' ')) end -- Reports status messages. List of strings. local function status(report, ...) report('status: ' .. table.concat({...}, ' ')) end -- unique value used to detect require loops (A require B require A) local REQUIRE_SENTINEL = function() end -- Gets single return value of chunk ast. Assumes ast is inspected. local function chunk_return_value(ast) local vinfo if ENABLE_RETURN_ANALYSIS then local info = M.debuginfo[ast.value] local retvals = info and info.retvals if retvals then vinfo = retvals[1] else vinfo = T.universal end else if ast[#ast] and ast[#ast].tag == 'Return' and ast[#ast][1] then vinfo = ast[#ast][1] else vinfo = T.universal end end return vinfo end -- Version of require that does source analysis (inspect) on module. function M.require_inspect(name, report, spath) local plinfo = M.package_loaded[name] if plinfo == REQUIRE_SENTINEL then warn(report, "loop in require when loading " .. name) return nil end if plinfo then return plinfo[1] end status(report, 'loading:' .. name) M.package_loaded[name] = REQUIRE_SENTINEL -- avoid recursion on require loops local msrc, mpath = load_module_source(name, spath) local vinfo, mast if msrc then local err; mast, err = LA.ast_from_string(msrc, mpath) if mast then local mtokenlist = LA.ast_to_tokenlist(mast, msrc) M.inspect(mast, mtokenlist, msrc, report) vinfo = chunk_return_value(mast) else vinfo = T.error(err) warn(report, err, " ", mpath) --Q:error printing good? end else warn(report, 'module not found: ' .. name) vinfo = T.error'module not found' --IMPROVE: include search paths? end M.package_loaded[name] = {vinfo, mast} return vinfo, mast end -- Marks AST node and all children as dead (ast.isdead). local function mark_dead(ast) LA.walk(ast, function(bast) bast.isdead = true end) end -- Gets list of `Return statement ASTs in `Function (or chunk) f_ast, not including -- return's in nested functions. Also returns boolean `has_implicit` indicating -- whether function may return by exiting the function without a return statement. -- Returns that are never exected are omitted (e.g. last return is omitted in -- `function f() if x then return 1 else return 2 end return 3 end`). -- Also marks AST nodes with ast.isdead (dead-code). local function get_func_returns(f_ast) local isalwaysreturn = {} local returns = {} local function f(ast, isdead) for _,cast in ipairs(ast) do if type(cast) == 'table' then if isdead then mark_dead(cast) end -- even if DETECT_DEADCODE disabled if cast.tag ~= 'Function' and not isdead then -- skip nested functions f(cast, isdead) -- depth-first traverse end if ast.tag ~= 'If' and isalwaysreturn[cast] then isdead = true end -- subsequent statements in block never executed end end -- Code on walking up AST: propagate children to parents if ast.tag == 'Return' then returns[#returns+1] = ast isalwaysreturn[ast] = true elseif ast.tag == 'If' then if #ast%2 ~= 0 then -- has 'else' block local isreturn = true for i=2,#ast do if (i%2==0 or i==#ast) and not isalwaysreturn[ast[i]] then isreturn = nil; break end end isalwaysreturn[ast] = isreturn end else -- note: iterates not just blocks, but should be ok for i=1,#ast do if isalwaysreturn[ast[i]] then isalwaysreturn[ast] = true; break end end end end f(f_ast, false) local block_ast = f_ast.tag == 'Function' and f_ast[2] or f_ast local has_implicit = not isalwaysreturn[block_ast] return returns, has_implicit end -- temporary hack? local function valnode_normalize(valnode) if valnode then return valnode.value else return T.none end end -- Gets return value at given return argument index, given list of `Return statements. -- Return value is a superset of corresponding types in list of statements. -- Example: {`Return{1,2,3}, `Return{1,3,'z'}} would return -- 1, T.number, and T.universal for retidx 1, 2 and 3 respectively. local function get_return_value(returns, retidx) if #returns == 0 then return T.none elseif #returns == 1 then return valnode_normalize(returns[1][retidx]) else local combined_value = valnode_normalize(returns[1][retidx]) for i=2,#returns do local cur_value = valnode_normalize(returns[i][retidx]) combined_value = T.superset_types(combined_value, cur_value) if combined_value == T.universal then -- can't expand set further return combined_value end end return combined_value --TODO: handle values with possibly any number of return values, like f() end end -- Gets return values (or types) on `Function (or chunk) represented by given AST. local function get_func_return_values(f_ast) local returns, has_implicit = get_func_returns(f_ast) if has_implicit then returns[#returns+1] = {tag='Return'} end local returnvals = {n=0} for retidx=1,math.huge do local value = get_return_value(returns, retidx) if value == T.none then break end returnvals[#returnvals+1] = value returnvals.n = returnvals.n + 1 end return returnvals end -- Example: AST of `function(x) if x then return 1,2,3 else return 1,3,"z" end end` -- returns {1, T.number, T.universal}. -- Given list of values, return the first nvalues values plus the rest of the values -- as a tuple. Useful for things like -- local ok, values = valuesandtuple(1, pcall(f)) -- CATEGORY: utility function (list) local function valuesandtuple(nvalues, ...) if nvalues >= 1 then return (...), valuesandtuple(nvalues-1, select(2, ...)) else return {n=select('#', ...), ...} end end -- Infers values of variables. Also marks dead code (ast.isdead). --FIX/WARNING - this probably needs more work -- Sets top_ast.valueglobals, ast.value, ast.valueself -- CATEGORY: code interpretation function M.infer_values(top_ast, tokenlist, src, report) if not top_ast.valueglobals then top_ast.valueglobals = {} end -- infer values LA.walk(top_ast, function(ast) -- walk down if ast.tag == 'Function' then local paramlist_ast = ast[1] for i=1,#paramlist_ast do local param_ast = paramlist_ast[i] if param_ast.value == nil then param_ast.value = T.universal end end end end, function(ast) -- walk up -- process `require` statements. if ast.tag == 'Local' or ast.tag == 'Localrec' then local vars_ast, values_ast = ast[1], ast[2] local valuelist = #values_ast > 0 and values_ast[#values_ast].valuelist for i=1,#vars_ast do local var_ast, value_ast = vars_ast[i], values_ast[i] local value if value_ast then value = value_ast.value elseif valuelist then local vlidx = i - #values_ast + 1 value = valuelist.sizeunknown and vlidx > valuelist.n and T.universal or valuelist[vlidx] end set_value(var_ast, value) end elseif ast.tag == 'Set' then -- note: implementation similar to 'Local' local vars_ast, values_ast = ast[1], ast[2] local valuelist = #values_ast > 0 and values_ast[#values_ast].valuelist for i=1,#vars_ast do local var_ast, value_ast = vars_ast[i], values_ast[i] local value if value_ast then value = value_ast.value elseif valuelist then local vlidx = i - #values_ast + 1 value = valuelist.sizeunknown and vlidx > valuelist.n and T.universal or valuelist[vlidx] end if var_ast.tag == 'Index' then local t_ast, k_ast = var_ast[1], var_ast[2] if not T.istype[t_ast.value] then -- note: don't mutate types local v_ast = {value=value} local ok; ok, var_ast.value = pzcall(tastnewindex, {t_ast, k_ast, v_ast}, t_ast, k_ast, v_ast) if not ok then var_ast.value = T.error(var_ast.value) end --FIX: propagate to localdefinition? end else assert(var_ast.tag == 'Id', var_ast.tag) if var_ast.localdefinition then set_value(var_ast, value) else -- global local name = var_ast[1] top_ast.valueglobals[name] = value end end --FIX: propagate to definition or localdefinition? end elseif ast.tag == 'Fornum' then local var_ast = ast[1] set_value(var_ast, T.number) elseif ast.tag == 'Forin' then local varlist_ast, iter_ast = ast[1], ast[2] if #iter_ast == 1 and iter_ast[1].tag == 'Call' and iter_ast[1][1].value == ipairs then for i, var_ast in ipairs(varlist_ast) do if i == 1 then set_value(var_ast, T.number) -- handle the type of the value as the type of the first element -- in the table that is a parameter for ipairs elseif i == 2 then local t_ast = iter_ast[1][2] local value = T.universal if (known(t_ast.value) or T.istabletype[t_ast.value]) then local ok; ok, value = pzcall(tindex, {t_ast, {tag='Number', 1}}, t_ast.value, 1) if not ok then value = T.error(t_ast.value) end end set_value(var_ast, value) else set_value(var_ast, nil) end end elseif #iter_ast == 1 and iter_ast[1].tag == 'Call' and iter_ast[1][1].value == pairs then local t_ast = iter_ast[1][2] local value = T.universal local key if t_ast.value and (known(t_ast.value) or T.istabletype[t_ast.value]) then key = next(t_ast.value) local ok; ok, value = pzcall(tindex, {t_ast, {tag='String', key}}, t_ast.value, key) if not ok then value = T.error(t_ast.value) end end for i, var_ast in ipairs(varlist_ast) do if i == 1 then set_value(var_ast, type(key)) elseif i == 2 then set_value(var_ast, value) else set_value(var_ast, nil) end end else -- general case, unknown iterator for _, var_ast in ipairs(varlist_ast) do set_value(var_ast, T.universal) end end elseif ast.tag == 'Id' then if ast.localdefinition then local localdefinition = ast.localdefinition if not localdefinition.isset then -- IMPROVE: support non-const (isset false) too set_value(ast, localdefinition.value) end else -- global local name = ast[1] local v = top_ast.valueglobals[name] if v ~= nil then ast.value = v else local ok; ok, ast.value = pzcall(tindex, {{tag='Id', '_G'}, {tag='String', name}}, _G, name) if not ok then ast.value = T.error(ast.value) end end end elseif ast.tag == 'Index' then local t_ast, k_ast = ast[1], ast[2] if (known(t_ast.value) or T.istabletype[t_ast.value]) and known(k_ast.value) then local ok; ok, ast.value = pzcall(tindex, {t_ast, k_ast}, t_ast.value, k_ast.value) if not ok then ast.value = T.error(ast.value) end end elseif ast.tag == 'Call' or ast.tag == 'Invoke' then -- Determine function to call (infer via index if method call). local isinvoke = ast.tag == 'Invoke' if isinvoke then local t, k = ast[1].value, ast[2].value if known(t) and known(k) then local ok; ok, ast.valueself = pzcall(tindex, {ast[1], ast[2]}, t, k) if not ok then ast.valueself = T.error(ast.valueself) end end end local func; if isinvoke then func = ast.valueself else func = ast[1].value end -- Handle function call. local argvalues_concrete = true; do -- true iff all arguments known precisely. if #ast >= 2 then local firstargvalue; if isinvoke then firstargvalue = ast.valueself else firstargvalue = ast[2].value end if unknown(firstargvalue) then argvalues_concrete = false else -- test remaining args for i=3,#ast do if unknown(ast[i].value) then argvalues_concrete = false; break end end end end end local found if known(func) and argvalues_concrete then -- attempt call with concrete args -- Get list of values of arguments. local argvalues; do argvalues = {n=#ast-1}; for i=1,argvalues.n do argvalues[i] = ast[i+1].value end if isinvoke then argvalues[1] = ast.valueself end -- `self` end -- Any call to require is handled specially (source analysis). if func == require and type(argvalues[1]) == 'string' then local spath = tostring(ast.lineinfo.first):gsub('<C|','<'):match('<([^|]+)') -- a HACK? relies on AST lineinfo local val, mast = M.require_inspect(argvalues[1], report, spath:gsub('[^\\/]+$', '')) if known(val) and val ~= nil then ast.value = val found = true end -- note: on nil value, assumes analysis failed (not found). This is a heuristic only. if mast and mast.valueglobals then ast.valueglobals = mast.valueglobals end end -- Attempt call if safe. if not found and (LS.safe_function[func] or func == pcall and LS.safe_function[argvalues[1]]) then local ok; ok, ast.valuelist = valuesandtuple(1, pcall(func, unpack(argvalues,1,argvalues.n))) ast.value = ast.valuelist[1]; if not ok then ast.value = T.error(ast.value) end found = true end end if not found then -- Attempt mock function. Note: supports nonconcrete args too. local mf = LS.mock_functions[func] if mf then ast.valuelist = mf.outputs; ast.value = ast.valuelist[1] else -- Attempt infer from return statements in function source. local info = M.debuginfo[func] if not info then -- try match from dynamic debug info local dinfo = type(func) == 'function' and debug.getinfo(func) if dinfo then local source, linedefined = dinfo.source, dinfo.linedefined if source and linedefined then local sourceline = source .. ':' .. linedefined info = M.debuginfo[sourceline] end end end local retvals = info and info.retvals if retvals then ast.valuelist = retvals; ast.value = ast.valuelist[1] else -- Could not infer. ast.valuelist = {n=0, sizeunknown=true}; ast.value = T.universal end end end elseif ast.tag == 'String' or ast.tag == 'Number' then ast.value = ast[1] elseif ast.tag == 'True' or ast.tag == 'False' then ast.value = (ast.tag == 'True') elseif ast.tag == 'Function' or ast == top_ast then -- includes chunk if ast.value == nil then -- avoid redefinition local x local val = function() x=nil end local fpos = LA.ast_pos_range(ast, tokenlist) local source, linenum = tostring(ast.lineinfo.first):gsub('<C|','<'):match('<([^|]+)|L(%d+)') -- a HACK? relies on AST lineinfo local retvals if ENABLE_RETURN_ANALYSIS then retvals = get_func_return_values(ast) --Q:move outside of containing conditional? end local info = {fpos=fpos, source="@" .. source, fast=ast, tokenlist=tokenlist, retvals=retvals, top_ast = top_ast} M.debuginfo[val] = info local sourceline = '@' .. source .. ':' .. linenum local oldinfo = M.debuginfo[sourceline] if oldinfo then if oldinfo.fast ~= ast then -- Two functions on the same source line cannot necessarily be disambiguated. -- Unfortuntely, Lua debuginfo lacks exact character position. -- http://lua-users.org/lists/lua-l/2010-08/msg00273.html -- So, just disable info if ambiguous. Note: a slight improvement is to use the lastlinedefined. M.debuginfo[sourceline] = false end else if oldinfo == nil then M.debuginfo[sourceline] = info -- store by sourceline too for quick lookup from dynamic debug info end -- else false (do nothing) end ast.value = val ast.nocollect = info -- prevents garbage collection while ast exists end elseif ast.tag == 'Table' then if ast.value == nil then -- avoid redefinition local value = {} local n = 1 for _,east in ipairs(ast) do if east.tag == 'Pair' then local kast, vast = east[1], east[2] if known(kast.value) and known(vast.value) then if kast.value == nil then -- IMPROVE? warn in some way? else value[kast.value] = vast.value end end else if known(east.value) then value[n] = east.value end n = n + 1 end end --table.foreach(value, print) ast.value = value end elseif ast.tag == 'Paren' then ast.value = ast[1].value elseif ast.tag == 'Op' then local opid, aast, bast = ast[1], ast[2], ast[3] local ok if bast then ok, ast.value = pzcall(dobinop, {aast, bast}, opid, aast.value, bast.value) else ok, ast.value = pzcall(dounop, {aast}, opid, aast.value) end if not ok then ast.value = T.error(ast.value) end elseif ast.tag == 'If' then -- detect dead-code if DETECT_DEADCODE then for i=2,#ast,2 do local valnode = ast[i-1] local bval = T.boolean_cast(valnode.value) if bval == false then -- certainly false mark_dead(ast[i]) elseif bval == true then -- certainly true for ii=i+1,#ast do if ii%2 == 0 or ii==#ast then -- following blocks are dead mark_dead(ast[ii]) end end break end end end -- IMPROVE? `if true return end; f()` - f could be marked as deadcode elseif ast.tag == 'While' then -- detect dead-code if DETECT_DEADCODE then local expr_ast, body_ast = ast[1], ast[2] if T.boolean_cast(expr_ast.value) == false then mark_dead(body_ast) end end end end) end -- Labels variables with unique identifiers. -- Sets ast.id, ast.resolvedname -- CATEGORY: code interpretation function M.mark_identifiers(ast) local id = 0 local seen_globals = {} LA.walk(ast, function(ast) if ast.tag == 'Id' or ast.isfield then if ast.localdefinition then if ast.localdefinition == ast then -- lexical definition id = id + 1 ast.id = id else ast.id = ast.localdefinition.id end elseif ast.isfield then local previousid = ast.previous.id if not previousid then -- note: ("abc"):upper() has no previous ID id = id + 1 previousid = id end local name = previousid .. '.' .. ast[1]:gsub('%%', '%%'):gsub('%.', '%d') if not seen_globals[name] then id = id + 1 seen_globals[name] = id end ast.id = seen_globals[name] -- also resolve name local previousresolvedname = ast.previous.resolvedname if previousresolvedname then ast.resolvedname = previousresolvedname .. '.' .. ast[1]:gsub('%%', '%%'):gsub('%.', '%d') end else -- global local name = ast[1] if not seen_globals[name] then id = id + 1 seen_globals[name] = id end ast.id = seen_globals[name] -- also resolve name ast.resolvedname = ast[1] end end end) end -- Environment in which to execute special comments (see below). local env = setmetatable({}, {__index=_G}) env.context = env env.number = T.number env.string = T.string env.boolean = T.boolean env.error = T.error -- Applies value to all identifiers with name matching pattern. -- This command is callable inside special comments. -- CATEGORY: code interpretation / special comment command function env.apply_value(pattern, val) local function f(ast) if ast.tag == 'Id' and ast[1]:match(pattern) then ast.value = val; ast.isvaluepegged = true end for _,bast in ipairs(ast) do if type(bast) == 'table' then f(bast) end end end f(env.ast) -- ast from environment --UNUSED: -- for i=env.asti, #env.ast do -- local bast = env.ast[i] -- if type(bast) == 'table' then f(bast) end --end end -- Evaluates all special comments (i.e. comments prefixed by '!') in code. -- This is similar to luaanalyze. -- CATEGORY: code interpretation / special comments function M.eval_comments(ast, tokenlist, report) local function eval(command, ast) --DEBUG('!', command:gsub('%s+$', ''), ast.tag) local f, err = COMPAT.load(command, nil, 't', env) if f then env.ast = ast local ok, err = pcall(f, ast) if not ok then warn(report, err, ': ', command) end env.ast = nil else warn(report, err, ': ', command) end end for idx=1,#tokenlist do local token = tokenlist[idx] if token.tag == 'Comment' then local command = token[1]:match'^!(.*)' if command then local mast = LA.smallest_ast_containing_range(ast, tokenlist, token.fpos, token.lpos) eval(command, mast) end end end end --IMPROVE: in `do f() --[[!g()]] h()` only apply g to h. -- Partially undoes effects of inspect(). -- Note: does not undo mark_tag2 and mark_parents (see replace_statements). -- CATEGORY: code interpretation function M.uninspect(top_ast) -- remove ast from M.debuginfo for k, info in pairs(M.debuginfo) do if info and info.top_ast == top_ast then M.debuginfo[k] = nil end end -- Clean ast. LA.walk(top_ast, function(ast) -- undo inspect_globals.globals ast.localdefinition = nil ast.functionlevel = nil ast.isparam = nil ast.isset = nil ast.isused = nil ast.isignore = nil ast.isfield = nil ast.previous = nil ast.localmasked = nil ast.localmasking = nil -- undo mark_identifiers ast.id = nil ast.resolvedname = nil -- undo infer_values ast.value = nil ast.valueself = nil ast.valuelist = nil ast.isdead = nil -- via get_func_returns ast.isvaluepegged = nil -- undo walk setting ast.seevalue ast.seevalue = nil -- undo walk setting ast.definedglobal ast.definedglobal = nil -- undo notes ast.note = nil ast.nocollect = nil -- undo infer_values ast.valueglobals = nil end) end -- Main inspection routine. Inspects top_ast/tokenlist. -- Error/status messages are sent to function `report`. -- CATEGORY: code interpretation function M.inspect(top_ast, tokenlist, src, report) --DEBUG: local t0 = os.clock() if not report then -- compat for older version of lua-inspect assert('inspect signature changed; please upgrade your code') end report = report or function() end local globals = LG.globals(top_ast) M.mark_identifiers(top_ast) M.eval_comments(top_ast, tokenlist, report) M.infer_values(top_ast, tokenlist, src, report) M.infer_values(top_ast, tokenlist, src, report) -- two passes to handle forward declarations of globals (IMPROVE: more passes?) -- Make some nodes as having values related to its parent. -- This allows clicking on `bar` in `foo.bar` to display -- the value of `foo.bar` rather than just "bar". LA.walk(top_ast, function(ast) if ast.tag == 'Index' then ast[2].seevalue = ast elseif ast.tag == 'Invoke' then ast[2].seevalue = {value=ast.valueself, parent=ast} end end) local function eval_name_helper(name) local var = _G for part in (name .. '.'):gmatch("([^.]*)%.") do part = part:gsub('%%(.)', unescape) if type(var) ~= 'table' and type(var) ~= 'userdata' then return nil end --TODO:improve? var = var[part] if var == nil then return nil end end return var end local function eval_name(name) local ok, o = pzcall(eval_name_helper, {}, name) if ok then return o else return nil end end LA.walk(top_ast, function(ast) if top_ast ~= ast and ast.valueglobals then for k in pairs(ast.valueglobals) do globals[k] = {set = ast} end ast.valueglobals = nil end if ast.tag == 'Id' or ast.isfield then local vname = ast[1] --TODO: rename definedglobal to definedfield for clarity local atype = ast.localdefinition and 'local' or ast.isfield and 'field' or 'global' local definedglobal = ast.resolvedname and eval_name(ast.resolvedname) ~= nil or atype == 'global' and (globals[vname] and globals[vname].set) or nil ast.definedglobal = definedglobal -- FIX: _G includes modules imported by inspect.lua, which is not desired elseif ast.tag == 'Call' or ast.tag == 'Invoke' then -- Argument count check. local value = ast.valueself or ast[1].value local info = M.debuginfo[value] local fast = info and info.fast if fast or LS.argument_counts[value] then local nparammin, nparammax if fast then nparammin, nparammax = function_param_range(info.fast) else nparammin, nparammax = unpack(LS.argument_counts[value]) end local nargmin, nargmax = call_arg_range(ast) --print('DEBUG:', nparammin, nparammax, nargmin, nargmax) local iswarn local target_ast = ast.tag == 'Call' and ast[1] or ast[2] if (nargmax or math.huge) < nparammin then ast.note = "Too few arguments; " iswarn = true elseif nargmin > (nparammax or math.huge) then ast.note = "Too many arguments; " iswarn = true end if iswarn then ast.note = ast.note .. "expected " .. nparammin .. (nparammax == nparammin and "" or " to " .. (nparammax or "infinity")) .. " but got " .. nargmin .. (nargmax == nargmin and "" or " to " .. (nargmax or "infinity")) .. "." end end end end) end -- Resolves identifier to value [*] function M.resolve_id(id, scope, valueglobals, _G) local val if scope[id] then val = scope[id].value elseif valueglobals[id] ~= nil then val = valueglobals[id] else val = _G[id] -- assumes not raise end return val end -- Resolves prefix chain expression to value. [*] -- On error returns nil and error object function M.resolve_prefixexp(ids, scope, valueglobals, _G) local _1 = M.resolve_id(ids[1], scope, valueglobals, _G) local ok, err = pzcall(function() for i=2,#ids do _1 = _1[ids[i]] end end, {}) if err then return nil, err or '?' end return _1 end -- Gets local scope at given 1-indexed char position function M.get_scope(pos1, ast, tokenlist) local mast, isafter = LA.current_statementblock(ast, tokenlist, pos1) local scope = LG.variables_in_scope(mast, isafter) return scope end -- Gets names in prefix expression ids (as returned by resolve_prefixexp). [*] function M.names_in_prefixexp(ids, pos, ast, tokenlist) local scope = M.get_scope(pos, ast, tokenlist) --FIX: above does not handle `for x=1,2 do| print(x) end` where '|' is cursor position. local names = {} if #ids == 0 then -- global for name in pairs(scope) do names[#names+1] = name end for name in pairs(ast.valueglobals) do names[#names+1] = name end for name in pairs(_G) do names[#names+1] = name end else -- field local t, err_ = M.resolve_prefixexp(ids, scope, ast.valueglobals, _G) if type(t) == 'table' then -- note: err_ implies false here for name in pairs(t) do names[#names+1] = name end end end return names end -- Gets signature (function argument string or helpinfo string) on value. -- Returns nil on not found. function M.get_signature_of_value(value) local info = M.debuginfo[value] -- first try this if info and info.fast then local fidx, lidx = LA.ast_idx_range_in_tokenlist(info.tokenlist, info.fast[1]) local ts = {} if fidx then for i=fidx,lidx do local token = info.tokenlist[i] ts[#ts+1] = token.tag == 'Dots' and '...' or token[1] end end local sig = 'function(' .. table.concat(ts, ' ') .. ')' if info.retvals then local vals = info.retvals local ts = {} if vals.n == 0 then sig = sig .. " no returns" else for i=1,vals.n do local val = vals[i] ts[#ts+1] = T.istype[val] and tostring(val) or LD.dumpstring(val) --Q:dumpstring too verbose? end sig = sig .. " returns " .. table.concat(ts, ", ") end end return sig end local sig = LS.value_signatures[value] -- else try this return sig end -- Gets signature (function argument string or helpinfo string) on variable ast. -- Returns nil on not found. function M.get_signature(ast) if known(ast.value) then return M.get_signature_of_value(ast.value) end end -- Gets 1-indexed character (or line) position and filename of -- definition associated with AST node (if any). function M.ast_to_definition_position(ast, tokenlist) local local_ast = ast.localdefinition local fpos, fline, path if local_ast then local tidx = LA.ast_idx_range_in_tokenlist(tokenlist, local_ast) if tidx then local spath = tostring(ast.lineinfo.first):gsub('<C|','<'):match('<([^|]+)') -- a HACK? using lineinfo fpos = tokenlist[tidx].fpos; path = spath end end if not fpos then local valueast = ast.seevalue or ast local val = valueast and valueast.value local info = M.debuginfo[val] or type(val) == 'function' and debug.getinfo(val) if info then if info.source:match'^@' then path = info.source:match'@(.*)' if info.linedefined then fline = info.linedefined else fpos = info.fpos end end end end return fpos, fline, path end -- Returns true iff value in ast node is known in some way. function M.is_known_value(ast) local vast = ast.seevalue or ast return vast.definedglobal or known(vast.value) and vast.value ~= nil end -- Gets list of variable attributes for AST node. function M.get_var_attributes(ast) local vast = ast.seevalue or ast local attributes = {} if ast.localdefinition then attributes[#attributes+1] = "local" if ast.localdefinition.functionlevel < ast.functionlevel then attributes[#attributes+1] = 'upvalue' end if ast.localdefinition.isparam then attributes[#attributes+1] = "param" end if not ast.localdefinition.isused then attributes[#attributes+1] = 'unused' end if ast.isignore then attributes[#attributes+1] = 'ignore' end if ast.localdefinition.isset then attributes[#attributes+1] = 'mutatebind' else attributes[#attributes+1] = 'constbind' end if ast.localmasking then attributes[#attributes+1] = "masking" end if ast.localmasked then attributes[#attributes+1] = "masked" end elseif ast.tag == 'Id' then -- global attributes[#attributes+1] = (M.is_known_value(vast) and "known" or "unknown") attributes[#attributes+1] = "global" elseif ast.isfield then attributes[#attributes+1] = (M.is_known_value(vast) and "known" or "unknown") attributes[#attributes+1] = "field" else attributes[#attributes+1] = "FIX" -- shouldn't happen? end if vast.parent and (vast.parent.tag == 'Call' or vast.parent.tag == 'Invoke') and vast.parent.note then attributes[#attributes+1] = 'warn' end return attributes end -- Gets detailed information about value in AST node, as string. function M.get_value_details(ast, tokenlist, src) local lines = {} if not ast then return '?' end local vast = ast.seevalue or ast lines[#lines+1] = "attributes: " .. table.concat(M.get_var_attributes(ast), " ") lines[#lines+1] = "value: " .. tostring(vast.value) local sig = M.get_signature(vast) if sig then local kind = sig:find '%w%s*%b()$' and 'signature' or 'description' lines[#lines+1] = kind .. ": " .. sig end local fpos, fline, path = M.ast_to_definition_position(ast, tokenlist) if fpos or fline then local fcol if fpos then fline, fcol = LA.pos_to_linecol(fpos, src) end local location = path .. ":" .. (fline) .. (fcol and ":" .. fcol or "") lines[#lines+1] = "location defined: " .. location end if ast.localdefinition and ast.localmasking then local fpos = LA.ast_pos_range(ast.localmasking, tokenlist) if fpos then local linenum = LA.pos_to_linecol(fpos, src) lines[#lines+1] = "masking definition at line: " .. linenum end end -- Render warning notes attached to calls/invokes. local note = vast.parent and (vast.parent.tag == 'Call' or vast.parent.tag == 'Invoke') and vast.parent.note if note then lines[#lines+1] = "WARNING: " .. note end return table.concat(lines, "\n") end -- Gets list of all warnings, as strings. -- In HTML Tidy format (which supports column numbers in SciTE, although is -- slightly verbose and lacks filename). function M.list_warnings(tokenlist, src) local warnings = {} local ttoken local function warn(msg) local linenum, colnum = LA.pos_to_linecol(ttoken.fpos, src) warnings[#warnings+1] = "line " .. linenum .. " column " .. colnum .. " - " .. msg end local isseen = {} for i,token in ipairs(tokenlist) do ttoken = token if token.ast then local ast = token.ast if ast.localmasking then local pos = LA.ast_pos_range(ast.localmasking, tokenlist) local linenum = pos and LA.pos_to_linecol(pos, src) warn("local " .. ast[1] .. " masks another local" .. (pos and " on line " .. linenum or "")) end if ast.localdefinition == ast and not ast.isused and not ast.isignore then warn("unused local " .. ast[1]) end if ast.isfield and not(known(ast.seevalue.value) and ast.seevalue.value ~= nil) then warn("unknown field " .. ast[1]) elseif ast.tag == 'Id' and not ast.localdefinition and not ast.definedglobal then warn("unknown global " .. ast[1]) end local vast = ast.seevalue or ast local note = vast.parent and (vast.parent.tag == 'Call' or vast.parent.tag == 'Invoke') and vast.parent.note if note and not isseen[vast.parent] then isseen[vast.parent] = true local esrc = LA.ast_to_text(vast.parent, tokenlist, src) -- IMPROVE: large items like `f(function() ... end)` may be shortened. warn(note .. (esrc and "for " .. esrc or "")) end end end return warnings end return M
LuaExtend/LuaExtend
tools/ZeroBraneStudio/lualibs/luainspect/init.lua
Lua
apache-2.0
50,289
[ 30522, 1011, 1011, 11320, 28247, 5051, 6593, 1012, 1999, 4183, 1011, 4563, 11320, 28247, 5051, 6593, 3120, 4106, 1012, 1011, 1011, 1011, 1011, 2023, 11336, 2003, 1037, 2978, 2062, 2152, 2504, 2084, 11320, 28247, 5051, 6593, 1012, 2004, 2102...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_08.html">Class Test_AbaRouteValidator_08</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_16417_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_08.html?line=34072#src-34072" >testAbaNumberCheck_16417_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:38:01 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_16417_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=23059#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
dcarda/aba.route.validator
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_08_testAbaNumberCheck_16417_good_hsj.html
HTML
apache-2.0
9,181
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 20950, 3619, 1027, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, 8917, 1013, 2639, 1013, 1060, 11039, 19968, 1000, 20950, 1024, 11374, 1027, 1000, 4372, 1000, 11374, 102...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Copyright (c) 2006-2009 The Trustees of Indiana University. # All rights reserved. # # 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 Indiana University 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. from corepy.spre.spe import Instruction, DispatchInstruction, Register from spu_insts import * __doc__=""" ISA for the Cell Broadband Engine's SPU. """ class lqx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':452} cycles = (1, 6, 0) class stqx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':324} cycles = (1, 6, 0) class cbx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':468} cycles = (1, 4, 0) class chx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':469} cycles = (1, 4, 0) class cwx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':470} cycles = (1, 4, 0) class cdx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':471} cycles = (1, 4, 0) class ah(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':200} cycles = (0, 2, 0) class a(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':192} cycles = (0, 2, 0) class sfh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':72} cycles = (0, 2, 0) class sf(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':64} cycles = (0, 2, 0) class addx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':832} cycles = (0, 2, 0) class cg(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':194} cycles = (0, 2, 0) class cgx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':834} cycles = (0, 2, 0) class sfx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':833} cycles = (0, 2, 0) class bg(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':66} cycles = (0, 2, 0) class bgx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':835} cycles = (0, 2, 0) class mpy(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':964} cycles = (0, 7, 0) class mpyu(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':972} cycles = (0, 7, 0) class mpyh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':965} cycles = (0, 7, 0) class mpys(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':967} cycles = (0, 7, 0) class mpyhh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':966} cycles = (0, 7, 0) class mpyhha(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':838} cycles = (0, 7, 0) class mpyhhu(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':974} cycles = (0, 7, 0) class mpyhhau(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':846} cycles = (0, 7, 0) class clz(Instruction): machine_inst = OPCD_A_T params = {'OPCD':677} cycles = (0, 2, 0) class cntb(Instruction): machine_inst = OPCD_A_T params = {'OPCD':692} cycles = (0, 4, 0) class fsmb(Instruction): machine_inst = OPCD_A_T params = {'OPCD':438} cycles = (1, 4, 0) class fsmh(Instruction): machine_inst = OPCD_A_T params = {'OPCD':437} cycles = (1, 4, 0) class fsm(Instruction): machine_inst = OPCD_A_T params = {'OPCD':436} cycles = (1, 4, 0) class gbb(Instruction): machine_inst = OPCD_A_T params = {'OPCD':434} cycles = (1, 4, 0) class gbh(Instruction): machine_inst = OPCD_A_T params = {'OPCD':433} cycles = (1, 4, 0) class gb(Instruction): machine_inst = OPCD_A_T params = {'OPCD':432} cycles = (1, 4, 0) class avgb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':211} cycles = (0, 4, 0) class absdb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':83} cycles = (0, 4, 0) class sumb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':595} cycles = (0, 4, 0) class xsbh(Instruction): machine_inst = OPCD_A_T params = {'OPCD':694} cycles = (0, 2, 0) class xshw(Instruction): machine_inst = OPCD_A_T params = {'OPCD':686} cycles = (0, 2, 0) class xswd(Instruction): machine_inst = OPCD_A_T params = {'OPCD':678} cycles = (0, 2, 0) class and_(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':193} cycles = (0, 2, 0) class andc(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':705} cycles = (0, 2, 0) class or_(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':65} cycles = (0, 2, 0) class orc(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':713} cycles = (0, 2, 0) class orx(Instruction): machine_inst = OPCD_A_T params = {'OPCD':496} cycles = (1, 4, 0) class xor(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':577} cycles = (0, 2, 0) class nand(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':201} cycles = (0, 2, 0) class nor(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':73} cycles = (0, 2, 0) class eqv(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':585} cycles = (0, 2, 0) class shlh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':95} cycles = (0, 4, 0) class shl(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':91} cycles = (0, 4, 0) class shlqbi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':475} cycles = (1, 4, 0) class shlqby(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':479} cycles = (1, 4, 0) class shlqbybi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':463} cycles = (1, 4, 0) class roth(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':92} cycles = (0, 4, 0) class rot(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':88} cycles = (0, 4, 0) class rotqby(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':476} cycles = (1, 4, 0) class rotqbybi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':460} cycles = (1, 4, 0) class rotqbi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':472} cycles = (1, 4, 0) class rothm(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':93} cycles = (0, 4, 0) class rotm(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':89} cycles = (0, 4, 0) class rotqmby(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':477} cycles = (1, 4, 0) class rotqmbybi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':461} cycles = (1, 4, 0) class rotqmbi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':473} cycles = (1, 4, 0) class rotmah(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':94} cycles = (0, 4, 0) class rotma(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':90} cycles = (0, 4, 0) class heq(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':984} cycles = (0, 2, 0) class hgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':600} cycles = (0, 2, 0) class hlgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':728} cycles = (0, 2, 0) class ceqb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':976} cycles = (0, 2, 0) class ceqh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':968} cycles = (0, 2, 0) class ceq(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':960} cycles = (0, 2, 0) class cgtb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':592} cycles = (0, 2, 0) class cgth(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':584} cycles = (0, 2, 0) class cgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':576} cycles = (0, 2, 0) class clgtb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':720} cycles = (0, 2, 0) class clgth(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':712} cycles = (0, 2, 0) class clgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':704} cycles = (0, 2, 0) class bi(Instruction): machine_inst = OPCD_A_D_E params = {'OPCD':424} cycles = (1, 4, 0) class iret(Instruction): machine_inst = OPCD_A_D_E params = {'OPCD':426} cycles = (1, 4, 0) class bisled(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':427} cycles = (1, 4, 0) class bisl(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':425} cycles = (1, 4, 0) class biz(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':296} cycles = (1, 4, 0) class binz(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':297} cycles = (1, 4, 0) class bihz(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':294} cycles = (1, 4, 0) class bihnz(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':299} cycles = (1, 4, 0) # TODO - can we check that if P is set then RO is zero as required? class hbr(DispatchInstruction): cycles = (1, 15, 0) dispatch = ( (OPCD_RO_A_P, {'OPCD':428}), (OPCD_LBL9_A_P, {'OPCD':428})) class fa(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':708} cycles = (0, 6, 0) class dfa(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':716} cycles = (0, 13, 6) class fs(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':709} cycles = (0, 6, 0) class dfs(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':717} cycles = (0, 13, 6) class fm(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':710} cycles = (0, 6, 0) class dfm(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':718} cycles = (0, 13, 6) class dfma(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':860} cycles = (0, 13, 6) class dfnms(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':862} cycles = (0, 13, 6) class dfms(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':861} cycles = (0, 13, 6) class dfnma(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':863} cycles = (0, 13, 6) class frest(Instruction): machine_inst = OPCD_A_T params = {'OPCD':440} cycles = (1, 4, 0) class frsqest(Instruction): machine_inst = OPCD_A_T params = {'OPCD':441} cycles = (1, 4, 0) class fi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':980} cycles = (0, 7, 0) class frds(Instruction): machine_inst = OPCD_A_T params = {'OPCD':953} cycles = (0, 13, 6) class fesd(Instruction): machine_inst = OPCD_A_T params = {'OPCD':952} cycles = (0, 13, 6) class fceq(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':962} cycles = (0, 2, 0) class fcmeq(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':970} cycles = (0, 2, 0) class fcgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':706} cycles = (0, 2, 0) class fcmgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':714} cycles = (0, 2, 0) class fscrwr(Instruction): machine_inst = OPCD_A_T params = {'OPCD':954} cycles = (0, 7, 0) class fscrrd(Instruction): machine_inst = OPCD_T params = {'OPCD':920} cycles = (0, 13, 6) class stop(Instruction): machine_inst = OPCD_STOP_SIG params = {'OPCD':0} cycles = (1, 4, 0) class stopd(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':320} cycles = (1, 4, 0) class lnop(Instruction): machine_inst = OPCD params = {'OPCD':1} cycles = (1, 0, 0) class nop(Instruction): machine_inst = OPCD_T params = {'OPCD':513} cycles = (0, 0, 0) class sync(Instruction): machine_inst = OPCD_CF params = {'OPCD':2} cycles = (1, 4, 0) class dsync(Instruction): machine_inst = OPCD params = {'OPCD':3} cycles = (1, 4, 0) class mfspr(Instruction): machine_inst = OPCD_SA_T params = {'OPCD':12} cycles = (1, 6, 0) class mtspr(Instruction): machine_inst = OPCD_SA_T params = {'OPCD':268} cycles = (1, 6, 0) class rdch(Instruction): machine_inst = OPCD_A_T params = {'OPCD':13} cycles = (1, 6, 0) class rchcnt(Instruction): machine_inst = OPCD_A_T params = {'OPCD':15} cycles = (1, 6, 0) class wrch(Instruction): machine_inst = OPCD_A_T params = {'OPCD':269} cycles = (1, 6, 0) class mpya(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':12} cycles = (0, 7, 0) class selb(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':8} cycles = (0, 2, 0) class shufb(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':11} cycles = (1, 4, 0) class fma(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':14} cycles = (0, 6, 0) class fnms(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':13} cycles = (0, 6, 0) class fms(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':15} cycles = (0, 6, 0) class cbd(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':500} cycles = (1, 4, 0) class chd(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':501} cycles = (1, 4, 0) class cwd(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':502} cycles = (1, 4, 0) class cdd(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':503} cycles = (1, 4, 0) class shlhi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':127} cycles = (0, 4, 0) class shli(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':123} cycles = (0, 4, 0) class shlqbii(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':507} cycles = (1, 4, 0) class shlqbyi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':511} cycles = (1, 4, 0) class rothi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':124} cycles = (0, 4, 0) class roti(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':120} cycles = (0, 4, 0) class rotqbyi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':508} cycles = (1, 4, 0) class rotqbii(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':504} cycles = (1, 4, 0) class rothmi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':125} cycles = (0, 4, 0) class rotmi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':121} cycles = (0, 4, 0) class rotqmbyi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':509} cycles = (1, 4, 0) class rotqmbii(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':505} cycles = (1, 4, 0) class rotmahi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':126} cycles = (0, 4, 0) class rotmai(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':122} cycles = (0, 4, 0) class csflt(Instruction): machine_inst = OPCD_I8_A_T params = {'OPCD':474} cycles = (0, 7, 0) class cflts(Instruction): machine_inst = OPCD_I8_A_T params = {'OPCD':472} cycles = (0, 7, 0) class cuflt(Instruction): machine_inst = OPCD_I8_A_T params = {'OPCD':475} cycles = (0, 7, 0) class cfltu(Instruction): machine_inst = OPCD_I8_A_T params = {'OPCD':473} cycles = (0, 7, 0) class lqd(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':52} cycles = (1, 6, 0) class stqd(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':36} cycles = (1, 6, 0) class ahi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':29} cycles = (0, 2, 0) class ai(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':28} cycles = (0, 2, 0) class sfhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':13} cycles = (0, 2, 0) class sfi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':12} cycles = (0, 2, 0) class mpyi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':116} cycles = (0, 7, 0) class mpyui(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':117} cycles = (0, 7, 0) class andbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':22} cycles = (0, 2, 0) class andhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':21} cycles = (0, 2, 0) class andi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':20} cycles = (0, 2, 0) class orbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':6} cycles = (0, 2, 0) class orhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':5} cycles = (0, 2, 0) class ori(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':4} cycles = (0, 2, 0) class xorbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':70} cycles = (0, 2, 0) class xorhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':69} cycles = (0, 2, 0) class xori(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':68} cycles = (0, 2, 0) class heqi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':127} cycles = (0, 2, 0) class hgti(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':79} cycles = (0, 2, 0) class hlgti(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':95} cycles = (0, 2, 0) class ceqbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':126} cycles = (0, 2, 0) class ceqhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':125} cycles = (0, 2, 0) class ceqi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':124} cycles = (0, 2, 0) class cgtbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':78} cycles = (0, 2, 0) class cgthi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':77} cycles = (0, 2, 0) class cgti(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':76} cycles = (0, 2, 0) class clgtbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':94} cycles = (0, 2, 0) class clgthi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':93} cycles = (0, 2, 0) class clgti(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':92} cycles = (0, 2, 0) class lqa(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':97} cycles = (1, 6, 0) class lqr(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':103} cycles = (1, 6, 0) class stqa(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':65} cycles = (1, 6, 0) class stqr(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':71} cycles = (1, 6, 0) class ilh(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':131} cycles = (0, 2, 0) class ilhu(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':130} cycles = (0, 2, 0) class il(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':129} cycles = (0, 2, 0) class iohl(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':193} cycles = (0, 2, 0) class fsmbi(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':101} cycles = (1, 4, 0) class br(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16, {'OPCD':100}), (OPCD_LBL16, {'OPCD':100})) # TODO - how can I do absolute branches? class bra(Instruction): machine_inst = OPCD_I16 params = {'OPCD':96} cycles = (1, 4, 0) # TODO - I16 has two zero bits appended, do I handle this correctly? # What is the correct way, anyway? class brsl(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16_T, {'OPCD':102}), (OPCD_LBL16_T, {'OPCD':102})) class brasl(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':98} cycles = (1, 4, 0) class brnz(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16_T, {'OPCD':66}), (OPCD_LBL16_T, {'OPCD':66})) class brz(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16_T, {'OPCD':64}), (OPCD_LBL16_T, {'OPCD':64})) class brhnz(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16, {'OPCD':70}), (OPCD_LBL16, {'OPCD':70})) class brhz(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16, {'OPCD':68}), (OPCD_LBL16, {'OPCD':68})) class hbra(Instruction): machine_inst = OPCD_LBL9_I16 params = {'OPCD':8} cycles = (1, 15, 0) class hbrr(DispatchInstruction): cycles = (1, 15, 0) dispatch = ( (OPCD_ROA_I16, {'OPCD':9}), (OPCD_LBL9_LBL16, {'OPCD':9})) class ila(Instruction): machine_inst = OPCD_I18_T params = {'OPCD':33} cycles = (0, 2, 0)
matthiaskramm/corepy
corepy/arch/spu/isa/spu_isa.py
Python
bsd-3-clause
22,294
[ 30522, 1001, 9385, 1006, 1039, 1007, 2294, 1011, 2268, 1996, 9360, 1997, 5242, 2118, 1012, 1001, 2035, 2916, 9235, 1012, 1001, 1001, 25707, 1998, 2224, 1999, 3120, 1998, 12441, 3596, 1010, 2007, 2030, 2302, 1001, 14080, 1010, 2024, 7936, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!-- @license Copyright (c) 2017 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <link rel="import" href="../utils/boot.html"> <link rel="import" href="../utils/mixin.html"> <link rel="import" href="../utils/path.html"> <!-- for notify, reflect --> <link rel="import" href="../utils/case-map.html"> <link rel="import" href="property-accessors.html"> <!-- for annotated effects --> <link rel="import" href="template-stamp.html"> <script> (function() { 'use strict'; /** @const {Object} */ const CaseMap = Polymer.CaseMap; // Monotonically increasing unique ID used for de-duping effects triggered // from multiple properties in the same turn let dedupeId = 0; /** * Property effect types; effects are stored on the prototype using these keys * @enum {string} */ const TYPES = { COMPUTE: '__computeEffects', REFLECT: '__reflectEffects', NOTIFY: '__notifyEffects', PROPAGATE: '__propagateEffects', OBSERVE: '__observeEffects', READ_ONLY: '__readOnly' }; /** * @typedef {{ * name: (string | undefined), * structured: (boolean | undefined), * wildcard: (boolean | undefined) * }} */ let DataTrigger; //eslint-disable-line no-unused-vars /** * @typedef {{ * info: ?, * trigger: (!DataTrigger | undefined), * fn: (!Function | undefined) * }} */ let DataEffect; //eslint-disable-line no-unused-vars let PropertyEffectsType; //eslint-disable-line no-unused-vars /** * Ensures that the model has an own-property map of effects for the given type. * The model may be a prototype or an instance. * * Property effects are stored as arrays of effects by property in a map, * by named type on the model. e.g. * * __computeEffects: { * foo: [ ... ], * bar: [ ... ] * } * * If the model does not yet have an effect map for the type, one is created * and returned. If it does, but it is not an own property (i.e. the * prototype had effects), the the map is deeply cloned and the copy is * set on the model and returned, ready for new effects to be added. * * @param {Object} model Prototype or instance * @param {string} type Property effect type * @return {Object} The own-property map of effects for the given type * @private */ function ensureOwnEffectMap(model, type) { let effects = model[type]; if (!effects) { effects = model[type] = {}; } else if (!model.hasOwnProperty(type)) { effects = model[type] = Object.create(model[type]); for (let p in effects) { let protoFx = effects[p]; let instFx = effects[p] = Array(protoFx.length); for (let i=0; i<protoFx.length; i++) { instFx[i] = protoFx[i]; } } } return effects; } // -- effects ---------------------------------------------- /** * Runs all effects of a given type for the given set of property changes * on an instance. * * @param {!PropertyEffectsType} inst The instance with effects to run * @param {Object} effects Object map of property-to-Array of effects * @param {Object} props Bag of current property changes * @param {Object=} oldProps Bag of previous values for changed properties * @param {boolean=} hasPaths True with `props` contains one or more paths * @param {*=} extraArgs Additional metadata to pass to effect function * @return {boolean} True if an effect ran for this property * @private */ function runEffects(inst, effects, props, oldProps, hasPaths, extraArgs) { if (effects) { let ran = false; let id = dedupeId++; for (let prop in props) { if (runEffectsForProperty(inst, effects, id, prop, props, oldProps, hasPaths, extraArgs)) { ran = true; } } return ran; } return false; } /** * Runs a list of effects for a given property. * * @param {!PropertyEffectsType} inst The instance with effects to run * @param {Object} effects Object map of property-to-Array of effects * @param {number} dedupeId Counter used for de-duping effects * @param {string} prop Name of changed property * @param {*} props Changed properties * @param {*} oldProps Old properties * @param {boolean=} hasPaths True with `props` contains one or more paths * @param {*=} extraArgs Additional metadata to pass to effect function * @return {boolean} True if an effect ran for this property * @private */ function runEffectsForProperty(inst, effects, dedupeId, prop, props, oldProps, hasPaths, extraArgs) { let ran = false; let rootProperty = hasPaths ? Polymer.Path.root(prop) : prop; let fxs = effects[rootProperty]; if (fxs) { for (let i=0, l=fxs.length, fx; (i<l) && (fx=fxs[i]); i++) { if ((!fx.info || fx.info.lastRun !== dedupeId) && (!hasPaths || pathMatchesTrigger(prop, fx.trigger))) { if (fx.info) { fx.info.lastRun = dedupeId; } fx.fn(inst, prop, props, oldProps, fx.info, hasPaths, extraArgs); ran = true; } } } return ran; } /** * Determines whether a property/path that has changed matches the trigger * criteria for an effect. A trigger is a descriptor with the following * structure, which matches the descriptors returned from `parseArg`. * e.g. for `foo.bar.*`: * ``` * trigger: { * name: 'a.b', * structured: true, * wildcard: true * } * ``` * If no trigger is given, the path is deemed to match. * * @param {string} path Path or property that changed * @param {DataTrigger} trigger Descriptor * @return {boolean} Whether the path matched the trigger */ function pathMatchesTrigger(path, trigger) { if (trigger) { let triggerPath = trigger.name; return (triggerPath == path) || (trigger.structured && Polymer.Path.isAncestor(triggerPath, path)) || (trigger.wildcard && Polymer.Path.isDescendant(triggerPath, path)); } else { return true; } } /** * Implements the "observer" effect. * * Calls the method with `info.methodName` on the instance, passing the * new and old values. * * @param {!PropertyEffectsType} inst The instance the effect will be run on * @param {string} property Name of property * @param {Object} props Bag of current property changes * @param {Object} oldProps Bag of previous values for changed properties * @param {?} info Effect metadata * @return {void} * @private */ function runObserverEffect(inst, property, props, oldProps, info) { let fn = typeof info.method === "string" ? inst[info.method] : info.method; let changedProp = info.property; if (fn) { fn.call(inst, inst.__data[changedProp], oldProps[changedProp]); } else if (!info.dynamicFn) { console.warn('observer method `' + info.method + '` not defined'); } } /** * Runs "notify" effects for a set of changed properties. * * This method differs from the generic `runEffects` method in that it * will dispatch path notification events in the case that the property * changed was a path and the root property for that path didn't have a * "notify" effect. This is to maintain 1.0 behavior that did not require * `notify: true` to ensure object sub-property notifications were * sent. * * @param {!PropertyEffectsType} inst The instance with effects to run * @param {Object} notifyProps Bag of properties to notify * @param {Object} props Bag of current property changes * @param {Object} oldProps Bag of previous values for changed properties * @param {boolean} hasPaths True with `props` contains one or more paths * @return {void} * @private */ function runNotifyEffects(inst, notifyProps, props, oldProps, hasPaths) { // Notify let fxs = inst[TYPES.NOTIFY]; let notified; let id = dedupeId++; // Try normal notify effects; if none, fall back to try path notification for (let prop in notifyProps) { if (notifyProps[prop]) { if (fxs && runEffectsForProperty(inst, fxs, id, prop, props, oldProps, hasPaths)) { notified = true; } else if (hasPaths && notifyPath(inst, prop, props)) { notified = true; } } } // Flush host if we actually notified and host was batching // And the host has already initialized clients; this prevents // an issue with a host observing data changes before clients are ready. let host; if (notified && (host = inst.__dataHost) && host._invalidateProperties) { host._invalidateProperties(); } } /** * Dispatches {property}-changed events with path information in the detail * object to indicate a sub-path of the property was changed. * * @param {!PropertyEffectsType} inst The element from which to fire the event * @param {string} path The path that was changed * @param {Object} props Bag of current property changes * @return {boolean} Returns true if the path was notified * @private */ function notifyPath(inst, path, props) { let rootProperty = Polymer.Path.root(path); if (rootProperty !== path) { let eventName = Polymer.CaseMap.camelToDashCase(rootProperty) + '-changed'; dispatchNotifyEvent(inst, eventName, props[path], path); return true; } return false; } /** * Dispatches {property}-changed events to indicate a property (or path) * changed. * * @param {!PropertyEffectsType} inst The element from which to fire the event * @param {string} eventName The name of the event to send ('{property}-changed') * @param {*} value The value of the changed property * @param {string | null | undefined} path If a sub-path of this property changed, the path * that changed (optional). * @return {void} * @private * @suppress {invalidCasts} */ function dispatchNotifyEvent(inst, eventName, value, path) { let detail = { value: value, queueProperty: true }; if (path) { detail.path = path; } /** @type {!HTMLElement} */(inst).dispatchEvent(new CustomEvent(eventName, { detail })); } /** * Implements the "notify" effect. * * Dispatches a non-bubbling event named `info.eventName` on the instance * with a detail object containing the new `value`. * * @param {!PropertyEffectsType} inst The instance the effect will be run on * @param {string} property Name of property * @param {Object} props Bag of current property changes * @param {Object} oldProps Bag of previous values for changed properties * @param {?} info Effect metadata * @param {boolean} hasPaths True with `props` contains one or more paths * @return {void} * @private */ function runNotifyEffect(inst, property, props, oldProps, info, hasPaths) { let rootProperty = hasPaths ? Polymer.Path.root(property) : property; let path = rootProperty != property ? property : null; let value = path ? Polymer.Path.get(inst, path) : inst.__data[property]; if (path && value === undefined) { value = props[property]; // specifically for .splices } dispatchNotifyEvent(inst, info.eventName, value, path); } /** * Handler function for 2-way notification events. Receives context * information captured in the `addNotifyListener` closure from the * `__notifyListeners` metadata. * * Sets the value of the notified property to the host property or path. If * the event contained path information, translate that path to the host * scope's name for that path first. * * @param {CustomEvent} event Notification event (e.g. '<property>-changed') * @param {!PropertyEffectsType} inst Host element instance handling the notification event * @param {string} fromProp Child element property that was bound * @param {string} toPath Host property/path that was bound * @param {boolean} negate Whether the binding was negated * @return {void} * @private */ function handleNotification(event, inst, fromProp, toPath, negate) { let value; let detail = /** @type {Object} */(event.detail); let fromPath = detail && detail.path; if (fromPath) { toPath = Polymer.Path.translate(fromProp, toPath, fromPath); value = detail && detail.value; } else { value = event.target[fromProp]; } value = negate ? !value : value; if (!inst[TYPES.READ_ONLY] || !inst[TYPES.READ_ONLY][toPath]) { if (inst._setPendingPropertyOrPath(toPath, value, true, Boolean(fromPath)) && (!detail || !detail.queueProperty)) { inst._invalidateProperties(); } } } /** * Implements the "reflect" effect. * * Sets the attribute named `info.attrName` to the given property value. * * @param {!PropertyEffectsType} inst The instance the effect will be run on * @param {string} property Name of property * @param {Object} props Bag of current property changes * @param {Object} oldProps Bag of previous values for changed properties * @param {?} info Effect metadata * @return {void} * @private */ function runReflectEffect(inst, property, props, oldProps, info) { let value = inst.__data[property]; if (Polymer.sanitizeDOMValue) { value = Polymer.sanitizeDOMValue(value, info.attrName, 'attribute', /** @type {Node} */(inst)); } inst._propertyToAttribute(property, info.attrName, value); } /** * Runs "computed" effects for a set of changed properties. * * This method differs from the generic `runEffects` method in that it * continues to run computed effects based on the output of each pass until * there are no more newly computed properties. This ensures that all * properties that will be computed by the initial set of changes are * computed before other effects (binding propagation, observers, and notify) * run. * * @param {!PropertyEffectsType} inst The instance the effect will be run on * @param {!Object} changedProps Bag of changed properties * @param {!Object} oldProps Bag of previous values for changed properties * @param {boolean} hasPaths True with `props` contains one or more paths * @return {void} * @private */ function runComputedEffects(inst, changedProps, oldProps, hasPaths) { let computeEffects = inst[TYPES.COMPUTE]; if (computeEffects) { let inputProps = changedProps; while (runEffects(inst, computeEffects, inputProps, oldProps, hasPaths)) { Object.assign(oldProps, inst.__dataOld); Object.assign(changedProps, inst.__dataPending); inputProps = inst.__dataPending; inst.__dataPending = null; } } } /** * Implements the "computed property" effect by running the method with the * values of the arguments specified in the `info` object and setting the * return value to the computed property specified. * * @param {!PropertyEffectsType} inst The instance the effect will be run on * @param {string} property Name of property * @param {Object} props Bag of current property changes * @param {Object} oldProps Bag of previous values for changed properties * @param {?} info Effect metadata * @return {void} * @private */ function runComputedEffect(inst, property, props, oldProps, info) { let result = runMethodEffect(inst, property, props, oldProps, info); let computedProp = info.methodInfo; if (inst.__dataHasAccessor && inst.__dataHasAccessor[computedProp]) { inst._setPendingProperty(computedProp, result, true); } else { inst[computedProp] = result; } } /** * Computes path changes based on path links set up using the `linkPaths` * API. * * @param {!PropertyEffectsType} inst The instance whose props are changing * @param {string | !Array<(string|number)>} path Path that has changed * @param {*} value Value of changed path * @return {void} * @private */ function computeLinkedPaths(inst, path, value) { let links = inst.__dataLinkedPaths; if (links) { let link; for (let a in links) { let b = links[a]; if (Polymer.Path.isDescendant(a, path)) { link = Polymer.Path.translate(a, b, path); inst._setPendingPropertyOrPath(link, value, true, true); } else if (Polymer.Path.isDescendant(b, path)) { link = Polymer.Path.translate(b, a, path); inst._setPendingPropertyOrPath(link, value, true, true); } } } } // -- bindings ---------------------------------------------- /** * Adds binding metadata to the current `nodeInfo`, and binding effects * for all part dependencies to `templateInfo`. * * @param {Function} constructor Class that `_parseTemplate` is currently * running on * @param {TemplateInfo} templateInfo Template metadata for current template * @param {NodeInfo} nodeInfo Node metadata for current template node * @param {string} kind Binding kind, either 'property', 'attribute', or 'text' * @param {string} target Target property name * @param {!Array<!BindingPart>} parts Array of binding part metadata * @param {string=} literal Literal text surrounding binding parts (specified * only for 'property' bindings, since these must be initialized as part * of boot-up) * @return {void} * @private */ function addBinding(constructor, templateInfo, nodeInfo, kind, target, parts, literal) { // Create binding metadata and add to nodeInfo nodeInfo.bindings = nodeInfo.bindings || []; let /** Binding */ binding = { kind, target, parts, literal, isCompound: (parts.length !== 1) }; nodeInfo.bindings.push(binding); // Add listener info to binding metadata if (shouldAddListener(binding)) { let {event, negate} = binding.parts[0]; binding.listenerEvent = event || (CaseMap.camelToDashCase(target) + '-changed'); binding.listenerNegate = negate; } // Add "propagate" property effects to templateInfo let index = templateInfo.nodeInfoList.length; for (let i=0; i<binding.parts.length; i++) { let part = binding.parts[i]; part.compoundIndex = i; addEffectForBindingPart(constructor, templateInfo, binding, part, index); } } /** * Adds property effects to the given `templateInfo` for the given binding * part. * * @param {Function} constructor Class that `_parseTemplate` is currently * running on * @param {TemplateInfo} templateInfo Template metadata for current template * @param {!Binding} binding Binding metadata * @param {!BindingPart} part Binding part metadata * @param {number} index Index into `nodeInfoList` for this node * @return {void} */ function addEffectForBindingPart(constructor, templateInfo, binding, part, index) { if (!part.literal) { if (binding.kind === 'attribute' && binding.target[0] === '-') { console.warn('Cannot set attribute ' + binding.target + ' because "-" is not a valid attribute starting character'); } else { let dependencies = part.dependencies; let info = { index, binding, part, evaluator: constructor }; for (let j=0; j<dependencies.length; j++) { let trigger = dependencies[j]; if (typeof trigger == 'string') { trigger = parseArg(trigger); trigger.wildcard = true; } constructor._addTemplatePropertyEffect(templateInfo, trigger.rootProperty, { fn: runBindingEffect, info, trigger }); } } } } /** * Implements the "binding" (property/path binding) effect. * * Note that binding syntax is overridable via `_parseBindings` and * `_evaluateBinding`. This method will call `_evaluateBinding` for any * non-literal parts returned from `_parseBindings`. However, * there is no support for _path_ bindings via custom binding parts, * as this is specific to Polymer's path binding syntax. * * @param {!PropertyEffectsType} inst The instance the effect will be run on * @param {string} path Name of property * @param {Object} props Bag of current property changes * @param {Object} oldProps Bag of previous values for changed properties * @param {?} info Effect metadata * @param {boolean} hasPaths True with `props` contains one or more paths * @param {Array} nodeList List of nodes associated with `nodeInfoList` template * metadata * @return {void} * @private */ function runBindingEffect(inst, path, props, oldProps, info, hasPaths, nodeList) { let node = nodeList[info.index]; let binding = info.binding; let part = info.part; // Subpath notification: transform path and set to client // e.g.: foo="{{obj.sub}}", path: 'obj.sub.prop', set 'foo.prop'=obj.sub.prop if (hasPaths && part.source && (path.length > part.source.length) && (binding.kind == 'property') && !binding.isCompound && node.__dataHasAccessor && node.__dataHasAccessor[binding.target]) { let value = props[path]; path = Polymer.Path.translate(part.source, binding.target, path); if (node._setPendingPropertyOrPath(path, value, false, true)) { inst._enqueueClient(node); } } else { let value = info.evaluator._evaluateBinding(inst, part, path, props, oldProps, hasPaths); // Propagate value to child applyBindingValue(inst, node, binding, part, value); } } /** * Sets the value for an "binding" (binding) effect to a node, * either as a property or attribute. * * @param {!PropertyEffectsType} inst The instance owning the binding effect * @param {Node} node Target node for binding * @param {!Binding} binding Binding metadata * @param {!BindingPart} part Binding part metadata * @param {*} value Value to set * @return {void} * @private */ function applyBindingValue(inst, node, binding, part, value) { value = computeBindingValue(node, value, binding, part); if (Polymer.sanitizeDOMValue) { value = Polymer.sanitizeDOMValue(value, binding.target, binding.kind, node); } if (binding.kind == 'attribute') { // Attribute binding inst._valueToNodeAttribute(/** @type {Element} */(node), value, binding.target); } else { // Property binding let prop = binding.target; if (node.__dataHasAccessor && node.__dataHasAccessor[prop]) { if (!node[TYPES.READ_ONLY] || !node[TYPES.READ_ONLY][prop]) { if (node._setPendingProperty(prop, value)) { inst._enqueueClient(node); } } } else { inst._setUnmanagedPropertyToNode(node, prop, value); } } } /** * Transforms an "binding" effect value based on compound & negation * effect metadata, as well as handling for special-case properties * * @param {Node} node Node the value will be set to * @param {*} value Value to set * @param {!Binding} binding Binding metadata * @param {!BindingPart} part Binding part metadata * @return {*} Transformed value to set * @private */ function computeBindingValue(node, value, binding, part) { if (binding.isCompound) { let storage = node.__dataCompoundStorage[binding.target]; storage[part.compoundIndex] = value; value = storage.join(''); } if (binding.kind !== 'attribute') { // Some browsers serialize `undefined` to `"undefined"` if (binding.target === 'textContent' || (binding.target === 'value' && (node.localName === 'input' || node.localName === 'textarea'))) { value = value == undefined ? '' : value; } } return value; } /** * Returns true if a binding's metadata meets all the requirements to allow * 2-way binding, and therefore a `<property>-changed` event listener should be * added: * - used curly braces * - is a property (not attribute) binding * - is not a textContent binding * - is not compound * * @param {!Binding} binding Binding metadata * @return {boolean} True if 2-way listener should be added * @private */ function shouldAddListener(binding) { return Boolean(binding.target) && binding.kind != 'attribute' && binding.kind != 'text' && !binding.isCompound && binding.parts[0].mode === '{'; } /** * Setup compound binding storage structures, notify listeners, and dataHost * references onto the bound nodeList. * * @param {!PropertyEffectsType} inst Instance that bas been previously bound * @param {TemplateInfo} templateInfo Template metadata * @return {void} * @private */ function setupBindings(inst, templateInfo) { // Setup compound storage, dataHost, and notify listeners let {nodeList, nodeInfoList} = templateInfo; if (nodeInfoList.length) { for (let i=0; i < nodeInfoList.length; i++) { let info = nodeInfoList[i]; let node = nodeList[i]; let bindings = info.bindings; if (bindings) { for (let i=0; i<bindings.length; i++) { let binding = bindings[i]; setupCompoundStorage(node, binding); addNotifyListener(node, inst, binding); } } node.__dataHost = inst; } } } /** * Initializes `__dataCompoundStorage` local storage on a bound node with * initial literal data for compound bindings, and sets the joined * literal parts to the bound property. * * When changes to compound parts occur, they are first set into the compound * storage array for that property, and then the array is joined to result in * the final value set to the property/attribute. * * @param {Node} node Bound node to initialize * @param {Binding} binding Binding metadata * @return {void} * @private */ function setupCompoundStorage(node, binding) { if (binding.isCompound) { // Create compound storage map let storage = node.__dataCompoundStorage || (node.__dataCompoundStorage = {}); let parts = binding.parts; // Copy literals from parts into storage for this binding let literals = new Array(parts.length); for (let j=0; j<parts.length; j++) { literals[j] = parts[j].literal; } let target = binding.target; storage[target] = literals; // Configure properties with their literal parts if (binding.literal && binding.kind == 'property') { node[target] = binding.literal; } } } /** * Adds a 2-way binding notification event listener to the node specified * * @param {Object} node Child element to add listener to * @param {!PropertyEffectsType} inst Host element instance to handle notification event * @param {Binding} binding Binding metadata * @return {void} * @private */ function addNotifyListener(node, inst, binding) { if (binding.listenerEvent) { let part = binding.parts[0]; node.addEventListener(binding.listenerEvent, function(e) { handleNotification(e, inst, binding.target, part.source, part.negate); }); } } // -- for method-based effects (complexObserver & computed) -------------- /** * Adds property effects for each argument in the method signature (and * optionally, for the method name if `dynamic` is true) that calls the * provided effect function. * * @param {Element | Object} model Prototype or instance * @param {!MethodSignature} sig Method signature metadata * @param {string} type Type of property effect to add * @param {Function} effectFn Function to run when arguments change * @param {*=} methodInfo Effect-specific information to be included in * method effect metadata * @param {boolean|Object=} dynamicFn Boolean or object map indicating whether * method names should be included as a dependency to the effect. Note, * defaults to true if the signature is static (sig.static is true). * @return {void} * @private */ function createMethodEffect(model, sig, type, effectFn, methodInfo, dynamicFn) { dynamicFn = sig.static || (dynamicFn && (typeof dynamicFn !== 'object' || dynamicFn[sig.methodName])); let info = { methodName: sig.methodName, args: sig.args, methodInfo, dynamicFn }; for (let i=0, arg; (i<sig.args.length) && (arg=sig.args[i]); i++) { if (!arg.literal) { model._addPropertyEffect(arg.rootProperty, type, { fn: effectFn, info: info, trigger: arg }); } } if (dynamicFn) { model._addPropertyEffect(sig.methodName, type, { fn: effectFn, info: info }); } } /** * Calls a method with arguments marshaled from properties on the instance * based on the method signature contained in the effect metadata. * * Multi-property observers, computed properties, and inline computing * functions call this function to invoke the method, then use the return * value accordingly. * * @param {!PropertyEffectsType} inst The instance the effect will be run on * @param {string} property Name of property * @param {Object} props Bag of current property changes * @param {Object} oldProps Bag of previous values for changed properties * @param {?} info Effect metadata * @return {*} Returns the return value from the method invocation * @private */ function runMethodEffect(inst, property, props, oldProps, info) { // Instances can optionally have a _methodHost which allows redirecting where // to find methods. Currently used by `templatize`. let context = inst._methodHost || inst; let fn = context[info.methodName]; if (fn) { let args = marshalArgs(inst.__data, info.args, property, props); return fn.apply(context, args); } else if (!info.dynamicFn) { console.warn('method `' + info.methodName + '` not defined'); } } const emptyArray = []; // Regular expressions used for binding const IDENT = '(?:' + '[a-zA-Z_$][\\w.:$\\-*]*' + ')'; const NUMBER = '(?:' + '[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?' + ')'; const SQUOTE_STRING = '(?:' + '\'(?:[^\'\\\\]|\\\\.)*\'' + ')'; const DQUOTE_STRING = '(?:' + '"(?:[^"\\\\]|\\\\.)*"' + ')'; const STRING = '(?:' + SQUOTE_STRING + '|' + DQUOTE_STRING + ')'; const ARGUMENT = '(?:(' + IDENT + '|' + NUMBER + '|' + STRING + ')\\s*' + ')'; const ARGUMENTS = '(?:' + ARGUMENT + '(?:,\\s*' + ARGUMENT + ')*' + ')'; const ARGUMENT_LIST = '(?:' + '\\(\\s*' + '(?:' + ARGUMENTS + '?' + ')' + '\\)\\s*' + ')'; const BINDING = '(' + IDENT + '\\s*' + ARGUMENT_LIST + '?' + ')'; // Group 3 const OPEN_BRACKET = '(\\[\\[|{{)' + '\\s*'; const CLOSE_BRACKET = '(?:]]|}})'; const NEGATE = '(?:(!)\\s*)?'; // Group 2 const EXPRESSION = OPEN_BRACKET + NEGATE + BINDING + CLOSE_BRACKET; const bindingRegex = new RegExp(EXPRESSION, "g"); /** * Create a string from binding parts of all the literal parts * * @param {!Array<BindingPart>} parts All parts to stringify * @return {string} String made from the literal parts */ function literalFromParts(parts) { let s = ''; for (let i=0; i<parts.length; i++) { let literal = parts[i].literal; s += literal || ''; } return s; } /** * Parses an expression string for a method signature, and returns a metadata * describing the method in terms of `methodName`, `static` (whether all the * arguments are literals), and an array of `args` * * @param {string} expression The expression to parse * @return {?MethodSignature} The method metadata object if a method expression was * found, otherwise `undefined` * @private */ function parseMethod(expression) { // tries to match valid javascript property names let m = expression.match(/([^\s]+?)\(([\s\S]*)\)/); if (m) { let methodName = m[1]; let sig = { methodName, static: true, args: emptyArray }; if (m[2].trim()) { // replace escaped commas with comma entity, split on un-escaped commas let args = m[2].replace(/\\,/g, '&comma;').split(','); return parseArgs(args, sig); } else { return sig; } } return null; } /** * Parses an array of arguments and sets the `args` property of the supplied * signature metadata object. Sets the `static` property to false if any * argument is a non-literal. * * @param {!Array<string>} argList Array of argument names * @param {!MethodSignature} sig Method signature metadata object * @return {!MethodSignature} The updated signature metadata object * @private */ function parseArgs(argList, sig) { sig.args = argList.map(function(rawArg) { let arg = parseArg(rawArg); if (!arg.literal) { sig.static = false; } return arg; }, this); return sig; } /** * Parses an individual argument, and returns an argument metadata object * with the following fields: * * { * value: 'prop', // property/path or literal value * literal: false, // whether argument is a literal * structured: false, // whether the property is a path * rootProperty: 'prop', // the root property of the path * wildcard: false // whether the argument was a wildcard '.*' path * } * * @param {string} rawArg The string value of the argument * @return {!MethodArg} Argument metadata object * @private */ function parseArg(rawArg) { // clean up whitespace let arg = rawArg.trim() // replace comma entity with comma .replace(/&comma;/g, ',') // repair extra escape sequences; note only commas strictly need // escaping, but we allow any other char to be escaped since its // likely users will do this .replace(/\\(.)/g, '\$1') ; // basic argument descriptor let a = { name: arg, value: '', literal: false }; // detect literal value (must be String or Number) let fc = arg[0]; if (fc === '-') { fc = arg[1]; } if (fc >= '0' && fc <= '9') { fc = '#'; } switch(fc) { case "'": case '"': a.value = arg.slice(1, -1); a.literal = true; break; case '#': a.value = Number(arg); a.literal = true; break; } // if not literal, look for structured path if (!a.literal) { a.rootProperty = Polymer.Path.root(arg); // detect structured path (has dots) a.structured = Polymer.Path.isPath(arg); if (a.structured) { a.wildcard = (arg.slice(-2) == '.*'); if (a.wildcard) { a.name = arg.slice(0, -2); } } } return a; } /** * Gather the argument values for a method specified in the provided array * of argument metadata. * * The `path` and `value` arguments are used to fill in wildcard descriptor * when the method is being called as a result of a path notification. * * @param {Object} data Instance data storage object to read properties from * @param {!Array<!MethodArg>} args Array of argument metadata * @param {string} path Property/path name that triggered the method effect * @param {Object} props Bag of current property changes * @return {Array<*>} Array of argument values * @private */ function marshalArgs(data, args, path, props) { let values = []; for (let i=0, l=args.length; i<l; i++) { let arg = args[i]; let name = arg.name; let v; if (arg.literal) { v = arg.value; } else { if (arg.structured) { v = Polymer.Path.get(data, name); // when data is not stored e.g. `splices` if (v === undefined) { v = props[name]; } } else { v = data[name]; } } if (arg.wildcard) { // Only send the actual path changed info if the change that // caused the observer to run matched the wildcard let baseChanged = (name.indexOf(path + '.') === 0); let matches = (path.indexOf(name) === 0 && !baseChanged); values[i] = { path: matches ? path : name, value: matches ? props[path] : v, base: v }; } else { values[i] = v; } } return values; } // data api /** * Sends array splice notifications (`.splices` and `.length`) * * Note: this implementation only accepts normalized paths * * @param {!PropertyEffectsType} inst Instance to send notifications to * @param {Array} array The array the mutations occurred on * @param {string} path The path to the array that was mutated * @param {Array} splices Array of splice records * @return {void} * @private */ function notifySplices(inst, array, path, splices) { let splicesPath = path + '.splices'; inst.notifyPath(splicesPath, { indexSplices: splices }); inst.notifyPath(path + '.length', array.length); // Null here to allow potentially large splice records to be GC'ed. inst.__data[splicesPath] = {indexSplices: null}; } /** * Creates a splice record and sends an array splice notification for * the described mutation * * Note: this implementation only accepts normalized paths * * @param {!PropertyEffectsType} inst Instance to send notifications to * @param {Array} array The array the mutations occurred on * @param {string} path The path to the array that was mutated * @param {number} index Index at which the array mutation occurred * @param {number} addedCount Number of added items * @param {Array} removed Array of removed items * @return {void} * @private */ function notifySplice(inst, array, path, index, addedCount, removed) { notifySplices(inst, array, path, [{ index: index, addedCount: addedCount, removed: removed, object: array, type: 'splice' }]); } /** * Returns an upper-cased version of the string. * * @param {string} name String to uppercase * @return {string} Uppercased string * @private */ function upper(name) { return name[0].toUpperCase() + name.substring(1); } /** * Element class mixin that provides meta-programming for Polymer's template * binding and data observation (collectively, "property effects") system. * * This mixin uses provides the following key static methods for adding * property effects to an element class: * - `addPropertyEffect` * - `createPropertyObserver` * - `createMethodObserver` * - `createNotifyingProperty` * - `createReadOnlyProperty` * - `createReflectedProperty` * - `createComputedProperty` * - `bindTemplate` * * Each method creates one or more property accessors, along with metadata * used by this mixin's implementation of `_propertiesChanged` to perform * the property effects. * * Underscored versions of the above methods also exist on the element * prototype for adding property effects on instances at runtime. * * Note that this mixin overrides several `PropertyAccessors` methods, in * many cases to maintain guarantees provided by the Polymer 1.x features; * notably it changes property accessors to be synchronous by default * whereas the default when using `PropertyAccessors` standalone is to be * async by default. * * @mixinFunction * @polymer * @appliesMixin Polymer.TemplateStamp * @appliesMixin Polymer.PropertyAccessors * @memberof Polymer * @summary Element class mixin that provides meta-programming for Polymer's * template binding and data observation system. */ Polymer.PropertyEffects = Polymer.dedupingMixin(superClass => { /** * @constructor * @extends {superClass} * @implements {Polymer_PropertyAccessors} * @implements {Polymer_TemplateStamp} * @unrestricted */ const propertyEffectsBase = Polymer.TemplateStamp(Polymer.PropertyAccessors(superClass)); /** * @polymer * @mixinClass * @implements {Polymer_PropertyEffects} * @extends {propertyEffectsBase} * @unrestricted */ class PropertyEffects extends propertyEffectsBase { constructor() { super(); /** @type {boolean} */ this.__dataClientsReady; /** @type {Array} */ this.__dataPendingClients; /** @type {Object} */ this.__dataToNotify; /** @type {Object} */ this.__dataLinkedPaths; /** @type {boolean} */ this.__dataHasPaths; /** @type {Object} */ this.__dataCompoundStorage; /** @type {Polymer_PropertyEffects} */ this.__dataHost; /** @type {!Object} */ this.__dataTemp; /** @type {boolean} */ this.__dataClientsInitialized; /** @type {!Object} */ this.__data; /** @type {!Object} */ this.__dataPending; /** @type {!Object} */ this.__dataOld; /** @type {Object} */ this.__computeEffects; /** @type {Object} */ this.__reflectEffects; /** @type {Object} */ this.__notifyEffects; /** @type {Object} */ this.__propagateEffects; /** @type {Object} */ this.__observeEffects; /** @type {Object} */ this.__readOnly; /** @type {number} */ this.__dataCounter; /** @type {!TemplateInfo} */ this.__templateInfo; } get PROPERTY_EFFECT_TYPES() { return TYPES; } _initializeProperties() { super._initializeProperties(); hostStack.registerHost(this); this.__dataClientsReady = false; this.__dataPendingClients = null; this.__dataToNotify = null; this.__dataLinkedPaths = null; this.__dataHasPaths = false; // May be set on instance prior to upgrade this.__dataCompoundStorage = this.__dataCompoundStorage || null; this.__dataHost = this.__dataHost || null; this.__dataTemp = {}; this.__dataClientsInitialized = false; } /** * Overrides `Polymer.PropertyAccessors` implementation to provide a * more efficient implementation of initializing properties from * the prototype on the instance. * * @override * @param {Object} props Properties to initialize on the prototype */ _initializeProtoProperties(props) { this.__data = Object.create(props); this.__dataPending = Object.create(props); this.__dataOld = {}; } /** * Overrides `Polymer.PropertyAccessors` implementation to avoid setting * `_setProperty`'s `shouldNotify: true`. * * @override * @param {Object} props Properties to initialize on the instance */ _initializeInstanceProperties(props) { let readOnly = this[TYPES.READ_ONLY]; for (let prop in props) { if (!readOnly || !readOnly[prop]) { this.__dataPending = this.__dataPending || {}; this.__dataOld = this.__dataOld || {}; this.__data[prop] = this.__dataPending[prop] = props[prop]; } } } // Prototype setup ---------------------------------------- /** * Equivalent to static `addPropertyEffect` API but can be called on * an instance to add effects at runtime. See that method for * full API docs. * * @param {string} property Property that should trigger the effect * @param {string} type Effect type, from this.PROPERTY_EFFECT_TYPES * @param {Object=} effect Effect metadata object * @return {void} * @protected */ _addPropertyEffect(property, type, effect) { this._createPropertyAccessor(property, type == TYPES.READ_ONLY); // effects are accumulated into arrays per property based on type let effects = ensureOwnEffectMap(this, type)[property]; if (!effects) { effects = this[type][property] = []; } effects.push(effect); } /** * Removes the given property effect. * * @param {string} property Property the effect was associated with * @param {string} type Effect type, from this.PROPERTY_EFFECT_TYPES * @param {Object=} effect Effect metadata object to remove * @return {void} */ _removePropertyEffect(property, type, effect) { let effects = ensureOwnEffectMap(this, type)[property]; let idx = effects.indexOf(effect); if (idx >= 0) { effects.splice(idx, 1); } } /** * Returns whether the current prototype/instance has a property effect * of a certain type. * * @param {string} property Property name * @param {string=} type Effect type, from this.PROPERTY_EFFECT_TYPES * @return {boolean} True if the prototype/instance has an effect of this type * @protected */ _hasPropertyEffect(property, type) { let effects = this[type]; return Boolean(effects && effects[property]); } /** * Returns whether the current prototype/instance has a "read only" * accessor for the given property. * * @param {string} property Property name * @return {boolean} True if the prototype/instance has an effect of this type * @protected */ _hasReadOnlyEffect(property) { return this._hasPropertyEffect(property, TYPES.READ_ONLY); } /** * Returns whether the current prototype/instance has a "notify" * property effect for the given property. * * @param {string} property Property name * @return {boolean} True if the prototype/instance has an effect of this type * @protected */ _hasNotifyEffect(property) { return this._hasPropertyEffect(property, TYPES.NOTIFY); } /** * Returns whether the current prototype/instance has a "reflect to attribute" * property effect for the given property. * * @param {string} property Property name * @return {boolean} True if the prototype/instance has an effect of this type * @protected */ _hasReflectEffect(property) { return this._hasPropertyEffect(property, TYPES.REFLECT); } /** * Returns whether the current prototype/instance has a "computed" * property effect for the given property. * * @param {string} property Property name * @return {boolean} True if the prototype/instance has an effect of this type * @protected */ _hasComputedEffect(property) { return this._hasPropertyEffect(property, TYPES.COMPUTE); } // Runtime ---------------------------------------- /** * Sets a pending property or path. If the root property of the path in * question had no accessor, the path is set, otherwise it is enqueued * via `_setPendingProperty`. * * This function isolates relatively expensive functionality necessary * for the public API (`set`, `setProperties`, `notifyPath`, and property * change listeners via {{...}} bindings), such that it is only done * when paths enter the system, and not at every propagation step. It * also sets a `__dataHasPaths` flag on the instance which is used to * fast-path slower path-matching code in the property effects host paths. * * `path` can be a path string or array of path parts as accepted by the * public API. * * @param {string | !Array<number|string>} path Path to set * @param {*} value Value to set * @param {boolean=} shouldNotify Set to true if this change should * cause a property notification event dispatch * @param {boolean=} isPathNotification If the path being set is a path * notification of an already changed value, as opposed to a request * to set and notify the change. In the latter `false` case, a dirty * check is performed and then the value is set to the path before * enqueuing the pending property change. * @return {boolean} Returns true if the property/path was enqueued in * the pending changes bag. * @protected */ _setPendingPropertyOrPath(path, value, shouldNotify, isPathNotification) { if (isPathNotification || Polymer.Path.root(Array.isArray(path) ? path[0] : path) !== path) { // Dirty check changes being set to a path against the actual object, // since this is the entry point for paths into the system; from here // the only dirty checks are against the `__dataTemp` cache to prevent // duplicate work in the same turn only. Note, if this was a notification // of a change already set to a path (isPathNotification: true), // we always let the change through and skip the `set` since it was // already dirty checked at the point of entry and the underlying // object has already been updated if (!isPathNotification) { let old = Polymer.Path.get(this, path); path = /** @type {string} */ (Polymer.Path.set(this, path, value)); // Use property-accessor's simpler dirty check if (!path || !super._shouldPropertyChange(path, value, old)) { return false; } } this.__dataHasPaths = true; if (this._setPendingProperty(/**@type{string}*/(path), value, shouldNotify)) { computeLinkedPaths(this, path, value); return true; } } else { if (this.__dataHasAccessor && this.__dataHasAccessor[path]) { return this._setPendingProperty(/**@type{string}*/(path), value, shouldNotify); } else { this[path] = value; } } return false; } /** * Applies a value to a non-Polymer element/node's property. * * The implementation makes a best-effort at binding interop: * Some native element properties have side-effects when * re-setting the same value (e.g. setting `<input>.value` resets the * cursor position), so we do a dirty-check before setting the value. * However, for better interop with non-Polymer custom elements that * accept objects, we explicitly re-set object changes coming from the * Polymer world (which may include deep object changes without the * top reference changing), erring on the side of providing more * information. * * Users may override this method to provide alternate approaches. * * @param {Node} node The node to set a property on * @param {string} prop The property to set * @param {*} value The value to set * @return {void} * @protected */ _setUnmanagedPropertyToNode(node, prop, value) { // It is a judgment call that resetting primitives is // "bad" and resettings objects is also "good"; alternatively we could // implement a whitelist of tag & property values that should never // be reset (e.g. <input>.value && <select>.value) if (value !== node[prop] || typeof value == 'object') { node[prop] = value; } } /** * Overrides the `PropertyAccessors` implementation to introduce special * dirty check logic depending on the property & value being set: * * 1. Any value set to a path (e.g. 'obj.prop': 42 or 'obj.prop': {...}) * Stored in `__dataTemp`, dirty checked against `__dataTemp` * 2. Object set to simple property (e.g. 'prop': {...}) * Stored in `__dataTemp` and `__data`, dirty checked against * `__dataTemp` by default implementation of `_shouldPropertyChange` * 3. Primitive value set to simple property (e.g. 'prop': 42) * Stored in `__data`, dirty checked against `__data` * * The dirty-check is important to prevent cycles due to two-way * notification, but paths and objects are only dirty checked against any * previous value set during this turn via a "temporary cache" that is * cleared when the last `_propertiesChanged` exits. This is so: * a. any cached array paths (e.g. 'array.3.prop') may be invalidated * due to array mutations like shift/unshift/splice; this is fine * since path changes are dirty-checked at user entry points like `set` * b. dirty-checking for objects only lasts one turn to allow the user * to mutate the object in-place and re-set it with the same identity * and have all sub-properties re-propagated in a subsequent turn. * * The temp cache is not necessarily sufficient to prevent invalid array * paths, since a splice can happen during the same turn (with pathological * user code); we could introduce a "fixup" for temporarily cached array * paths if needed: https://github.com/Polymer/polymer/issues/4227 * * @param {string} property Name of the property * @param {*} value Value to set * @param {boolean=} shouldNotify True if property should fire notification * event (applies only for `notify: true` properties) * @return {boolean} Returns true if the property changed * @override */ _setPendingProperty(property, value, shouldNotify) { let isPath = this.__dataHasPaths && Polymer.Path.isPath(property); let prevProps = isPath ? this.__dataTemp : this.__data; if (this._shouldPropertyChange(property, value, prevProps[property])) { if (!this.__dataPending) { this.__dataPending = {}; this.__dataOld = {}; } // Ensure old is captured from the last turn if (!(property in this.__dataOld)) { this.__dataOld[property] = this.__data[property]; } // Paths are stored in temporary cache (cleared at end of turn), // which is used for dirty-checking, all others stored in __data if (isPath) { this.__dataTemp[property] = value; } else { this.__data[property] = value; } // All changes go into pending property bag, passed to _propertiesChanged this.__dataPending[property] = value; // Track properties that should notify separately if (isPath || (this[TYPES.NOTIFY] && this[TYPES.NOTIFY][property])) { this.__dataToNotify = this.__dataToNotify || {}; this.__dataToNotify[property] = shouldNotify; } return true; } return false; } /** * Overrides base implementation to ensure all accessors set `shouldNotify` * to true, for per-property notification tracking. * * @override */ _setProperty(property, value) { if (this._setPendingProperty(property, value, true)) { this._invalidateProperties(); } } /** * Overrides `PropertyAccessor`'s default async queuing of * `_propertiesChanged`: if `__dataReady` is false (has not yet been * manually flushed), the function no-ops; otherwise flushes * `_propertiesChanged` synchronously. * * @override */ _invalidateProperties() { if (this.__dataReady) { this._flushProperties(); } } /** * Enqueues the given client on a list of pending clients, whose * pending property changes can later be flushed via a call to * `_flushClients`. * * @param {Object} client PropertyEffects client to enqueue * @return {void} * @protected */ _enqueueClient(client) { this.__dataPendingClients = this.__dataPendingClients || []; if (client !== this) { this.__dataPendingClients.push(client); } } /** * Flushes any clients previously enqueued via `_enqueueClient`, causing * their `_flushProperties` method to run. * * @return {void} * @protected */ _flushClients() { if (!this.__dataClientsReady) { this.__dataClientsReady = true; this._readyClients(); // Override point where accessors are turned on; importantly, // this is after clients have fully readied, providing a guarantee // that any property effects occur only after all clients are ready. this.__dataReady = true; } else { this.__enableOrFlushClients(); } } // NOTE: We ensure clients either enable or flush as appropriate. This // handles two corner cases: // (1) clients flush properly when connected/enabled before the host // enables; e.g. // (a) Templatize stamps with no properties and does not flush and // (b) the instance is inserted into dom and // (c) then the instance flushes. // (2) clients enable properly when not connected/enabled when the host // flushes; e.g. // (a) a template is runtime stamped and not yet connected/enabled // (b) a host sets a property, causing stamped dom to flush // (c) the stamped dom enables. __enableOrFlushClients() { let clients = this.__dataPendingClients; if (clients) { this.__dataPendingClients = null; for (let i=0; i < clients.length; i++) { let client = clients[i]; if (!client.__dataEnabled) { client._enableProperties(); } else if (client.__dataPending) { client._flushProperties(); } } } } /** * Perform any initial setup on client dom. Called before the first * `_flushProperties` call on client dom and before any element * observers are called. * * @return {void} * @protected */ _readyClients() { this.__enableOrFlushClients(); } /** * Sets a bag of property changes to this instance, and * synchronously processes all effects of the properties as a batch. * * Property names must be simple properties, not paths. Batched * path propagation is not supported. * * @param {Object} props Bag of one or more key-value pairs whose key is * a property and value is the new value to set for that property. * @param {boolean=} setReadOnly When true, any private values set in * `props` will be set. By default, `setProperties` will not set * `readOnly: true` root properties. * @return {void} * @public */ setProperties(props, setReadOnly) { for (let path in props) { if (setReadOnly || !this[TYPES.READ_ONLY] || !this[TYPES.READ_ONLY][path]) { //TODO(kschaaf): explicitly disallow paths in setProperty? // wildcard observers currently only pass the first changed path // in the `info` object, and you could do some odd things batching // paths, e.g. {'foo.bar': {...}, 'foo': null} this._setPendingPropertyOrPath(path, props[path], true); } } this._invalidateProperties(); } /** * Overrides `PropertyAccessors` so that property accessor * side effects are not enabled until after client dom is fully ready. * Also calls `_flushClients` callback to ensure client dom is enabled * that was not enabled as a result of flushing properties. * * @override */ ready() { // It is important that `super.ready()` is not called here as it // immediately turns on accessors. Instead, we wait until `readyClients` // to enable accessors to provide a guarantee that clients are ready // before processing any accessors side effects. this._flushProperties(); // If no data was pending, `_flushProperties` will not `flushClients` // so ensure this is done. if (!this.__dataClientsReady) { this._flushClients(); } // Before ready, client notifications do not trigger _flushProperties. // Therefore a flush is necessary here if data has been set. if (this.__dataPending) { this._flushProperties(); } } /** * Implements `PropertyAccessors`'s properties changed callback. * * Runs each class of effects for the batch of changed properties in * a specific order (compute, propagate, reflect, observe, notify). * * @override */ _propertiesChanged(currentProps, changedProps, oldProps) { // ---------------------------- // let c = Object.getOwnPropertyNames(changedProps || {}); // window.debug && console.group(this.localName + '#' + this.id + ': ' + c); // if (window.debug) { debugger; } // ---------------------------- let hasPaths = this.__dataHasPaths; this.__dataHasPaths = false; // Compute properties runComputedEffects(this, changedProps, oldProps, hasPaths); // Clear notify properties prior to possible reentry (propagate, observe), // but after computing effects have a chance to add to them let notifyProps = this.__dataToNotify; this.__dataToNotify = null; // Propagate properties to clients this._propagatePropertyChanges(changedProps, oldProps, hasPaths); // Flush clients this._flushClients(); // Reflect properties runEffects(this, this[TYPES.REFLECT], changedProps, oldProps, hasPaths); // Observe properties runEffects(this, this[TYPES.OBSERVE], changedProps, oldProps, hasPaths); // Notify properties to host if (notifyProps) { runNotifyEffects(this, notifyProps, changedProps, oldProps, hasPaths); } // Clear temporary cache at end of turn if (this.__dataCounter == 1) { this.__dataTemp = {}; } // ---------------------------- // window.debug && console.groupEnd(this.localName + '#' + this.id + ': ' + c); // ---------------------------- } /** * Called to propagate any property changes to stamped template nodes * managed by this element. * * @param {Object} changedProps Bag of changed properties * @param {Object} oldProps Bag of previous values for changed properties * @param {boolean} hasPaths True with `props` contains one or more paths * @return {void} * @protected */ _propagatePropertyChanges(changedProps, oldProps, hasPaths) { if (this[TYPES.PROPAGATE]) { runEffects(this, this[TYPES.PROPAGATE], changedProps, oldProps, hasPaths); } let templateInfo = this.__templateInfo; while (templateInfo) { runEffects(this, templateInfo.propertyEffects, changedProps, oldProps, hasPaths, templateInfo.nodeList); templateInfo = templateInfo.nextTemplateInfo; } } /** * Aliases one data path as another, such that path notifications from one * are routed to the other. * * @param {string | !Array<string|number>} to Target path to link. * @param {string | !Array<string|number>} from Source path to link. * @return {void} * @public */ linkPaths(to, from) { to = Polymer.Path.normalize(to); from = Polymer.Path.normalize(from); this.__dataLinkedPaths = this.__dataLinkedPaths || {}; this.__dataLinkedPaths[to] = from; } /** * Removes a data path alias previously established with `_linkPaths`. * * Note, the path to unlink should be the target (`to`) used when * linking the paths. * * @param {string | !Array<string|number>} path Target path to unlink. * @return {void} * @public */ unlinkPaths(path) { path = Polymer.Path.normalize(path); if (this.__dataLinkedPaths) { delete this.__dataLinkedPaths[path]; } } /** * Notify that an array has changed. * * Example: * * this.items = [ {name: 'Jim'}, {name: 'Todd'}, {name: 'Bill'} ]; * ... * this.items.splice(1, 1, {name: 'Sam'}); * this.items.push({name: 'Bob'}); * this.notifySplices('items', [ * { index: 1, removed: [{name: 'Todd'}], addedCount: 1, object: this.items, type: 'splice' }, * { index: 3, removed: [], addedCount: 1, object: this.items, type: 'splice'} * ]); * * @param {string} path Path that should be notified. * @param {Array} splices Array of splice records indicating ordered * changes that occurred to the array. Each record should have the * following fields: * * index: index at which the change occurred * * removed: array of items that were removed from this index * * addedCount: number of new items added at this index * * object: a reference to the array in question * * type: the string literal 'splice' * * Note that splice records _must_ be normalized such that they are * reported in index order (raw results from `Object.observe` are not * ordered and must be normalized/merged before notifying). * @return {void} * @public */ notifySplices(path, splices) { let info = {path: ''}; let array = /** @type {Array} */(Polymer.Path.get(this, path, info)); notifySplices(this, array, info.path, splices); } /** * Convenience method for reading a value from a path. * * Note, if any part in the path is undefined, this method returns * `undefined` (this method does not throw when dereferencing undefined * paths). * * @param {(string|!Array<(string|number)>)} path Path to the value * to read. The path may be specified as a string (e.g. `foo.bar.baz`) * or an array of path parts (e.g. `['foo.bar', 'baz']`). Note that * bracketed expressions are not supported; string-based path parts * *must* be separated by dots. Note that when dereferencing array * indices, the index may be used as a dotted part directly * (e.g. `users.12.name` or `['users', 12, 'name']`). * @param {Object=} root Root object from which the path is evaluated. * @return {*} Value at the path, or `undefined` if any part of the path * is undefined. * @public */ get(path, root) { return Polymer.Path.get(root || this, path); } /** * Convenience method for setting a value to a path and notifying any * elements bound to the same path. * * Note, if any part in the path except for the last is undefined, * this method does nothing (this method does not throw when * dereferencing undefined paths). * * @param {(string|!Array<(string|number)>)} path Path to the value * to write. The path may be specified as a string (e.g. `'foo.bar.baz'`) * or an array of path parts (e.g. `['foo.bar', 'baz']`). Note that * bracketed expressions are not supported; string-based path parts * *must* be separated by dots. Note that when dereferencing array * indices, the index may be used as a dotted part directly * (e.g. `'users.12.name'` or `['users', 12, 'name']`). * @param {*} value Value to set at the specified path. * @param {Object=} root Root object from which the path is evaluated. * When specified, no notification will occur. * @return {void} * @public */ set(path, value, root) { if (root) { Polymer.Path.set(root, path, value); } else { if (!this[TYPES.READ_ONLY] || !this[TYPES.READ_ONLY][/** @type {string} */(path)]) { if (this._setPendingPropertyOrPath(path, value, true)) { this._invalidateProperties(); } } } } /** * Adds items onto the end of the array at the path specified. * * The arguments after `path` and return value match that of * `Array.prototype.push`. * * This method notifies other paths to the same array that a * splice occurred to the array. * * @param {string | !Array<string|number>} path Path to array. * @param {...*} items Items to push onto array * @return {number} New length of the array. * @public */ push(path, ...items) { let info = {path: ''}; let array = /** @type {Array}*/(Polymer.Path.get(this, path, info)); let len = array.length; let ret = array.push(...items); if (items.length) { notifySplice(this, array, info.path, len, items.length, []); } return ret; } /** * Removes an item from the end of array at the path specified. * * The arguments after `path` and return value match that of * `Array.prototype.pop`. * * This method notifies other paths to the same array that a * splice occurred to the array. * * @param {string | !Array<string|number>} path Path to array. * @return {*} Item that was removed. * @public */ pop(path) { let info = {path: ''}; let array = /** @type {Array} */(Polymer.Path.get(this, path, info)); let hadLength = Boolean(array.length); let ret = array.pop(); if (hadLength) { notifySplice(this, array, info.path, array.length, 0, [ret]); } return ret; } /** * Starting from the start index specified, removes 0 or more items * from the array and inserts 0 or more new items in their place. * * The arguments after `path` and return value match that of * `Array.prototype.splice`. * * This method notifies other paths to the same array that a * splice occurred to the array. * * @param {string | !Array<string|number>} path Path to array. * @param {number} start Index from which to start removing/inserting. * @param {number} deleteCount Number of items to remove. * @param {...*} items Items to insert into array. * @return {Array} Array of removed items. * @public */ splice(path, start, deleteCount, ...items) { let info = {path : ''}; let array = /** @type {Array} */(Polymer.Path.get(this, path, info)); // Normalize fancy native splice handling of crazy start values if (start < 0) { start = array.length - Math.floor(-start); } else { start = Math.floor(start); } if (!start) { start = 0; } let ret = array.splice(start, deleteCount, ...items); if (items.length || ret.length) { notifySplice(this, array, info.path, start, items.length, ret); } return ret; } /** * Removes an item from the beginning of array at the path specified. * * The arguments after `path` and return value match that of * `Array.prototype.pop`. * * This method notifies other paths to the same array that a * splice occurred to the array. * * @param {string | !Array<string|number>} path Path to array. * @return {*} Item that was removed. * @public */ shift(path) { let info = {path: ''}; let array = /** @type {Array} */(Polymer.Path.get(this, path, info)); let hadLength = Boolean(array.length); let ret = array.shift(); if (hadLength) { notifySplice(this, array, info.path, 0, 0, [ret]); } return ret; } /** * Adds items onto the beginning of the array at the path specified. * * The arguments after `path` and return value match that of * `Array.prototype.push`. * * This method notifies other paths to the same array that a * splice occurred to the array. * * @param {string | !Array<string|number>} path Path to array. * @param {...*} items Items to insert info array * @return {number} New length of the array. * @public */ unshift(path, ...items) { let info = {path: ''}; let array = /** @type {Array} */(Polymer.Path.get(this, path, info)); let ret = array.unshift(...items); if (items.length) { notifySplice(this, array, info.path, 0, items.length, []); } return ret; } /** * Notify that a path has changed. * * Example: * * this.item.user.name = 'Bob'; * this.notifyPath('item.user.name'); * * @param {string} path Path that should be notified. * @param {*=} value Value at the path (optional). * @return {void} * @public */ notifyPath(path, value) { /** @type {string} */ let propPath; if (arguments.length == 1) { // Get value if not supplied let info = {path: ''}; value = Polymer.Path.get(this, path, info); propPath = info.path; } else if (Array.isArray(path)) { // Normalize path if needed propPath = Polymer.Path.normalize(path); } else { propPath = /** @type{string} */(path); } if (this._setPendingPropertyOrPath(propPath, value, true, true)) { this._invalidateProperties(); } } /** * Equivalent to static `createReadOnlyProperty` API but can be called on * an instance to add effects at runtime. See that method for * full API docs. * * @param {string} property Property name * @param {boolean=} protectedSetter Creates a custom protected setter * when `true`. * @return {void} * @protected */ _createReadOnlyProperty(property, protectedSetter) { this._addPropertyEffect(property, TYPES.READ_ONLY); if (protectedSetter) { this['_set' + upper(property)] = /** @this {PropertyEffects} */function(value) { this._setProperty(property, value); }; } } /** * Equivalent to static `createPropertyObserver` API but can be called on * an instance to add effects at runtime. See that method for * full API docs. * * @param {string} property Property name * @param {string|function(*,*)} method Function or name of observer method to call * @param {boolean=} dynamicFn Whether the method name should be included as * a dependency to the effect. * @return {void} * @protected */ _createPropertyObserver(property, method, dynamicFn) { let info = { property, method, dynamicFn: Boolean(dynamicFn) }; this._addPropertyEffect(property, TYPES.OBSERVE, { fn: runObserverEffect, info, trigger: {name: property} }); if (dynamicFn) { this._addPropertyEffect(method, TYPES.OBSERVE, { fn: runObserverEffect, info, trigger: {name: method} }); } } /** * Equivalent to static `createMethodObserver` API but can be called on * an instance to add effects at runtime. See that method for * full API docs. * * @param {string} expression Method expression * @param {boolean|Object=} dynamicFn Boolean or object map indicating * whether method names should be included as a dependency to the effect. * @return {void} * @protected */ _createMethodObserver(expression, dynamicFn) { let sig = parseMethod(expression); if (!sig) { throw new Error("Malformed observer expression '" + expression + "'"); } createMethodEffect(this, sig, TYPES.OBSERVE, runMethodEffect, null, dynamicFn); } /** * Equivalent to static `createNotifyingProperty` API but can be called on * an instance to add effects at runtime. See that method for * full API docs. * * @param {string} property Property name * @return {void} * @protected */ _createNotifyingProperty(property) { this._addPropertyEffect(property, TYPES.NOTIFY, { fn: runNotifyEffect, info: { eventName: CaseMap.camelToDashCase(property) + '-changed', property: property } }); } /** * Equivalent to static `createReflectedProperty` API but can be called on * an instance to add effects at runtime. See that method for * full API docs. * * @param {string} property Property name * @return {void} * @protected */ _createReflectedProperty(property) { let attr = CaseMap.camelToDashCase(property); if (attr[0] === '-') { console.warn('Property ' + property + ' cannot be reflected to attribute ' + attr + ' because "-" is not a valid starting attribute name. Use a lowercase first letter for the property instead.'); } else { this._addPropertyEffect(property, TYPES.REFLECT, { fn: runReflectEffect, info: { attrName: attr } }); } } /** * Equivalent to static `createComputedProperty` API but can be called on * an instance to add effects at runtime. See that method for * full API docs. * * @param {string} property Name of computed property to set * @param {string} expression Method expression * @param {boolean|Object=} dynamicFn Boolean or object map indicating * whether method names should be included as a dependency to the effect. * @return {void} * @protected */ _createComputedProperty(property, expression, dynamicFn) { let sig = parseMethod(expression); if (!sig) { throw new Error("Malformed computed expression '" + expression + "'"); } createMethodEffect(this, sig, TYPES.COMPUTE, runComputedEffect, property, dynamicFn); } // -- static class methods ------------ /** * Ensures an accessor exists for the specified property, and adds * to a list of "property effects" that will run when the accessor for * the specified property is set. Effects are grouped by "type", which * roughly corresponds to a phase in effect processing. The effect * metadata should be in the following form: * * { * fn: effectFunction, // Reference to function to call to perform effect * info: { ... } // Effect metadata passed to function * trigger: { // Optional triggering metadata; if not provided * name: string // the property is treated as a wildcard * structured: boolean * wildcard: boolean * } * } * * Effects are called from `_propertiesChanged` in the following order by * type: * * 1. COMPUTE * 2. PROPAGATE * 3. REFLECT * 4. OBSERVE * 5. NOTIFY * * Effect functions are called with the following signature: * * effectFunction(inst, path, props, oldProps, info, hasPaths) * * @param {string} property Property that should trigger the effect * @param {string} type Effect type, from this.PROPERTY_EFFECT_TYPES * @param {Object=} effect Effect metadata object * @return {void} * @protected */ static addPropertyEffect(property, type, effect) { this.prototype._addPropertyEffect(property, type, effect); } /** * Creates a single-property observer for the given property. * * @param {string} property Property name * @param {string|function(*,*)} method Function or name of observer method to call * @param {boolean=} dynamicFn Whether the method name should be included as * a dependency to the effect. * @return {void} * @protected */ static createPropertyObserver(property, method, dynamicFn) { this.prototype._createPropertyObserver(property, method, dynamicFn); } /** * Creates a multi-property "method observer" based on the provided * expression, which should be a string in the form of a normal JavaScript * function signature: `'methodName(arg1, [..., argn])'`. Each argument * should correspond to a property or path in the context of this * prototype (or instance), or may be a literal string or number. * * @param {string} expression Method expression * @param {boolean|Object=} dynamicFn Boolean or object map indicating * @return {void} * whether method names should be included as a dependency to the effect. * @protected */ static createMethodObserver(expression, dynamicFn) { this.prototype._createMethodObserver(expression, dynamicFn); } /** * Causes the setter for the given property to dispatch `<property>-changed` * events to notify of changes to the property. * * @param {string} property Property name * @return {void} * @protected */ static createNotifyingProperty(property) { this.prototype._createNotifyingProperty(property); } /** * Creates a read-only accessor for the given property. * * To set the property, use the protected `_setProperty` API. * To create a custom protected setter (e.g. `_setMyProp()` for * property `myProp`), pass `true` for `protectedSetter`. * * Note, if the property will have other property effects, this method * should be called first, before adding other effects. * * @param {string} property Property name * @param {boolean=} protectedSetter Creates a custom protected setter * when `true`. * @return {void} * @protected */ static createReadOnlyProperty(property, protectedSetter) { this.prototype._createReadOnlyProperty(property, protectedSetter); } /** * Causes the setter for the given property to reflect the property value * to a (dash-cased) attribute of the same name. * * @param {string} property Property name * @return {void} * @protected */ static createReflectedProperty(property) { this.prototype._createReflectedProperty(property); } /** * Creates a computed property whose value is set to the result of the * method described by the given `expression` each time one or more * arguments to the method changes. The expression should be a string * in the form of a normal JavaScript function signature: * `'methodName(arg1, [..., argn])'` * * @param {string} property Name of computed property to set * @param {string} expression Method expression * @param {boolean|Object=} dynamicFn Boolean or object map indicating whether * method names should be included as a dependency to the effect. * @return {void} * @protected */ static createComputedProperty(property, expression, dynamicFn) { this.prototype._createComputedProperty(property, expression, dynamicFn); } /** * Parses the provided template to ensure binding effects are created * for them, and then ensures property accessors are created for any * dependent properties in the template. Binding effects for bound * templates are stored in a linked list on the instance so that * templates can be efficiently stamped and unstamped. * * @param {HTMLTemplateElement} template Template containing binding * bindings * @return {Object} Template metadata object * @protected */ static bindTemplate(template) { return this.prototype._bindTemplate(template); } // -- binding ---------------------------------------------- /** * Equivalent to static `bindTemplate` API but can be called on * an instance to add effects at runtime. See that method for * full API docs. * * This method may be called on the prototype (for prototypical template * binding, to avoid creating accessors every instance) once per prototype, * and will be called with `runtimeBinding: true` by `_stampTemplate` to * create and link an instance of the template metadata associated with a * particular stamping. * * @param {HTMLTemplateElement} template Template containing binding * bindings * @param {boolean=} instanceBinding When false (default), performs * "prototypical" binding of the template and overwrites any previously * bound template for the class. When true (as passed from * `_stampTemplate`), the template info is instanced and linked into * the list of bound templates. * @return {!TemplateInfo} Template metadata object; for `runtimeBinding`, * this is an instance of the prototypical template info * @protected */ _bindTemplate(template, instanceBinding) { let templateInfo = this.constructor._parseTemplate(template); let wasPreBound = this.__templateInfo == templateInfo; // Optimization: since this is called twice for proto-bound templates, // don't attempt to recreate accessors if this template was pre-bound if (!wasPreBound) { for (let prop in templateInfo.propertyEffects) { this._createPropertyAccessor(prop); } } if (instanceBinding) { // For instance-time binding, create instance of template metadata // and link into list of templates if necessary templateInfo = /** @type {!TemplateInfo} */(Object.create(templateInfo)); templateInfo.wasPreBound = wasPreBound; if (!wasPreBound && this.__templateInfo) { let last = this.__templateInfoLast || this.__templateInfo; this.__templateInfoLast = last.nextTemplateInfo = templateInfo; templateInfo.previousTemplateInfo = last; return templateInfo; } } return this.__templateInfo = templateInfo; } /** * Adds a property effect to the given template metadata, which is run * at the "propagate" stage of `_propertiesChanged` when the template * has been bound to the element via `_bindTemplate`. * * The `effect` object should match the format in `_addPropertyEffect`. * * @param {Object} templateInfo Template metadata to add effect to * @param {string} prop Property that should trigger the effect * @param {Object=} effect Effect metadata object * @return {void} * @protected */ static _addTemplatePropertyEffect(templateInfo, prop, effect) { let hostProps = templateInfo.hostProps = templateInfo.hostProps || {}; hostProps[prop] = true; let effects = templateInfo.propertyEffects = templateInfo.propertyEffects || {}; let propEffects = effects[prop] = effects[prop] || []; propEffects.push(effect); } /** * Stamps the provided template and performs instance-time setup for * Polymer template features, including data bindings, declarative event * listeners, and the `this.$` map of `id`'s to nodes. A document fragment * is returned containing the stamped DOM, ready for insertion into the * DOM. * * This method may be called more than once; however note that due to * `shadycss` polyfill limitations, only styles from templates prepared * using `ShadyCSS.prepareTemplate` will be correctly polyfilled (scoped * to the shadow root and support CSS custom properties), and note that * `ShadyCSS.prepareTemplate` may only be called once per element. As such, * any styles required by in runtime-stamped templates must be included * in the main element template. * * @param {!HTMLTemplateElement} template Template to stamp * @return {!StampedTemplate} Cloned template content * @override * @protected */ _stampTemplate(template) { // Ensures that created dom is `_enqueueClient`'d to this element so // that it can be flushed on next call to `_flushProperties` hostStack.beginHosting(this); let dom = super._stampTemplate(template); hostStack.endHosting(this); let templateInfo = /** @type {!TemplateInfo} */(this._bindTemplate(template, true)); // Add template-instance-specific data to instanced templateInfo templateInfo.nodeList = dom.nodeList; // Capture child nodes to allow unstamping of non-prototypical templates if (!templateInfo.wasPreBound) { let nodes = templateInfo.childNodes = []; for (let n=dom.firstChild; n; n=n.nextSibling) { nodes.push(n); } } dom.templateInfo = templateInfo; // Setup compound storage, 2-way listeners, and dataHost for bindings setupBindings(this, templateInfo); // Flush properties into template nodes if already booted if (this.__dataReady) { runEffects(this, templateInfo.propertyEffects, this.__data, null, false, templateInfo.nodeList); } return dom; } /** * Removes and unbinds the nodes previously contained in the provided * DocumentFragment returned from `_stampTemplate`. * * @param {!StampedTemplate} dom DocumentFragment previously returned * from `_stampTemplate` associated with the nodes to be removed * @return {void} * @protected */ _removeBoundDom(dom) { // Unlink template info let templateInfo = dom.templateInfo; if (templateInfo.previousTemplateInfo) { templateInfo.previousTemplateInfo.nextTemplateInfo = templateInfo.nextTemplateInfo; } if (templateInfo.nextTemplateInfo) { templateInfo.nextTemplateInfo.previousTemplateInfo = templateInfo.previousTemplateInfo; } if (this.__templateInfoLast == templateInfo) { this.__templateInfoLast = templateInfo.previousTemplateInfo; } templateInfo.previousTemplateInfo = templateInfo.nextTemplateInfo = null; // Remove stamped nodes let nodes = templateInfo.childNodes; for (let i=0; i<nodes.length; i++) { let node = nodes[i]; node.parentNode.removeChild(node); } } /** * Overrides default `TemplateStamp` implementation to add support for * parsing bindings from `TextNode`'s' `textContent`. A `bindings` * array is added to `nodeInfo` and populated with binding metadata * with information capturing the binding target, and a `parts` array * with one or more metadata objects capturing the source(s) of the * binding. * * @override * @param {Node} node Node to parse * @param {TemplateInfo} templateInfo Template metadata for current template * @param {NodeInfo} nodeInfo Node metadata for current template node * @return {boolean} `true` if the visited node added node-specific * metadata to `nodeInfo` * @protected * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do */ static _parseTemplateNode(node, templateInfo, nodeInfo) { let noted = super._parseTemplateNode(node, templateInfo, nodeInfo); if (node.nodeType === Node.TEXT_NODE) { let parts = this._parseBindings(node.textContent, templateInfo); if (parts) { // Initialize the textContent with any literal parts // NOTE: default to a space here so the textNode remains; some browsers // (IE) omit an empty textNode following cloneNode/importNode. node.textContent = literalFromParts(parts) || ' '; addBinding(this, templateInfo, nodeInfo, 'text', 'textContent', parts); noted = true; } } return noted; } /** * Overrides default `TemplateStamp` implementation to add support for * parsing bindings from attributes. A `bindings` * array is added to `nodeInfo` and populated with binding metadata * with information capturing the binding target, and a `parts` array * with one or more metadata objects capturing the source(s) of the * binding. * * @override * @param {Element} node Node to parse * @param {TemplateInfo} templateInfo Template metadata for current template * @param {NodeInfo} nodeInfo Node metadata for current template node * @param {string} name Attribute name * @param {string} value Attribute value * @return {boolean} `true` if the visited node added node-specific * metadata to `nodeInfo` * @protected * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do */ static _parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value) { let parts = this._parseBindings(value, templateInfo); if (parts) { // Attribute or property let origName = name; let kind = 'property'; if (name[name.length-1] == '$') { name = name.slice(0, -1); kind = 'attribute'; } // Initialize attribute bindings with any literal parts let literal = literalFromParts(parts); if (literal && kind == 'attribute') { node.setAttribute(name, literal); } // Clear attribute before removing, since IE won't allow removing // `value` attribute if it previously had a value (can't // unconditionally set '' before removing since attributes with `$` // can't be set using setAttribute) if (node.localName === 'input' && origName === 'value') { node.setAttribute(origName, ''); } // Remove annotation node.removeAttribute(origName); // Case hackery: attributes are lower-case, but bind targets // (properties) are case sensitive. Gambit is to map dash-case to // camel-case: `foo-bar` becomes `fooBar`. // Attribute bindings are excepted. if (kind === 'property') { name = Polymer.CaseMap.dashToCamelCase(name); } addBinding(this, templateInfo, nodeInfo, kind, name, parts, literal); return true; } else { return super._parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value); } } /** * Overrides default `TemplateStamp` implementation to add support for * binding the properties that a nested template depends on to the template * as `_host_<property>`. * * @override * @param {Node} node Node to parse * @param {TemplateInfo} templateInfo Template metadata for current template * @param {NodeInfo} nodeInfo Node metadata for current template node * @return {boolean} `true` if the visited node added node-specific * metadata to `nodeInfo` * @protected * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do */ static _parseTemplateNestedTemplate(node, templateInfo, nodeInfo) { let noted = super._parseTemplateNestedTemplate(node, templateInfo, nodeInfo); // Merge host props into outer template and add bindings let hostProps = nodeInfo.templateInfo.hostProps; let mode = '{'; for (let source in hostProps) { let parts = [{ mode, source, dependencies: [source] }]; addBinding(this, templateInfo, nodeInfo, 'property', '_host_' + source, parts); } return noted; } /** * Called to parse text in a template (either attribute values or * textContent) into binding metadata. * * Any overrides of this method should return an array of binding part * metadata representing one or more bindings found in the provided text * and any "literal" text in between. Any non-literal parts will be passed * to `_evaluateBinding` when any dependencies change. The only required * fields of each "part" in the returned array are as follows: * * - `dependencies` - Array containing trigger metadata for each property * that should trigger the binding to update * - `literal` - String containing text if the part represents a literal; * in this case no `dependencies` are needed * * Additional metadata for use by `_evaluateBinding` may be provided in * each part object as needed. * * The default implementation handles the following types of bindings * (one or more may be intermixed with literal strings): * - Property binding: `[[prop]]` * - Path binding: `[[object.prop]]` * - Negated property or path bindings: `[[!prop]]` or `[[!object.prop]]` * - Two-way property or path bindings (supports negation): * `{{prop}}`, `{{object.prop}}`, `{{!prop}}` or `{{!object.prop}}` * - Inline computed method (supports negation): * `[[compute(a, 'literal', b)]]`, `[[!compute(a, 'literal', b)]]` * * @param {string} text Text to parse from attribute or textContent * @param {Object} templateInfo Current template metadata * @return {Array<!BindingPart>} Array of binding part metadata * @protected */ static _parseBindings(text, templateInfo) { let parts = []; let lastIndex = 0; let m; // Example: "literal1{{prop}}literal2[[!compute(foo,bar)]]final" // Regex matches: // Iteration 1: Iteration 2: // m[1]: '{{' '[[' // m[2]: '' '!' // m[3]: 'prop' 'compute(foo,bar)' while ((m = bindingRegex.exec(text)) !== null) { // Add literal part if (m.index > lastIndex) { parts.push({literal: text.slice(lastIndex, m.index)}); } // Add binding part let mode = m[1][0]; let negate = Boolean(m[2]); let source = m[3].trim(); let customEvent = false, notifyEvent = '', colon = -1; if (mode == '{' && (colon = source.indexOf('::')) > 0) { notifyEvent = source.substring(colon + 2); source = source.substring(0, colon); customEvent = true; } let signature = parseMethod(source); let dependencies = []; if (signature) { // Inline computed function let {args, methodName} = signature; for (let i=0; i<args.length; i++) { let arg = args[i]; if (!arg.literal) { dependencies.push(arg); } } let dynamicFns = templateInfo.dynamicFns; if (dynamicFns && dynamicFns[methodName] || signature.static) { dependencies.push(methodName); signature.dynamicFn = true; } } else { // Property or path dependencies.push(source); } parts.push({ source, mode, negate, customEvent, signature, dependencies, event: notifyEvent }); lastIndex = bindingRegex.lastIndex; } // Add a final literal part if (lastIndex && lastIndex < text.length) { let literal = text.substring(lastIndex); if (literal) { parts.push({ literal: literal }); } } if (parts.length) { return parts; } else { return null; } } /** * Called to evaluate a previously parsed binding part based on a set of * one or more changed dependencies. * * @param {this} inst Element that should be used as scope for * binding dependencies * @param {BindingPart} part Binding part metadata * @param {string} path Property/path that triggered this effect * @param {Object} props Bag of current property changes * @param {Object} oldProps Bag of previous values for changed properties * @param {boolean} hasPaths True with `props` contains one or more paths * @return {*} Value the binding part evaluated to * @protected */ static _evaluateBinding(inst, part, path, props, oldProps, hasPaths) { let value; if (part.signature) { value = runMethodEffect(inst, path, props, oldProps, part.signature); } else if (path != part.source) { value = Polymer.Path.get(inst, part.source); } else { if (hasPaths && Polymer.Path.isPath(path)) { value = Polymer.Path.get(inst, path); } else { value = inst.__data[path]; } } if (part.negate) { value = !value; } return value; } } // make a typing for closure :P PropertyEffectsType = PropertyEffects; return PropertyEffects; }); /** * Helper api for enqueuing client dom created by a host element. * * By default elements are flushed via `_flushProperties` when * `connectedCallback` is called. Elements attach their client dom to * themselves at `ready` time which results from this first flush. * This provides an ordering guarantee that the client dom an element * creates is flushed before the element itself (i.e. client `ready` * fires before host `ready`). * * However, if `_flushProperties` is called *before* an element is connected, * as for example `Templatize` does, this ordering guarantee cannot be * satisfied because no elements are connected. (Note: Bound elements that * receive data do become enqueued clients and are properly ordered but * unbound elements are not.) * * To maintain the desired "client before host" ordering guarantee for this * case we rely on the "host stack. Client nodes registers themselves with * the creating host element when created. This ensures that all client dom * is readied in the proper order, maintaining the desired guarantee. * * @private */ let hostStack = { stack: [], /** * @param {*} inst Instance to add to hostStack * @return {void} * @this {hostStack} */ registerHost(inst) { if (this.stack.length) { let host = this.stack[this.stack.length-1]; host._enqueueClient(inst); } }, /** * @param {*} inst Instance to begin hosting * @return {void} * @this {hostStack} */ beginHosting(inst) { this.stack.push(inst); }, /** * @param {*} inst Instance to end hosting * @return {void} * @this {hostStack} */ endHosting(inst) { let stackLen = this.stack.length; if (stackLen && this.stack[stackLen-1] == inst) { this.stack.pop(); } } }; })(); </script>
uvalib/staff-directory
bower_components/json-formatter/bower_components/polymer/lib/mixins/property-effects.html
HTML
apache-2.0
105,334
[ 30522, 1026, 999, 1011, 1011, 1030, 6105, 9385, 1006, 1039, 1007, 2418, 1996, 17782, 2622, 6048, 1012, 2035, 2916, 9235, 1012, 2023, 3642, 2089, 2069, 2022, 2109, 2104, 1996, 18667, 2094, 2806, 6105, 2179, 2012, 8299, 1024, 1013, 1013, 17...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- # Simple script to test sending UTF8 text with the GrowlNotifier class import logging logging.basicConfig(level=logging.DEBUG) from gntp.notifier import GrowlNotifier import platform growl = GrowlNotifier(notifications=['Testing'],password='password',hostname='ayu') growl.subscribe(platform.node(),platform.node(),12345)
kfdm/gntp
test/subscribe.py
Python
mit
347
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1001, 3722, 5896, 2000, 3231, 6016, 21183, 2546, 2620, 3793, 2007, 1996, 13349, 17048, 18095, 2465, 12324, 15899, 15899, 1012, 3937, 8663, 8873, 2290, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#region License // ==================================================== // Project Porcupine Copyright(C) 2016 Team Porcupine // This program comes with ABSOLUTELY NO WARRANTY; This is free software, // and you are welcome to redistribute it under certain conditions; See // file LICENSE, which is part of this source code package, for details. // ==================================================== #endregion using System.Collections; using System.IO; using System.Linq; using System.Xml.Serialization; using UnityEngine; using UnityEngine.UI; //// Object -> MonoBehaviour -> DialogBox -> DialogBoxLoadSaveGame -> //// DialogBoxSaveGame //// DialogBoxLoadGame public class DialogBoxLoadSaveGame : DialogBox { public static readonly Color SecondaryColor = new Color(0.9f, 0.9f, 0.9f); public GameObject fileListItemPrefab; public Transform fileList; /// <summary> /// If directory doesn't exist EnsureDirectoryExists will create one. /// </summary> /// <param name="directoryPath">Full directory path.</param> public void EnsureDirectoryExists(string directoryPath) { if (Directory.Exists(directoryPath) == false) { Debug.ULogWarningChannel("DialogBoxLoadSaveGame", "Directory: " + directoryPath + " doesn't exist - creating."); Directory.CreateDirectory(directoryPath); } } public override void ShowDialog() { base.ShowDialog(); // Get list of files in save location string saveDirectoryPath = WorldController.Instance.FileSaveBasePath(); EnsureDirectoryExists(saveDirectoryPath); DirectoryInfo saveDir = new DirectoryInfo(saveDirectoryPath); FileInfo[] saveGames = saveDir.GetFiles().OrderByDescending(f => f.CreationTime).ToArray(); // Our save dialog has an input field, which the fileListItems fill out for // us when we click on them InputField inputField = gameObject.GetComponentInChildren<InputField>(); // Build file list by instantiating fileListItemPrefab for (int i = 0; i < saveGames.Length; i++) { FileInfo file = saveGames[i]; GameObject go = (GameObject)GameObject.Instantiate(fileListItemPrefab); // Make sure this GameObject is a child of our list box go.transform.SetParent(fileList); // file contains something like "C:\Users\UserName\......\Project Porcupine\Saves\SomeFileName.sav" // Path.GetFileName(file) returns "SomeFileName.sav" // Path.GetFileNameWithoutExtension(file) returns "SomeFileName" string fileName = Path.GetFileNameWithoutExtension(file.FullName); go.GetComponentInChildren<Text>().text = string.Format("{0}\n<size=11><i>{1}</i></size>", fileName, file.CreationTime); DialogListItem listItem = go.GetComponent<DialogListItem>(); listItem.fileName = fileName; listItem.inputField = inputField; go.GetComponent<Image>().color = i % 2 == 0 ? Color.white : SecondaryColor; } // Set scroll sensitivity based on the save-item count fileList.GetComponentInParent<ScrollRect>().scrollSensitivity = fileList.childCount / 2; } public override void CloseDialog() { // Clear out all the children of our file list while (fileList.childCount > 0) { Transform c = fileList.GetChild(0); c.SetParent(null); // Become Batman Destroy(c.gameObject); } //// We COULD clear out the inputField field here, but I think //// it makes sense to leave the old filename in there to make //// overwriting easier? //// Alternatively, we could either: //// a) Clear out the text box //// b) Append an incremental number to it so that it automatically does //// something like "SomeFileName 13" base.CloseDialog(); } }
therealjefe/ProjectPorcupine
Assets/Scripts/UI/DialogBox/FileSaveLoad/DialogBoxLoadSaveGame.cs
C#
gpl-3.0
4,095
[ 30522, 1001, 2555, 6105, 1013, 1013, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 102...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
require 'rubygems' gem 'rspec', '>= 1.2.8' require 'spec' require File.join(File.dirname(__FILE__), '..', 'lib', 'almaz') require 'base64' require 'timecop' require 'logger' Spec::Runner.configure do |config| config.before(:all) { result = RedisRunner.start_detached raise("Could not start redis-server, aborting") unless result # yeah, this sucks, but it seems like sometimes we try to connect too quickly w/o it sleep 1 # use database 15 for testing so we dont accidentally step on real data @db = Redis.new(:db => 15) #, :logger => Logger.new(STDOUT), :debug => true) } config.after(:each) { @db.flushdb } config.after(:all) { begin @db.quit ensure RedisRunner.stop rescue 'Oops' end } end def encode_credentials(username, password) "Basic " + Base64.encode64("#{username}:#{password}") end class ExampleSinatraApp < Sinatra::Base get '/awesome/controller' do 'wooo hoo' end end
jpoz/almaz
spec/spec_helper.rb
Ruby
mit
973
[ 30522, 5478, 1005, 10090, 3351, 5244, 1005, 17070, 1005, 12667, 5051, 2278, 1005, 1010, 1005, 1028, 1027, 1015, 1012, 1016, 1012, 1022, 1005, 5478, 1005, 28699, 1005, 5478, 5371, 1012, 3693, 1006, 5371, 1012, 16101, 18442, 1006, 1035, 1035,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/installer/util/google_update_settings.h" #include "base/registry.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_constants.h" namespace { bool ReadGoogleUpdateStrKey(const wchar_t* const name, std::wstring* value) { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring reg_path = dist->GetStateKey(); RegKey key(HKEY_CURRENT_USER, reg_path.c_str(), KEY_READ); if (!key.ReadValue(name, value)) { RegKey hklm_key(HKEY_LOCAL_MACHINE, reg_path.c_str(), KEY_READ); return hklm_key.ReadValue(name, value); } return true; } bool WriteGoogleUpdateStrKey(const wchar_t* const name, const std::wstring& value) { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring reg_path = dist->GetStateKey(); RegKey key(HKEY_CURRENT_USER, reg_path.c_str(), KEY_READ | KEY_WRITE); return key.WriteValue(name, value.c_str()); } bool ClearGoogleUpdateStrKey(const wchar_t* const name) { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring reg_path = dist->GetStateKey(); RegKey key(HKEY_CURRENT_USER, reg_path.c_str(), KEY_READ | KEY_WRITE); std::wstring value; if (!key.ReadValue(name, &value)) return false; return key.WriteValue(name, L""); } } // namespace. bool GoogleUpdateSettings::GetCollectStatsConsent() { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring reg_path = dist->GetStateKey(); RegKey key(HKEY_CURRENT_USER, reg_path.c_str(), KEY_READ); DWORD value; if (!key.ReadValueDW(google_update::kRegUsageStatsField, &value)) { RegKey hklm_key(HKEY_LOCAL_MACHINE, reg_path.c_str(), KEY_READ); if (!hklm_key.ReadValueDW(google_update::kRegUsageStatsField, &value)) return false; } return (1 == value); } bool GoogleUpdateSettings::SetCollectStatsConsent(bool consented) { DWORD value = consented? 1 : 0; // Writing to HKLM is only a best effort deal. BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring reg_path = dist->GetStateMediumKey(); RegKey key_hklm(HKEY_LOCAL_MACHINE, reg_path.c_str(), KEY_READ | KEY_WRITE); key_hklm.WriteValue(google_update::kRegUsageStatsField, value); // Writing to HKCU is used both by chrome and by the crash reporter. reg_path = dist->GetStateKey(); RegKey key_hkcu(HKEY_CURRENT_USER, reg_path.c_str(), KEY_READ | KEY_WRITE); return key_hkcu.WriteValue(google_update::kRegUsageStatsField, value); } bool GoogleUpdateSettings::SetEULAConsent(bool consented) { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring reg_path = dist->GetStateMediumKey(); RegKey key(HKEY_LOCAL_MACHINE, reg_path.c_str(), KEY_READ | KEY_SET_VALUE); return key.WriteValue(google_update::kRegEULAAceptedField, consented? 1 : 0); } bool GoogleUpdateSettings::GetBrowser(std::wstring* browser) { return ReadGoogleUpdateStrKey(google_update::kRegBrowserField, browser); } bool GoogleUpdateSettings::GetLanguage(std::wstring* language) { return ReadGoogleUpdateStrKey(google_update::kRegLangField, language); } bool GoogleUpdateSettings::GetBrand(std::wstring* brand) { return ReadGoogleUpdateStrKey(google_update::kRegRLZBrandField, brand); } bool GoogleUpdateSettings::GetClient(std::wstring* client) { return ReadGoogleUpdateStrKey(google_update::kRegClientField, client); } bool GoogleUpdateSettings::SetClient(const std::wstring& client) { return WriteGoogleUpdateStrKey(google_update::kRegClientField, client); } bool GoogleUpdateSettings::GetReferral(std::wstring* referral) { return ReadGoogleUpdateStrKey(google_update::kRegReferralField, referral); } bool GoogleUpdateSettings::ClearReferral() { return ClearGoogleUpdateStrKey(google_update::kRegReferralField); }
amyvmiwei/chromium
chrome/installer/util/google_update_settings.cc
C++
bsd-3-clause
4,045
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2294, 1011, 2268, 1996, 10381, 21716, 5007, 6048, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1037, 18667, 2094, 1011, 2806, 6105, 2008, 2064, 2022, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Infraestrutura.ORM.EF.Repositorio.Comum; namespace Dominio.Contrato.Comum { /// <summary> /// Repositório Pai. /// Contrato entre a camada de domínio e a camada de infraestrutura /// O que a diferencia da Camada DAO é justamente a sua forma desacoplada /// Aqui, não pode existir de forma alguma uma chamada a uma propriedade /// como por exemplo FindById(int id), isso deve ser trocado pelo padrão Specification /// que deve pertencer apenas ao Repositório especifico da entidade /// </summary> /// <typeparam name="T"></typeparam> public interface IRepositorioPai<T>: IUnitOfWork where T: class { void Criar(T entidade); void Editar(T entidade); void Excluir(T entidade); ICollection<T> BuscarTodos(); ICollection<T> FiltrarCompostoPor(Func<T, bool> predicado); T FiltrarSimplesPor(Func<T, bool> predicado); } }
gabrielsimas/SistemasExemplo
DDD/Refactoring3CamadasToSucesso/RefactDDD.Solucao/Dominio/Contrato/Comum/IRepositorioPai.cs
C#
mit
1,051
[ 30522, 2478, 2291, 1025, 2478, 2291, 1012, 6407, 1012, 12391, 1025, 2478, 2291, 1012, 11409, 4160, 1025, 2478, 2291, 1012, 3793, 1025, 2478, 2291, 1012, 11689, 2075, 1012, 8518, 1025, 2478, 1999, 27843, 4355, 22134, 4648, 1012, 2030, 2213, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2014 Alexey Andreev. * * 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 org.teavm.model; import java.util.Set; /** * * @author Alexey Andreev */ public interface VariableReader { int getIndex(); ProgramReader getProgram(); Set<String> readDebugNames(); int getRegister(); }
mpoindexter/teavm
teavm-core/src/main/java/org/teavm/model/VariableReader.java
Java
apache-2.0
844
[ 30522, 1013, 1008, 1008, 9385, 2297, 4074, 3240, 7213, 6777, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, 2224, 2023, 5371, 3272, 1999, 12...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package net.digitalbebop.pulsefilemodule import java.io.{FileInputStream, File} import java.nio.file.attribute.FileOwnerAttributeView import java.nio.file.{Paths, Files} import java.util.UUID import com.google.protobuf.ByteString import com.itextpdf.text.pdf.PdfReader import com.itextpdf.text.pdf.parser.PdfTextExtractor import net.digitalbebop.ClientRequests.IndexRequest import org.apache.commons.io.{FilenameUtils, IOUtils} import scala.util.parsing.json.JSONObject object Extractor { private final val fileModule = "files" private def splitCamelCase(s: String): String = s.replaceAll(String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])"), " ") private def replaceSplits(s: String) = s.replaceAll("[_|-]", " ") private def cleanString: String => String = splitCamelCase _ compose replaceSplits private def getTags(file: File, uidMap: Map[String, String]): Array[String] = file.getAbsolutePath.split("/") .dropWhile(s => !uidMap.contains(s)) .flatMap { name => if (name.endsWith(".pdf")) { cleanString(FilenameUtils.removeExtension(name)).split(" ") } else { cleanString(name).split(" ") } } // TODO add tags for file name def processPdf(file: File, uidMap: Map[String, String]): IndexRequest = { val reader = new PdfReader(file.getAbsolutePath) val indexData = (1 to reader.getNumberOfPages).foldLeft(new StringBuilder()) { (builder, page) => builder.append(PdfTextExtractor.getTextFromPage(reader, page) + " ") }.toString() val indexBuilder = IndexRequest.newBuilder() indexBuilder.setIndexData(indexData) indexBuilder.setRawData(ByteString.readFrom(Files.newInputStream(file.toPath))) indexBuilder.setLocation(file.getAbsolutePath) indexBuilder.setMetaTags(new JSONObject(Map(("format", "pdf"), ("title", file.getName))).toString()) indexBuilder.setTimestamp(file.lastModified()) indexBuilder.setModuleId(UUID.nameUUIDFromBytes(file.getAbsolutePath.getBytes).toString) indexBuilder.setModuleName(fileModule) getTags(file, uidMap).foreach(indexBuilder.addTags) val view = Files.getFileAttributeView(Paths.get(file.getAbsolutePath), classOf[FileOwnerAttributeView]) uidMap.get(view.getOwner.getName).map(indexBuilder.setUsername) reader.close() indexBuilder.build() } }
JDrit/PulseFileModule
src/main/scala/net/digitalbebop/pulsefilemodule/Extractor.scala
Scala
apache-2.0
2,378
[ 30522, 7427, 5658, 1012, 3617, 4783, 5092, 2361, 1012, 8187, 8873, 16930, 7716, 9307, 12324, 9262, 1012, 22834, 1012, 1063, 5371, 2378, 18780, 21422, 1010, 5371, 1065, 12324, 9262, 1012, 9152, 2080, 1012, 5371, 1012, 17961, 1012, 5371, 1238...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<h2 class="widget-title">iobrokerlog</h2> <!doctype html> <html> <head> <!-- Replace "localhost" with real IP address of controller, if default port changed, correct it too --> <script type="text/javascript" src="/javascripts/socket.io.js"></script> <!--script type="text/javascript" src="conn.js"></script--> </head> <body> <!-- Check the browser console! --> <script type="text/javascript"> servConn.namespace = 'mobile.0'; servConn._useStorage = false; var lineNr = 0; var socketInitiated = false; states = []; setInterval(()=>{ if (window.socketio && !socketInitiated){ socketInitiated = true; initSocket(); } }, 2000); function initSocket(){ servConn.init({ name: 'mobile.0', // optional - default 'vis.0' connLink: window.socketio, // optional URL of the socket.io adapter socketSession: '' // optional - used by authentication }, { onConnChange: function (isConnected) { if (isConnected) { console.log('connected'); servConn.getStates(function (err, _states) { var count = 0; for (var id in _states) { count++; } console.log('Received ' + count + ' states.'); states = _states; }); } else { console.log('disconnected'); } }, onRefresh: function () { window.location.reload(); }, onUpdate: function (id, state) { let _this = this; setTimeout(function () { let fvalue = $("#info_filter").html(); let exclude_sa = $("#filter_sa").is(':checked'); if(id.indexOf(fvalue) >= 0){ let result = JSON.stringify(state); console.log('NEW VALUE of ' + id + ': ' + result); if (exclude_sa && id.indexOf("system.adapter") >= 0) { _this.addOrUpdate("system.adapter", "."); //$(".content_iobroker").prepend(`.`); } else { _this.addOrUpdate(id, result); //$(".content_iobroker").prepend(`<div>[${lineNr++}] ${id}: ${result}</div>`) } } states[id] = state; //Will update other elements in the window let caller = window.stateUpdate; let el = caller[1]; if (caller) { caller[0](el, states, caller[3], caller[2]); } }, 0); }, addOrUpdate: function(key, val){ key = key.replace(/\./g, "_"); if($(`.content_iobroker > #${key}`).length) { $(`.content_iobroker > #${key}`).text(`[${key}]: ${val}`); } else { $(".content_iobroker").prepend(`<div id="${key}">[${key}]: ${val}</div>`); } //} else { // $(`.content_iobroker #${key}`).text(val); //} }, onError: function (err) { window.alert(_('Cannot execute %s for %s, because of insufficient permissions', err.command, err.arg), _('Insufficient permissions'), 'alert', 600); } }); } function filter(el) { if(event.key === 'Enter') { if(confirm(`Are you sure you want to filter for "${el.value}"?`)){ $("#info_filter").html(el.value); } } } </script> <input id="filter_s" type="text" value="mihome" onkeydown="filter(this)" /> <a href="#" onclick="$('#filter_s').blur();$('.content_iobroker').empty()">clear</a><br> <input id="filter_sa" type="checkbox" checked/>exclude system.adapter <div>Filtering for <span id="info_filter">mihome</span></div> <div class="content_iobroker"> </div> </body>
tcardoso2/t-motion-detector-cli
atlasboard/packages/default/widgets/iobrokerlog/iobrokerlog.html
HTML
bsd-2-clause
4,362
[ 30522, 1026, 1044, 2475, 2465, 1027, 1000, 15536, 24291, 1011, 2516, 1000, 1028, 22834, 12618, 5484, 21197, 1026, 1013, 1044, 2475, 1028, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 999, 1011, 1011, 5672,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package liquibase.sqlgenerator.core; import liquibase.change.ColumnConfig; import liquibase.database.ObjectQuotingStrategy; import liquibase.database.core.OracleDatabase; import liquibase.sql.Sql; import liquibase.statement.DatabaseFunction; import liquibase.statement.SequenceCurrentValueFunction; import liquibase.statement.SequenceNextValueFunction; import liquibase.statement.core.InsertOrUpdateStatement; import liquibase.statement.core.InsertStatement; import liquibase.statement.core.UpdateStatement; import org.junit.Test; import static org.junit.Assert.*; public class InsertOrUpdateGeneratorOracleTest { @Test public void ContainsInsertStatement() { OracleDatabase database = new OracleDatabase(); InsertOrUpdateGeneratorOracle generator = new InsertOrUpdateGeneratorOracle(); InsertOrUpdateStatement statement = new InsertOrUpdateStatement("mycatalog", "myschema","mytable","pk_col1"); statement.addColumnValue("pk_col1","value1"); statement.addColumnValue("col2","value2"); statement.addColumnValue("pk_col1","value1"); statement.addColumnValue("col2","value2"); Sql[] sql = generator.generateSql( statement, database, null); String theSql = sql[0].toSql(); assertTrue(theSql.contains("INSERT INTO mycatalog.mytable (pk_col1, col2) VALUES ('value1', 'value2');")); assertTrue(theSql.contains("UPDATE mycatalog.mytable")); String[] sqlLines = theSql.split("\n"); int lineToCheck = 0; assertEquals("DECLARE", sqlLines[lineToCheck].trim()); lineToCheck++; assertEquals("v_reccount NUMBER := 0;", sqlLines[lineToCheck].trim()); lineToCheck++; assertEquals("BEGIN", sqlLines[lineToCheck].trim()); lineToCheck++; assertEquals("SELECT COUNT(*) INTO v_reccount FROM mycatalog.mytable WHERE pk_col1 = 'value1';", sqlLines[lineToCheck].trim()); lineToCheck++; assertEquals("IF v_reccount = 0 THEN", sqlLines[lineToCheck].trim()); lineToCheck++; assertEquals("INSERT INTO mycatalog.mytable (pk_col1, col2) VALUES ('value1', 'value2');", sqlLines[lineToCheck]); lineToCheck++; assertEquals("ELSIF v_reccount = 1 THEN", sqlLines[lineToCheck].trim()); lineToCheck++; assertEquals("UPDATE mycatalog.mytable SET col2 = 'value2' WHERE pk_col1 = 'value1';", sqlLines[lineToCheck].trim()); lineToCheck++; assertEquals("END IF;", sqlLines[lineToCheck].trim()); lineToCheck++; assertEquals("END;", sqlLines[lineToCheck].trim()); /* DECLARE v_prodcount NUMBER := 0; BEGIN -- Check if product with this name already exists SELECT COUNT (*) INTO v_prodcount FROM books WHERE isbn = 12345678; -- Product does not exist IF v_prodcount = 0 THEN -- Insert row into PRODUCT based on arguments passed INSERT INTO books VALUES ( 12345678, 98765432, 'Working with Liquibase'); -- Product with this name already exists ELSIF v_prodcount = 1 THEN -- Update the existing product with values -- passed as arguments UPDATE books SET author_id = 98765432, title = 'Working with liquibase' WHERE isbn = 12345678; END IF; END;*/ } @Test public void testOnlyUpdateFlag() { OracleDatabase database = new OracleDatabase(); InsertOrUpdateGeneratorOracle generator = new InsertOrUpdateGeneratorOracle(); InsertOrUpdateStatement statement = new InsertOrUpdateStatement("mycatalog", "myschema", "mytable", "pk_col1", true); statement.addColumnValue("pk_col1", "value1"); statement.addColumnValue("col2", "value2"); Sql[] sql = generator.generateSql(statement, database, null); String theSql = sql[0].toSql(); assertFalse("should not have had insert statement", theSql.contains("INSERT INTO mycatalog.mytable (pk_col1, col2) VALUES ('value1', 'value2');")); assertTrue("missing update statement", theSql.contains("UPDATE mycatalog.mytable")); String[] sqlLines = theSql.split("\n"); int lineToCheck = 0; assertEquals("UPDATE mycatalog.mytable SET col2 = 'value2' WHERE pk_col1 = 'value1'", sqlLines[lineToCheck].trim()); assertEquals("Wrong number of lines", 1, sqlLines.length); } private String prepareInsertStatement(DatabaseFunction databaseSchemaBasedFunction) { OracleDatabase database = new OracleDatabase(); database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY); InsertGenerator generator = new InsertGenerator(); InsertStatement statement = new InsertStatement("mycatalog", "myschema", "mytable"); ColumnConfig columnConfig = new ColumnConfig(); if (databaseSchemaBasedFunction instanceof SequenceNextValueFunction) { columnConfig.setValueSequenceNext((SequenceNextValueFunction) databaseSchemaBasedFunction); } else if (databaseSchemaBasedFunction instanceof SequenceCurrentValueFunction) { columnConfig.setValueSequenceCurrent((SequenceCurrentValueFunction) databaseSchemaBasedFunction); } columnConfig.setName("col3"); statement.addColumn(columnConfig); Sql[] sql = generator.generateSql(statement, database, null); return sql[0].toSql(); } private String prepareUpdateStatement(SequenceNextValueFunction sequenceNextValueFunction) { OracleDatabase database = new OracleDatabase(); database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY); UpdateGenerator generator = new UpdateGenerator(); UpdateStatement statement = new UpdateStatement("mycatalog", "myschema", "mytable"); statement.addNewColumnValue("col3", sequenceNextValueFunction); Sql[] sql = generator.generateSql(statement, database, null); return sql[0].toSql(); } @Test public void testInsertSequenceValWithSchema() { SequenceNextValueFunction sequenceNext = new SequenceNextValueFunction("myschema", "my_seq"); assertEquals( "INSERT INTO mycatalog.mytable (col3) VALUES (myschema.my_seq.nextval)", prepareInsertStatement(sequenceNext)); } @Test public void testInsertSequenceValWithSchemaInWholeStatement() { SequenceNextValueFunction sequenceNext = new SequenceNextValueFunction("myschema", "my_seq"); assertEquals( "INSERT INTO mycatalog.mytable (col3) VALUES (myschema.my_seq.nextval)", prepareInsertStatement(sequenceNext)); } @Test public void testUpdateSequenceValWithSchema() { SequenceNextValueFunction sequenceNext = new SequenceNextValueFunction("myschema", "my_seq"); assertEquals( "UPDATE mycatalog.mytable SET col3 = myschema.my_seq.nextval", prepareUpdateStatement(sequenceNext)); } @Test public void testUpdateSequenceValWithSchemaInWholeStatement() { SequenceNextValueFunction sequenceNext = new SequenceNextValueFunction("myschema", "my_seq"); assertEquals( "UPDATE mycatalog.mytable SET col3 = myschema.my_seq.nextval", prepareUpdateStatement(sequenceNext)); } }
liquibase/liquibase
liquibase-core/src/test/java/liquibase/sqlgenerator/core/InsertOrUpdateGeneratorOracleTest.java
Java
apache-2.0
7,276
[ 30522, 7427, 5622, 15549, 15058, 1012, 29296, 6914, 6906, 4263, 1012, 4563, 1025, 12324, 5622, 15549, 15058, 1012, 2689, 1012, 5930, 8663, 8873, 2290, 1025, 12324, 5622, 15549, 15058, 1012, 7809, 1012, 4874, 28940, 20656, 20528, 2618, 6292, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<p style="text-align:justify">word0<strong> short term debt securities</strong> word1 word2 word3 <strong>december 21, 2010.</strong></p><p><br /></p>
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/tests/plugins/pastefromword/generated/_fixtures/Tickets/6751disappearing_spaces_example2/expected.html
HTML
gpl-3.0
150
[ 30522, 1026, 1052, 2806, 1027, 1000, 3793, 1011, 25705, 1024, 16114, 1000, 1028, 2773, 2692, 1026, 2844, 1028, 2460, 2744, 7016, 12012, 1026, 1013, 2844, 1028, 2773, 2487, 2773, 2475, 2773, 2509, 1026, 2844, 1028, 2285, 2538, 1010, 2230, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace Osiset\ShopifyApp\Contracts\Queries; use Illuminate\Support\Collection; use Osiset\ShopifyApp\Contracts\Objects\Values\ShopDomain as ShopDomainValue; use Osiset\ShopifyApp\Contracts\Objects\Values\ShopId as ShopIdValue; use Osiset\ShopifyApp\Contracts\ShopModel as IShopModel; /** * Reprecents a queries for shops. */ interface Shop { /** * Get by ID. * * @param ShopIdValue $shopId The shop ID. * @param array $with The relations to eager load. * @param bool $withTrashed Include trashed shops? * * @return IShopModel|null */ public function getById(ShopIdValue $shopId, array $with = [], bool $withTrashed = false): ?IShopModel; /** * Get by domain. * * @param ShopDomain $domain The shop domain. * @param array $with The relations to eager load. * @param bool $withTrashed Include trashed shops? * * @return IShopModel|null */ public function getByDomain(ShopDomainValue $domain, array $with = [], bool $withTrashed = false): ?IShopModel; /** * Get all records. * * @param array $with The relations to eager load. * * @return Collection IShopModel[] */ public function getAll(array $with = []): Collection; }
ohmybrew/laravel-shopify
src/ShopifyApp/Contracts/Queries/Shop.php
PHP
mit
1,317
[ 30522, 1026, 1029, 25718, 3415, 15327, 9808, 5562, 2102, 1032, 4497, 8757, 29098, 1032, 8311, 1032, 10861, 5134, 1025, 2224, 5665, 12717, 12556, 1032, 2490, 1032, 3074, 1025, 2224, 9808, 5562, 2102, 1032, 4497, 8757, 29098, 1032, 8311, 1032...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.example.aperture.core.contacts; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import java.util.List; import java.util.ArrayList; import com.example.aperture.core.Module; public class EmailFilter extends Filter { private final static String[] DATA_PROJECTION = new String[] { ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Data.DATA1 }; private final static String MIMETYPE_SELECTION = ContactsContract.Data.MIMETYPE + "=?"; private final static String[] EMAIL_MIMETYPE = new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }; private final static String[] PREFIXES = new String[] { "send an email to ", "send email to ", "email " }; private final static class EmailComparer implements java.util.Comparator<Intent> { private String mFragment; public EmailComparer(String fragment) { mFragment = fragment; } @Override public boolean equals(Object o) { return false; } @Override public int compare(Intent a, Intent b) { // Get the emails from the intents. String x = a.getStringExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE); String y = b.getStringExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE); // Split the emails into usernames and domains. String xu = x.substring(0, x.indexOf('@')); String yu = y.substring(0, y.indexOf('@')); String xd = x.substring(x.indexOf('@')+1); String yd = y.substring(y.indexOf('@')+1); // Get the locations of the query in the usernames and domains. int ixu = xu.indexOf(mFragment), iyu = yu.indexOf(mFragment); int ixd = xd.indexOf(mFragment), iyd = yd.indexOf(mFragment); // TODO refactor this to be less iffy // Explicitly writing out the comparision logic to avoid violating // general sorting contract for total ordering. if(ixu != -1 && iyu != -1) { if(ixu < iyu) return -1; else if(iyu < ixu) return 1; else return xu.compareTo(yu); } else if(ixu != -1 && iyu == -1) { return -1; } else if(ixu == -1 && iyu != -1) { return 1; } else { if(ixd != -1 && iyd != -1) { if(ixd < iyd) return -1; else if(iyd < ixd) return 1; else return xd.compareTo(yd); } else if(ixd != -1 && iyd == -1) { return -1; } else if(ixd == -1 && iyd != -1) { return 1; } else return x.compareTo(y); } } } private void sort(List<Intent> results, String query) { Intent[] buffer = new Intent[results.size()]; java.util.Arrays.sort(results.toArray(buffer), 0, buffer.length, new EmailComparer(query)); results.clear(); for(int i = 0; i < buffer.length; ++i) results.add(buffer[i]); } @Override public List<Intent> filter(Context context, String query) { List<Intent> results = new ArrayList<Intent>(); boolean hasPrefix = false; for(String prefix: PREFIXES) { if(query.startsWith(prefix)) { query = query.substring(prefix.length()); hasPrefix = true; break; } } Cursor data = context.getContentResolver().query( ContactsContract.Data.CONTENT_URI, DATA_PROJECTION, MIMETYPE_SELECTION, EMAIL_MIMETYPE, null); if(hasPrefix) results.addAll(filterByName(data, query)); results.addAll(filterByAddress(data, query)); data.close(); return results; } private List<Intent> filterByName(Cursor data, String query) { List<Intent> results = new ArrayList<Intent>(); query = query.toLowerCase(); for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) { String name = data.getString(1).toLowerCase(); if(name.contains(query)) results.add(intentFor(data.getString(1), data.getString(2))); } return results; } private List<Intent> filterByAddress(Cursor data, String query) { List<Intent> results = new ArrayList<Intent>(); for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) { String email = data.getString(2); if(email.contains(query)) results.add(intentFor(data.getString(1), email)); } sort(results, query); return results; } private Intent intentFor(String displayName, String email) { Intent result = new Intent(Intent.ACTION_SENDTO, new Uri.Builder().scheme("mailto").opaquePart(email).build()); result.putExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, email); result.putExtra(Module.RESPONSE_TEXT, String.format("%1$s <%2$s>", displayName, email)); return result; } }
ayshen/caek
src/com/example/aperture/core/contacts/EmailFilter.java
Java
mit
5,607
[ 30522, 7427, 4012, 1012, 2742, 1012, 18892, 1012, 4563, 1012, 10402, 1025, 12324, 11924, 1012, 4180, 1012, 6123, 1025, 12324, 11924, 1012, 4180, 1012, 7848, 1025, 12324, 11924, 1012, 7809, 1012, 12731, 25301, 2099, 1025, 12324, 11924, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Copyright 2013 IBM Corp. # # 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. from cinder.compute import nova from cinder import context from cinder import test class FakeNovaClient(object): class Volumes(object): def __getattr__(self, item): return None def __init__(self): self.volumes = self.Volumes() def create_volume_snapshot(self, *args, **kwargs): pass def delete_volume_snapshot(self, *args, **kwargs): pass class NovaApiTestCase(test.TestCase): def setUp(self): super(NovaApiTestCase, self).setUp() self.api = nova.API() self.novaclient = FakeNovaClient() self.ctx = context.get_admin_context() self.mox.StubOutWithMock(nova, 'novaclient') def test_update_server_volume(self): nova.novaclient(self.ctx).AndReturn(self.novaclient) self.mox.StubOutWithMock(self.novaclient.volumes, 'update_server_volume') self.novaclient.volumes.update_server_volume('server_id', 'attach_id', 'new_volume_id') self.mox.ReplayAll() self.api.update_server_volume(self.ctx, 'server_id', 'attach_id', 'new_volume_id')
Thingee/cinder
cinder/tests/compute/test_nova.py
Python
apache-2.0
1,814
[ 30522, 1001, 9385, 2286, 9980, 13058, 1012, 1001, 1001, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 2017, 2089, 1001, 2025, 2224, 2023, 5371, 3272, 1999, 12646, 2007, 1996, 6105, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
-- Path of Building -- -- Class: List Control -- Basic list control. -- -- This is an abstract base class; derived classes can supply these properties and methods to configure the list control: -- .label [Adds a label above the top left corner] -- .dragTargetList [List of controls that can receive drag events from this list control] -- .showRowSeparators [Shows separators between rows] -- :GetColumnOffset(column) [Called to get the offset of the given column] -- :GetRowValue(column, index, value) [Required; called to retrieve the text for the given column of the given list value] -- :AddValueTooltip(index, value) [Called to add the tooltip for the given list value] -- :GetDragValue(index, value) [Called to retrieve the drag type and object for the given list value] -- :CanReceiveDrag(type, value) [Called on drag target to determine if it can receive this value] -- :ReceiveDrag(type, value, source) [Called on the drag target when a drag completes] -- :OnDragSend(index, value, target) [Called after a drag event] -- :OnOrderChange() [Called after list order is changed through dragging] -- :OnSelect(index, value) [Called when a list value is selected] -- :OnSelClick(index, value, doubleClick) [Called when a list value is clicked] -- :OnSelCopy(index, value) [Called when Ctrl+C is pressed while a list value is selected] -- :OnSelDelete(index, value) [Called when backspace or delete is pressed while a list value is selected] -- :OnSelKeyDown(index, value) [Called when any other key is pressed while a list value is selected] -- local launch, main = ... local ipairs = ipairs local t_insert = table.insert local t_remove = table.remove local m_min = math.min local m_max = math.max local m_floor = math.floor local ListClass = common.NewClass("ListControl", "Control", "ControlHost", function(self, anchor, x, y, width, height, rowHeight, isMutable, list) self.Control(anchor, x, y, width, height) self.ControlHost() self.rowHeight = rowHeight self.isMutable = isMutable self.list = list or { } self.tooltip = common.New("Tooltip") self.controls.scrollBar = common.New("ScrollBarControl", {"RIGHT",self,"RIGHT"}, -1, 0, 16, 0, rowHeight * 2) self.controls.scrollBar.height = function() local width, height = self:GetSize() return height - 2 end end) function ListClass:SelectIndex(index) self.selValue = self.list[index] if self.selValue then self.selIndex = index local width, height = self:GetSize() self.controls.scrollBar:SetContentDimension(#self.list * self.rowHeight, height - 4) self.controls.scrollBar:ScrollIntoView((index - 2) * self.rowHeight, self.rowHeight * 3) if self.OnSelect then self:OnSelect(self.selIndex, self.selValue) end end end function ListClass:GetColumnOffset(column) if column == 1 then return 0 end end function ListClass:IsMouseOver() if not self:IsShown() then return end return self:IsMouseInBounds() or self:GetMouseOverControl() end function ListClass:Draw(viewPort) local x, y = self:GetPos() local width, height = self:GetSize() local rowHeight = self.rowHeight local list = self.list local scrollBar = self.controls.scrollBar scrollBar:SetContentDimension(#list * rowHeight, height - 4) local cursorX, cursorY = GetCursorPos() if self.selValue and self.selDragging and not self.selDragActive and (cursorX-self.selCX)*(cursorX-self.selCX)+(cursorY-self.selCY)*(cursorY-self.selCY) > 100 then self.selDragActive = true if self.dragTargetList then self.dragType, self.dragValue = self:GetDragValue(self.selIndex, self.selValue) for _, target in ipairs(self.dragTargetList) do if not target.CanReceiveDrag or target:CanReceiveDrag(self.dragType, self.dragValue) then target.otherDragSource = self end end end end self.selDragIndex = nil if (self.selDragActive or self.otherDragSource) and self.isMutable then if cursorX >= x + 2 and cursorY >= y + 2 and cursorX < x + width - 18 and cursorY < y + height - 2 then local index = math.floor((cursorY - y - 2 + scrollBar.offset) / rowHeight + 0.5) + 1 if not self.selIndex or index < self.selIndex or index > self.selIndex + 1 then self.selDragIndex = m_min(index, #list + 1) end end end if self.selDragActive and self.dragTargetList then self.dragTarget = nil for _, target in ipairs(self.dragTargetList) do if not self.dragTarget and target.otherDragSource == self and target:IsMouseOver() then self.dragTarget = target target.otherDragTargeting = true else target.otherDragTargeting = false end end end local label = self:GetProperty("label") if label then DrawString(x, y - 20, "LEFT", 16, "VAR", label) end if self.otherDragSource and not self.CanDragToValue then SetDrawColor(0.2, 0.6, 0.2) elseif self.hasFocus then SetDrawColor(1, 1, 1) else SetDrawColor(0.5, 0.5, 0.5) end DrawImage(nil, x, y, width, height) if self.otherDragSource and not self.CanDragToValue then SetDrawColor(0, 0.05, 0) else SetDrawColor(0, 0, 0) end DrawImage(nil, x + 1, y + 1, width - 2, height - 2) self:DrawControls(viewPort) SetViewport(x + 2, y + 2, width - 20, height - 4) local textOffsetY = self.showRowSeparators and 2 or 0 local textHeight = rowHeight - textOffsetY * 2 local ttIndex, ttValue, ttX, ttY, ttWidth local minIndex = m_floor(scrollBar.offset / rowHeight + 1) local maxIndex = m_min(m_floor((scrollBar.offset + height) / rowHeight + 1), #list) local column = 1 local elipWidth = DrawStringWidth(textHeight, "VAR", "...") while true do local colOffset = self:GetColumnOffset(column) if not colOffset then break end local colWidth = (self:GetColumnOffset(column + 1) or width - 20) - colOffset for index = minIndex, maxIndex do local lineY = rowHeight * (index - 1) - scrollBar.offset local value = list[index] local text = self:GetRowValue(column, index, value) local textWidth = DrawStringWidth(textHeight, "VAR", text) if textWidth > colWidth - 2 then local clipIndex = DrawStringCursorIndex(textHeight, "VAR", text, colWidth - elipWidth - 2, 0) text = text:sub(1, clipIndex - 1) .. "..." textWidth = DrawStringWidth(textHeight, "VAR", text) end if not scrollBar.dragging and (not self.selDragActive or (self.CanDragToValue and self:CanDragToValue(index, value, self.otherDragSource))) then local cursorX, cursorY = GetCursorPos() local relX = cursorX - (x + 2) local relY = cursorY - (y + 2) if relX >= colOffset and relX < width - 20 and relY >= 0 and relY >= lineY and relY < height - 2 and relY < lineY + rowHeight then ttIndex = index ttValue = value ttX = x + 2 + colOffset ttY = lineY + y + 2 ttWidth = m_max(textWidth + 8, relX - colOffset) end end if self.showRowSeparators then if self.hasFocus and value == self.selValue then SetDrawColor(1, 1, 1) elseif value == ttValue then SetDrawColor(0.8, 0.8, 0.8) else SetDrawColor(0.5, 0.5, 0.5) end DrawImage(nil, colOffset, lineY, colWidth, rowHeight) if (value == self.selValue or value == ttValue) then SetDrawColor(0.33, 0.33, 0.33) elseif self.otherDragSource and self.CanDragToValue and self:CanDragToValue(index, value, self.otherDragSource) then SetDrawColor(0, 0.2, 0) elseif index % 2 == 0 then SetDrawColor(0.05, 0.05, 0.05) else SetDrawColor(0, 0, 0) end DrawImage(nil, colOffset, lineY + 1, colWidth, rowHeight - 2) elseif value == self.selValue or value == ttValue then if self.hasFocus and value == self.selValue then SetDrawColor(1, 1, 1) elseif value == ttValue then SetDrawColor(0.8, 0.8, 0.8) else SetDrawColor(0.5, 0.5, 0.5) end DrawImage(nil, colOffset, lineY, colWidth, rowHeight) if self.otherDragSource and self.CanDragToValue and self:CanDragToValue(index, value, self.otherDragSource) then SetDrawColor(0, 0.2, 0) else SetDrawColor(0.15, 0.15, 0.15) end DrawImage(nil, colOffset, lineY + 1, colWidth, rowHeight - 2) end SetDrawColor(1, 1, 1) DrawString(colOffset, lineY + textOffsetY, "LEFT", textHeight, "VAR", text) end column = column + 1 end if #self.list == 0 and self.defaultText then SetDrawColor(1, 1, 1) DrawString(2, 2, "LEFT", 14, "VAR", self.defaultText) end if self.selDragIndex then local lineY = rowHeight * (self.selDragIndex - 1) - scrollBar.offset SetDrawColor(1, 1, 1) DrawImage(nil, 0, lineY - 1, width - 20, 3) SetDrawColor(0, 0, 0) DrawImage(nil, 0, lineY, width - 20, 1) end SetViewport() if self.selDragActive and self.dragTargetList and (not self.isMutable or not self:IsMouseOver()) then main.showDragText = self:GetRowValue(1, self.selIndex, self.selValue) end self.hoverIndex = ttIndex self.hoverValue = ttValue if ttIndex and self.AddValueTooltip then SetDrawLayer(nil, 100) self:AddValueTooltip(self.tooltip, ttIndex, ttValue) self.tooltip:Draw(ttX, ttY, ttWidth, rowHeight, viewPort) SetDrawLayer(nil, 0) end end function ListClass:OnKeyDown(key, doubleClick) if not self:IsShown() or not self:IsEnabled() then return end local mOverControl = self:GetMouseOverControl() if mOverControl and mOverControl.OnKeyDown then return mOverControl:OnKeyDown(key) end if not self:IsMouseOver() and key:match("BUTTON") then return end if key == "LEFTBUTTON" then self.selValue = nil self.selIndex = nil local x, y = self:GetPos() local width, height = self:GetSize() local cursorX, cursorY = GetCursorPos() if cursorX >= x + 2 and cursorY >= y + 2 and cursorX < x + width - 18 and cursorY < y + height - 2 then local index = math.floor((cursorY - y - 2 + self.controls.scrollBar.offset) / self.rowHeight) + 1 self.selValue = self.list[index] if self.selValue then self.selIndex = index if (self.isMutable or self.dragTargetList) and self:IsShown() then self.selCX = cursorX self.selCY = cursorY self.selDragging = true self.selDragActive = false end if self.OnSelect then self:OnSelect(self.selIndex, self.selValue) end if self.OnSelClick then self:OnSelClick(self.selIndex, self.selValue, doubleClick) end end end elseif #self.list > 0 and not self.selDragActive then if key == "UP" then self:SelectIndex(((self.selIndex or 1) - 2) % #self.list + 1) elseif key == "DOWN" then self:SelectIndex((self.selIndex or #self.list) % #self.list + 1) elseif key == "HOME" then self:SelectIndex(1) elseif key == "END" then self:SelectIndex(#self.list) elseif self.selValue then if key == "c" and IsKeyDown("CTRL") then if self.OnSelCopy then self:OnSelCopy(self.selIndex, self.selValue) end elseif key == "x" and IsKeyDown("CTRL") then if self.OnSelCut then self:OnSelCut(self.selIndex, self.selValue) end elseif key == "BACK" or key == "DELETE" then if self.OnSelDelete then self:OnSelDelete(self.selIndex, self.selValue) end elseif self.OnSelKeyDown then self:OnSelKeyDown(self.selIndex, self.selValue, key) end end end return self end function ListClass:OnKeyUp(key) if not self:IsShown() or not self:IsEnabled() then return end if key == "WHEELDOWN" then self.controls.scrollBar:Scroll(1) elseif key == "WHEELUP" then self.controls.scrollBar:Scroll(-1) elseif self.selValue then if key == "LEFTBUTTON" then self.selDragging = false if self.selDragActive then self.selDragActive = false if self.selDragIndex and self.selDragIndex ~= self.selIndex then t_remove(self.list, self.selIndex) if self.selDragIndex > self.selIndex then self.selDragIndex = self.selDragIndex - 1 end t_insert(self.list, self.selDragIndex, self.selValue) if self.OnOrderChange then self:OnOrderChange() end self.selValue = nil elseif self.dragTarget then self.dragTarget:ReceiveDrag(self.dragType, self.dragValue, self) if self.OnDragSend then self:OnDragSend(self.selIndex, self.selValue, self.dragTarget) end self.selValue = nil end if self.dragTargetList then for _, target in ipairs(self.dragTargetList) do target.otherDragSource = nil target.otherDragTargeting = false end end self.dragType = nil self.dragValue = nil self.dragTarget = nil end end end return self end
UnluckyNinja/PathOfBuilding
Classes/ListControl.lua
Lua
mit
12,361
[ 30522, 1011, 1011, 4130, 1997, 2311, 1011, 1011, 1011, 1011, 2465, 1024, 2862, 2491, 1011, 1011, 3937, 2862, 2491, 1012, 1011, 1011, 1011, 1011, 2023, 2003, 2019, 10061, 2918, 2465, 1025, 5173, 4280, 2064, 4425, 2122, 5144, 1998, 4725, 20...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Taskling.Blocks.RangeBlocks; using Taskling.InfrastructureContracts.Blocks.CommonRequests; namespace Taskling.InfrastructureContracts.Blocks { public interface IRangeBlockRepository { Task ChangeStatusAsync(BlockExecutionChangeStatusRequest changeStatusRequest); Task<RangeBlock> GetLastRangeBlockAsync(LastBlockRequest lastRangeBlockRequest); } }
Vanlightly/Taskling.NET
src/Taskling/InfrastructureContracts/Blocks/IRangeBlockRepository.cs
C#
mit
502
[ 30522, 2478, 2291, 1025, 2478, 2291, 1012, 6407, 1012, 12391, 1025, 2478, 2291, 1012, 11409, 4160, 1025, 2478, 2291, 1012, 3793, 1025, 2478, 2291, 1012, 11689, 2075, 1012, 8518, 1025, 2478, 4708, 2989, 1012, 5991, 1012, 2846, 23467, 2015, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * Created by PhpStorm. * User: rem * Date: 29.01.2015 * Time: 17:55 */ namespace app\commands; use Yii; use yii\console\Controller; class VipsratingController extends Controller { public function actionIndex() { echo "OK\n"; return true; } }
remk-wadriga/vicesisters-yii2-project
commands/VipsratingController.php
PHP
bsd-3-clause
288
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 2580, 2011, 25718, 19718, 1012, 1008, 5310, 1024, 2128, 2213, 1008, 3058, 1024, 2756, 1012, 5890, 1012, 2325, 1008, 2051, 1024, 2459, 1024, 4583, 1008, 1013, 3415, 15327, 10439, 1032, 10954,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <title>org.apache.jmeter.reporters (Apache JMeter API)</title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.jmeter.reporters (Apache JMeter API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><b>Apache JMeter</b></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/jmeter/report/processor/graph/impl/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../org/apache/jmeter/reporters/gui/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/jmeter/reporters/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.apache.jmeter.reporters</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/AbstractListenerElement.html" title="class in org.apache.jmeter.reporters">AbstractListenerElement</a></td> <td class="colLast"> <div class="block">Base class for Listeners</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/MailerModel.html" title="class in org.apache.jmeter.reporters">MailerModel</a></td> <td class="colLast"> <div class="block">The model for a MailerVisualizer.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/MailerResultCollector.html" title="class in org.apache.jmeter.reporters">MailerResultCollector</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/ResultAction.html" title="class in org.apache.jmeter.reporters">ResultAction</a></td> <td class="colLast"> <div class="block">ResultAction - take action based on the status of the last Result</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/ResultCollector.html" title="class in org.apache.jmeter.reporters">ResultCollector</a></td> <td class="colLast"> <div class="block">This class handles all saving of samples.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/ResultCollectorHelper.html" title="class in org.apache.jmeter.reporters">ResultCollectorHelper</a></td> <td class="colLast"> <div class="block">Helper class to allow TestResultWrapperConverter to send samples directly to the visualiser if required.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/ResultSaver.html" title="class in org.apache.jmeter.reporters">ResultSaver</a></td> <td class="colLast"> <div class="block">Save Result responseData to a set of files This is mainly intended for validation tests</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/Summariser.html" title="class in org.apache.jmeter.reporters">Summariser</a></td> <td class="colLast"> <div class="block">Generate a summary of the test run so far to the log file and/or standard output.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/apache/jmeter/reporters/MailerModel.MailAuthType.html" title="enum in org.apache.jmeter.reporters">MailerModel.MailAuthType</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><b>Apache JMeter</b></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/jmeter/report/processor/graph/impl/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../org/apache/jmeter/reporters/gui/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/jmeter/reporters/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#xA9; 1998-2017 Apache Software Foundation. All Rights Reserved.</small></p> </body> </html>
kangli914/JmeterAutomation
apache-jmeter-3.2/docs/api/org/apache/jmeter/reporters/package-summary.html
HTML
apache-2.0
8,001
[ 30522, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 16129, 1018, 1012, 5890, 17459, 1013, 1013, 4372, 1000, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, 8917, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Untitled Document</title> <metaname="viewport" content="width=device-width,user-scalable=no"/> <link rel="stylesheet" href="cssreset.css"/> <style type="text/css"> #content { width: 90%; margin: 10px auto; height: auto; } p { text-indent:2em } </style> <script src="jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".head_img").width($(window).width()); $(".tail_img").width($(window).width()); }); </script> </head> <body> <div id="head"> <img class="head_img" src="head.png"/> </div> <div id="content" align="justify"> <h3 style="text-align: center;">扰乱单位秩序、破坏选举秩序</h3> <p><strong>一、【中华人民共和国治安管理处罚法关于扰乱单位秩序、破坏选举秩序的规定】</strong></p> <p>第二十三条有下列行为之一的,处警告或者二百元以下罚款;情节较重的,处五日以上十日以下拘留,可以并处五百元以下罚款;</p> <p>(一)扰乱机关、团体、企业、事业单位秩序,致使工作、生产、营业、医疗、教学、科研不能正常进行,尚未造成严重损失的;</p> <p>(二)扰乱车站、港口、码头、机场、商场、公园、展览馆或者其他公共场所秩序的;</p> <p>(三)扰乱公共汽车、电车、火车、船舶、航空器或者其他公共交通工具上的秩序的;</p> <p>(四)非法拦截或者强登、扒乘机动车、船舶、航空器以及其他交通工具,影响交通工具正常行驶的;</p> <p>(五)破坏依法进行的选举秩序的。</p> <p>聚众实施前款行为的,对首要分子处十日以上十五日以下拘留,可以并处一千元以下罚款。</p> <p><strong>二、案例解析</strong></p> <p>2月19日下午,在推选村民代表。第一轮投票结束,两名候选人平票,按照程序,这样的情况需要重新投票。候选人蔡某表示抗议,当工作人员拿着选票箱让他投票时,蔡某情绪激动,将投票箱给砸毁,并将选票撕毁。最后,按照《治安管理处罚法》第二十三条规定,蔡某被处以行政拘留5日并处罚款500元。</p> </div> <div id="tail"> <img class="tail_img" src="tail.png"> </div> </body> </html>
zhaishuai/jingmintong
PoliceMessageBoard/PoliceMessageBoard/扰乱单位秩序,选举秩序.html
HTML
mit
2,526
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1013, 1028, 1026, 2516, 1028, 24819, 6254, 1026, 1013, 2516, 1028, 1026, 18804, 18442, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include "gradientwidget.h" #include "ui_gradientwidget.h" GradientWidget::GradientWidget(QWidget *parent) : AbstractWidget(parent), ui(new Ui::GradientWidget) { ui->setupUi(this); connect(ui->nextButton,SIGNAL(clicked(bool)),this,SLOT(nextClick(bool))); hide(); } GradientWidget::~GradientWidget() { delete ui; } void GradientWidget::showEvent(QShowEvent *) { ui->graphicsView->setScene(new QGraphicsScene); } void GradientWidget::execute() { module.mod_main(); m_picture renPic; renPic.width = module.p_width; renPic.height = module.p_height; renPic.data = module.HDR; ui->graphicsView->scene()->addPixmap(QPixmap::fromImage(picToImg(renPic))); ui->graphicsView->scene()->update(); }
LuisHsu/HDRI-Project
gradientwidget.cpp
C++
gpl-3.0
746
[ 30522, 1001, 2421, 1000, 17978, 9148, 24291, 1012, 1044, 1000, 1001, 2421, 1000, 21318, 1035, 17978, 9148, 24291, 1012, 1044, 1000, 17978, 9148, 24291, 1024, 1024, 17978, 9148, 24291, 1006, 1053, 9148, 24291, 1008, 6687, 1007, 1024, 10061, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
require 'fog/openstack/models/model' module Fog module Compute class OpenStack class Flavor < Fog::OpenStack::Model identity :id attribute :name attribute :ram attribute :disk attribute :vcpus attribute :links attribute :swap attribute :rxtx_factor attribute :metadata attribute :ephemeral, :aliases => 'OS-FLV-EXT-DATA:ephemeral' attribute :is_public, :aliases => 'os-flavor-access:is_public' attribute :disabled, :aliases => 'OS-FLV-DISABLED:disabled' def save requires :name, :ram, :vcpus, :disk attributes[:ephemeral] = self.ephemeral || 0 attributes[:is_public] = self.is_public || false attributes[:disabled] = self.disabled || false attributes[:swap] = self.swap || 0 attributes[:rxtx_factor] = self.rxtx_factor || 1.0 merge_attributes(service.create_flavor(self.attributes).body['flavor']) self end def destroy requires :id service.delete_flavor(self.id) true end def metadata service.get_flavor_metadata(self.id).body['extra_specs'] rescue Fog::Compute::OpenStack::NotFound nil end def create_metadata(metadata) service.create_flavor_metadata(self.id, metadata) rescue Fog::Compute::OpenStack::NotFound nil end end end end end
ralzate/Aerosanidad-Correciones
vendor/bundle/ruby/2.2.0/gems/fog-1.35.0/lib/fog/openstack/models/compute/flavor.rb
Ruby
mit
1,492
[ 30522, 5478, 1005, 9666, 1013, 7480, 2696, 3600, 1013, 4275, 1013, 2944, 1005, 11336, 9666, 11336, 24134, 2465, 7480, 30524, 1024, 9785, 17961, 1024, 18315, 12207, 17961, 1024, 6971, 17961, 1024, 19948, 17961, 1024, 1054, 18413, 2595, 1035, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_CREATERESERVEDINSTANCESLISTINGREQUEST_P_H #define QTAWS_CREATERESERVEDINSTANCESLISTINGREQUEST_P_H #include "ec2request_p.h" #include "createreservedinstanceslistingrequest.h" namespace QtAws { namespace EC2 { class CreateReservedInstancesListingRequest; class CreateReservedInstancesListingRequestPrivate : public Ec2RequestPrivate { public: CreateReservedInstancesListingRequestPrivate(const Ec2Request::Action action, CreateReservedInstancesListingRequest * const q); CreateReservedInstancesListingRequestPrivate(const CreateReservedInstancesListingRequestPrivate &other, CreateReservedInstancesListingRequest * const q); private: Q_DECLARE_PUBLIC(CreateReservedInstancesListingRequest) }; } // namespace EC2 } // namespace QtAws #endif
pcolby/libqtaws
src/ec2/createreservedinstanceslistingrequest_p.h
C
lgpl-3.0
1,576
[ 30522, 1013, 1008, 9385, 2286, 1011, 25682, 2703, 18650, 2023, 5371, 2003, 2112, 1997, 1053, 2696, 9333, 1012, 1053, 2696, 9333, 2003, 2489, 4007, 1024, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 19933, 2009, 2104, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright 2017 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 tabletconn import ( "testing" vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc" "github.com/youtube/vitess/go/vt/vterrors" ) func TestTabletErrorFromRPCError(t *testing.T) { testcases := []struct { in *vtrpcpb.RPCError want vtrpcpb.Code }{{ in: &vtrpcpb.RPCError{ LegacyCode: vtrpcpb.LegacyErrorCode_BAD_INPUT_LEGACY, Message: "bad input", }, want: vtrpcpb.Code_INVALID_ARGUMENT, }, { in: &vtrpcpb.RPCError{ LegacyCode: vtrpcpb.LegacyErrorCode_BAD_INPUT_LEGACY, Message: "bad input", Code: vtrpcpb.Code_INVALID_ARGUMENT, }, want: vtrpcpb.Code_INVALID_ARGUMENT, }, { in: &vtrpcpb.RPCError{ Message: "bad input", Code: vtrpcpb.Code_INVALID_ARGUMENT, }, want: vtrpcpb.Code_INVALID_ARGUMENT, }} for _, tcase := range testcases { got := vterrors.Code(ErrorFromVTRPC(tcase.in)) if got != tcase.want { t.Errorf("FromVtRPCError(%v):\n%v, want\n%v", tcase.in, got, tcase.want) } } }
NazarethCollege/heweb2017-devops-presentation
sites/tweetheat/src/backend/vendor/src/github.com/youtube/vitess/go/vt/vttablet/tabletconn/grpc_error_test.go
GO
mit
1,527
[ 30522, 1013, 1008, 9385, 2418, 8224, 4297, 1012, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 2017, 2089, 2025, 2224, 2023, 5371, 3272, 1999, 12646, 2007, 1996, 6105, 1012, 2017, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='reddit_gold', description='reddit gold', version='0.1', author='Chad Birch', author_email='chad@reddit.com', packages=find_packages(), install_requires=[ 'r2', ], entry_points={ 'r2.plugin': ['gold = reddit_gold:Gold'] }, include_package_data=True, zip_safe=False, )
madbook/reddit-plugin-gold
setup.py
Python
bsd-3-clause
418
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 18750, 2013, 16437, 3406, 27896, 12324, 16437, 1010, 2424, 1035, 14555, 16437, 1006, 2171, 1027, 1005, 2417, 23194, 1035, 2751, 1005, 1010, 6412, 1027, 1005, 2417, 23194, 275...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (c) 2001 Vojtech Pavlik * * CATC EL1210A NetMate USB Ethernet driver * * Sponsored by SuSE * * Based on the work of * Donald Becker * * Old chipset support added by Simon Evans <spse@secret.org.uk> 2002 * - adds support for Belkin F5U011 */ /* * 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/>. * * Should you need to contact me, the author, you can do so either by * e-mail - mail your message to <vojtech@suse.cz>, or by paper mail: * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/ethtool.h> #include <linux/crc32.h> #include <linux/bitops.h> #include <linux/gfp.h> #include <linux/uaccess.h> #undef DEBUG #include <linux/usb.h> /* * Version information. */ #define DRIVER_VERSION "v2.8" #define DRIVER_AUTHOR "Vojtech Pavlik <vojtech@suse.cz>" #define DRIVER_DESC "CATC EL1210A NetMate USB Ethernet driver" #define SHORT_DRIVER_DESC "EL1210A NetMate USB Ethernet" MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); static const char driver_name[] = "catc"; /* * Some defines. */ #define STATS_UPDATE (HZ) /* Time between stats updates */ #define TX_TIMEOUT (5*HZ) /* Max time the queue can be stopped */ #define PKT_SZ 1536 /* Max Ethernet packet size */ #define RX_MAX_BURST 15 /* Max packets per rx buffer (> 0, < 16) */ #define TX_MAX_BURST 15 /* Max full sized packets per tx buffer (> 0) */ #define CTRL_QUEUE 16 /* Max control requests in flight (power of two) */ #define RX_PKT_SZ 1600 /* Max size of receive packet for F5U011 */ /* * Control requests. */ enum control_requests { ReadMem = 0xf1, GetMac = 0xf2, Reset = 0xf4, SetMac = 0xf5, SetRxMode = 0xf5, /* F5U011 only */ WriteROM = 0xf8, SetReg = 0xfa, GetReg = 0xfb, WriteMem = 0xfc, ReadROM = 0xfd, }; /* * Registers. */ enum register_offsets { TxBufCount = 0x20, RxBufCount = 0x21, OpModes = 0x22, TxQed = 0x23, RxQed = 0x24, MaxBurst = 0x25, RxUnit = 0x60, EthStatus = 0x61, StationAddr0 = 0x67, EthStats = 0x69, LEDCtrl = 0x81, }; enum eth_stats { TxSingleColl = 0x00, TxMultiColl = 0x02, TxExcessColl = 0x04, RxFramErr = 0x06, }; enum op_mode_bits { Op3MemWaits = 0x03, OpLenInclude = 0x08, OpRxMerge = 0x10, OpTxMerge = 0x20, OpWin95bugfix = 0x40, OpLoopback = 0x80, }; enum rx_filter_bits { RxEnable = 0x01, RxPolarity = 0x02, RxForceOK = 0x04, RxMultiCast = 0x08, RxPromisc = 0x10, AltRxPromisc = 0x20, /* F5U011 uses different bit */ }; enum led_values { LEDFast = 0x01, LEDSlow = 0x02, LEDFlash = 0x03, LEDPulse = 0x04, LEDLink = 0x08, }; enum link_status { LinkNoChange = 0, LinkGood = 1, LinkBad = 2 }; /* * The catc struct. */ #define CTRL_RUNNING 0 #define RX_RUNNING 1 #define TX_RUNNING 2 struct catc { struct net_device *netdev; struct usb_device *usbdev; unsigned long flags; unsigned int tx_ptr, tx_idx; unsigned int ctrl_head, ctrl_tail; spinlock_t tx_lock, ctrl_lock; u8 tx_buf[2][TX_MAX_BURST * (PKT_SZ + 2)]; u8 rx_buf[RX_MAX_BURST * (PKT_SZ + 2)]; u8 irq_buf[2]; u8 ctrl_buf[64]; struct usb_ctrlrequest ctrl_dr; struct timer_list timer; u8 stats_buf[8]; u16 stats_vals[4]; unsigned long last_stats; u8 multicast[64]; struct ctrl_queue { u8 dir; u8 request; u16 value; u16 index; void *buf; int len; void (*callback)(struct catc *catc, struct ctrl_queue *q); } ctrl_queue[CTRL_QUEUE]; struct urb *tx_urb, *rx_urb, *irq_urb, *ctrl_urb; u8 is_f5u011; /* Set if device is an F5U011 */ u8 rxmode[2]; /* Used for F5U011 */ atomic_t recq_sz; /* Used for F5U011 - counter of waiting rx packets */ }; /* * Useful macros. */ #define catc_get_mac(catc, mac) catc_ctrl_msg(catc, USB_DIR_IN, GetMac, 0, 0, mac, 6) #define catc_reset(catc) catc_ctrl_msg(catc, USB_DIR_OUT, Reset, 0, 0, NULL, 0) #define catc_set_reg(catc, reg, val) catc_ctrl_msg(catc, USB_DIR_OUT, SetReg, val, reg, NULL, 0) #define catc_get_reg(catc, reg, buf) catc_ctrl_msg(catc, USB_DIR_IN, GetReg, 0, reg, buf, 1) #define catc_write_mem(catc, addr, buf, size) catc_ctrl_msg(catc, USB_DIR_OUT, WriteMem, 0, addr, buf, size) #define catc_read_mem(catc, addr, buf, size) catc_ctrl_msg(catc, USB_DIR_IN, ReadMem, 0, addr, buf, size) #define f5u011_rxmode(catc, rxmode) catc_ctrl_msg(catc, USB_DIR_OUT, SetRxMode, 0, 1, rxmode, 2) #define f5u011_rxmode_async(catc, rxmode) catc_ctrl_async(catc, USB_DIR_OUT, SetRxMode, 0, 1, &rxmode, 2, NULL) #define f5u011_mchash_async(catc, hash) catc_ctrl_async(catc, USB_DIR_OUT, SetRxMode, 0, 2, &hash, 8, NULL) #define catc_set_reg_async(catc, reg, val) catc_ctrl_async(catc, USB_DIR_OUT, SetReg, val, reg, NULL, 0, NULL) #define catc_get_reg_async(catc, reg, cb) catc_ctrl_async(catc, USB_DIR_IN, GetReg, 0, reg, NULL, 1, cb) #define catc_write_mem_async(catc, addr, buf, size) catc_ctrl_async(catc, USB_DIR_OUT, WriteMem, 0, addr, buf, size, NULL) /* * Receive routines. */ static void catc_rx_done(struct urb *urb) { struct catc *catc = urb->context; u8 *pkt_start = urb->transfer_buffer; struct sk_buff *skb; int pkt_len, pkt_offset = 0; int status = urb->status; if (!catc->is_f5u011) { clear_bit(RX_RUNNING, &catc->flags); pkt_offset = 2; } if (status) { dev_dbg(&urb->dev->dev, "rx_done, status %d, length %d\n", status, urb->actual_length); return; } do { if(!catc->is_f5u011) { pkt_len = le16_to_cpup((__le16*)pkt_start); if (pkt_len > urb->actual_length) { catc->netdev->stats.rx_length_errors++; catc->netdev->stats.rx_errors++; break; } } else { pkt_len = urb->actual_length; } if (!(skb = dev_alloc_skb(pkt_len))) return; skb_copy_to_linear_data(skb, pkt_start + pkt_offset, pkt_len); skb_put(skb, pkt_len); skb->protocol = eth_type_trans(skb, catc->netdev); netif_rx(skb); catc->netdev->stats.rx_packets++; catc->netdev->stats.rx_bytes += pkt_len; /* F5U011 only does one packet per RX */ if (catc->is_f5u011) break; pkt_start += (((pkt_len + 1) >> 6) + 1) << 6; } while (pkt_start - (u8 *) urb->transfer_buffer < urb->actual_length); if (catc->is_f5u011) { if (atomic_read(&catc->recq_sz)) { int state; atomic_dec(&catc->recq_sz); netdev_dbg(catc->netdev, "getting extra packet\n"); urb->dev = catc->usbdev; if ((state = usb_submit_urb(urb, GFP_ATOMIC)) < 0) { netdev_dbg(catc->netdev, "submit(rx_urb) status %d\n", state); } } else { clear_bit(RX_RUNNING, &catc->flags); } } } static void catc_irq_done(struct urb *urb) { struct catc *catc = urb->context; u8 *data = urb->transfer_buffer; int status = urb->status; unsigned int hasdata = 0, linksts = LinkNoChange; int res; if (!catc->is_f5u011) { hasdata = data[1] & 0x80; if (data[1] & 0x40) linksts = LinkGood; else if (data[1] & 0x20) linksts = LinkBad; } else { hasdata = (unsigned int)(be16_to_cpup((__be16*)data) & 0x0fff); if (data[0] == 0x90) linksts = LinkGood; else if (data[0] == 0xA0) linksts = LinkBad; } switch (status) { case 0: /* success */ break; case -ECONNRESET: /* unlink */ case -ENOENT: case -ESHUTDOWN: return; /* -EPIPE: should clear the halt */ default: /* error */ dev_dbg(&urb->dev->dev, "irq_done, status %d, data %02x %02x.\n", status, data[0], data[1]); goto resubmit; } if (linksts == LinkGood) { netif_carrier_on(catc->netdev); netdev_dbg(catc->netdev, "link ok\n"); } if (linksts == LinkBad) { netif_carrier_off(catc->netdev); netdev_dbg(catc->netdev, "link bad\n"); } if (hasdata) { if (test_and_set_bit(RX_RUNNING, &catc->flags)) { if (catc->is_f5u011) atomic_inc(&catc->recq_sz); } else { catc->rx_urb->dev = catc->usbdev; if ((res = usb_submit_urb(catc->rx_urb, GFP_ATOMIC)) < 0) { dev_err(&catc->usbdev->dev, "submit(rx_urb) status %d\n", res); } } } resubmit: res = usb_submit_urb (urb, GFP_ATOMIC); if (res) dev_err(&catc->usbdev->dev, "can't resubmit intr, %s-%s, status %d\n", catc->usbdev->bus->bus_name, catc->usbdev->devpath, res); } /* * Transmit routines. */ static int catc_tx_run(struct catc *catc) { int status; if (catc->is_f5u011) catc->tx_ptr = (catc->tx_ptr + 63) & ~63; catc->tx_urb->transfer_buffer_length = catc->tx_ptr; catc->tx_urb->transfer_buffer = catc->tx_buf[catc->tx_idx]; catc->tx_urb->dev = catc->usbdev; if ((status = usb_submit_urb(catc->tx_urb, GFP_ATOMIC)) < 0) dev_err(&catc->usbdev->dev, "submit(tx_urb), status %d\n", status); catc->tx_idx = !catc->tx_idx; catc->tx_ptr = 0; netif_trans_update(catc->netdev); return status; } static void catc_tx_done(struct urb *urb) { struct catc *catc = urb->context; unsigned long flags; int r, status = urb->status; if (status == -ECONNRESET) { dev_dbg(&urb->dev->dev, "Tx Reset.\n"); urb->status = 0; netif_trans_update(catc->netdev); catc->netdev->stats.tx_errors++; clear_bit(TX_RUNNING, &catc->flags); netif_wake_queue(catc->netdev); return; } if (status) { dev_dbg(&urb->dev->dev, "tx_done, status %d, length %d\n", status, urb->actual_length); return; } spin_lock_irqsave(&catc->tx_lock, flags); if (catc->tx_ptr) { r = catc_tx_run(catc); if (unlikely(r < 0)) clear_bit(TX_RUNNING, &catc->flags); } else { clear_bit(TX_RUNNING, &catc->flags); } netif_wake_queue(catc->netdev); spin_unlock_irqrestore(&catc->tx_lock, flags); } static netdev_tx_t catc_start_xmit(struct sk_buff *skb, struct net_device *netdev) { struct catc *catc = netdev_priv(netdev); unsigned long flags; int r = 0; char *tx_buf; spin_lock_irqsave(&catc->tx_lock, flags); catc->tx_ptr = (((catc->tx_ptr - 1) >> 6) + 1) << 6; tx_buf = catc->tx_buf[catc->tx_idx] + catc->tx_ptr; if (catc->is_f5u011) *(__be16 *)tx_buf = cpu_to_be16(skb->len); else *(__le16 *)tx_buf = cpu_to_le16(skb->len); skb_copy_from_linear_data(skb, tx_buf + 2, skb->len); catc->tx_ptr += skb->len + 2; if (!test_and_set_bit(TX_RUNNING, &catc->flags)) { r = catc_tx_run(catc); if (r < 0) clear_bit(TX_RUNNING, &catc->flags); } if ((catc->is_f5u011 && catc->tx_ptr) || (catc->tx_ptr >= ((TX_MAX_BURST - 1) * (PKT_SZ + 2)))) netif_stop_queue(netdev); spin_unlock_irqrestore(&catc->tx_lock, flags); if (r >= 0) { catc->netdev->stats.tx_bytes += skb->len; catc->netdev->stats.tx_packets++; } dev_kfree_skb(skb); return NETDEV_TX_OK; } static void catc_tx_timeout(struct net_device *netdev) { struct catc *catc = netdev_priv(netdev); dev_warn(&netdev->dev, "Transmit timed out.\n"); usb_unlink_urb(catc->tx_urb); } /* * Control messages. */ static int catc_ctrl_msg(struct catc *catc, u8 dir, u8 request, u16 value, u16 index, void *buf, int len) { int retval = usb_control_msg(catc->usbdev, dir ? usb_rcvctrlpipe(catc->usbdev, 0) : usb_sndctrlpipe(catc->usbdev, 0), request, 0x40 | dir, value, index, buf, len, 1000); return retval < 0 ? retval : 0; } static void catc_ctrl_run(struct catc *catc) { struct ctrl_queue *q = catc->ctrl_queue + catc->ctrl_tail; struct usb_device *usbdev = catc->usbdev; struct urb *urb = catc->ctrl_urb; struct usb_ctrlrequest *dr = &catc->ctrl_dr; int status; dr->bRequest = q->request; dr->bRequestType = 0x40 | q->dir; dr->wValue = cpu_to_le16(q->value); dr->wIndex = cpu_to_le16(q->index); dr->wLength = cpu_to_le16(q->len); urb->pipe = q->dir ? usb_rcvctrlpipe(usbdev, 0) : usb_sndctrlpipe(usbdev, 0); urb->transfer_buffer_length = q->len; urb->transfer_buffer = catc->ctrl_buf; urb->setup_packet = (void *) dr; urb->dev = usbdev; if (!q->dir && q->buf && q->len) memcpy(catc->ctrl_buf, q->buf, q->len); if ((status = usb_submit_urb(catc->ctrl_urb, GFP_ATOMIC))) dev_err(&catc->usbdev->dev, "submit(ctrl_urb) status %d\n", status); } static void catc_ctrl_done(struct urb *urb) { struct catc *catc = urb->context; struct ctrl_queue *q; unsigned long flags; int status = urb->status; if (status) dev_dbg(&urb->dev->dev, "ctrl_done, status %d, len %d.\n", status, urb->actual_length); spin_lock_irqsave(&catc->ctrl_lock, flags); q = catc->ctrl_queue + catc->ctrl_tail; if (q->dir) { if (q->buf && q->len) memcpy(q->buf, catc->ctrl_buf, q->len); else q->buf = catc->ctrl_buf; } if (q->callback) q->callback(catc, q); catc->ctrl_tail = (catc->ctrl_tail + 1) & (CTRL_QUEUE - 1); if (catc->ctrl_head != catc->ctrl_tail) catc_ctrl_run(catc); else clear_bit(CTRL_RUNNING, &catc->flags); spin_unlock_irqrestore(&catc->ctrl_lock, flags); } static int catc_ctrl_async(struct catc *catc, u8 dir, u8 request, u16 value, u16 index, void *buf, int len, void (*callback)(struct catc *catc, struct ctrl_queue *q)) { struct ctrl_queue *q; int retval = 0; unsigned long flags; spin_lock_irqsave(&catc->ctrl_lock, flags); q = catc->ctrl_queue + catc->ctrl_head; q->dir = dir; q->request = request; q->value = value; q->index = index; q->buf = buf; q->len = len; q->callback = callback; catc->ctrl_head = (catc->ctrl_head + 1) & (CTRL_QUEUE - 1); if (catc->ctrl_head == catc->ctrl_tail) { dev_err(&catc->usbdev->dev, "ctrl queue full\n"); catc->ctrl_tail = (catc->ctrl_tail + 1) & (CTRL_QUEUE - 1); retval = -1; } if (!test_and_set_bit(CTRL_RUNNING, &catc->flags)) catc_ctrl_run(catc); spin_unlock_irqrestore(&catc->ctrl_lock, flags); return retval; } /* * Statistics. */ static void catc_stats_done(struct catc *catc, struct ctrl_queue *q) { int index = q->index - EthStats; u16 data, last; catc->stats_buf[index] = *((char *)q->buf); if (index & 1) return; data = ((u16)catc->stats_buf[index] << 8) | catc->stats_buf[index + 1]; last = catc->stats_vals[index >> 1]; switch (index) { case TxSingleColl: case TxMultiColl: catc->netdev->stats.collisions += data - last; break; case TxExcessColl: catc->netdev->stats.tx_aborted_errors += data - last; catc->netdev->stats.tx_errors += data - last; break; case RxFramErr: catc->netdev->stats.rx_frame_errors += data - last; catc->netdev->stats.rx_errors += data - last; break; } catc->stats_vals[index >> 1] = data; } static void catc_stats_timer(struct timer_list *t) { struct catc *catc = from_timer(catc, t, timer); int i; for (i = 0; i < 8; i++) catc_get_reg_async(catc, EthStats + 7 - i, catc_stats_done); mod_timer(&catc->timer, jiffies + STATS_UPDATE); } /* * Receive modes. Broadcast, Multicast, Promisc. */ static void catc_multicast(unsigned char *addr, u8 *multicast) { u32 crc; crc = ether_crc_le(6, addr); multicast[(crc >> 3) & 0x3f] |= 1 << (crc & 7); } static void catc_set_multicast_list(struct net_device *netdev) { struct catc *catc = netdev_priv(netdev); struct netdev_hw_addr *ha; u8 broadcast[ETH_ALEN]; u8 rx = RxEnable | RxPolarity | RxMultiCast; eth_broadcast_addr(broadcast); memset(catc->multicast, 0, 64); catc_multicast(broadcast, catc->multicast); catc_multicast(netdev->dev_addr, catc->multicast); if (netdev->flags & IFF_PROMISC) { memset(catc->multicast, 0xff, 64); rx |= (!catc->is_f5u011) ? RxPromisc : AltRxPromisc; } if (netdev->flags & IFF_ALLMULTI) { memset(catc->multicast, 0xff, 64); } else { netdev_for_each_mc_addr(ha, netdev) { u32 crc = ether_crc_le(6, ha->addr); if (!catc->is_f5u011) { catc->multicast[(crc >> 3) & 0x3f] |= 1 << (crc & 7); } else { catc->multicast[7-(crc >> 29)] |= 1 << ((crc >> 26) & 7); } } } if (!catc->is_f5u011) { catc_set_reg_async(catc, RxUnit, rx); catc_write_mem_async(catc, 0xfa80, catc->multicast, 64); } else { f5u011_mchash_async(catc, catc->multicast); if (catc->rxmode[0] != rx) { catc->rxmode[0] = rx; netdev_dbg(catc->netdev, "Setting RX mode to %2.2X %2.2X\n", catc->rxmode[0], catc->rxmode[1]); f5u011_rxmode_async(catc, catc->rxmode); } } } static void catc_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct catc *catc = netdev_priv(dev); strlcpy(info->driver, driver_name, sizeof(info->driver)); strlcpy(info->version, DRIVER_VERSION, sizeof(info->version)); usb_make_path(catc->usbdev, info->bus_info, sizeof(info->bus_info)); } static int catc_get_link_ksettings(struct net_device *dev, struct ethtool_link_ksettings *cmd) { struct catc *catc = netdev_priv(dev); if (!catc->is_f5u011) return -EOPNOTSUPP; ethtool_link_ksettings_zero_link_mode(cmd, supported); ethtool_link_ksettings_add_link_mode(cmd, supported, 10baseT_Half); ethtool_link_ksettings_add_link_mode(cmd, supported, TP); ethtool_link_ksettings_zero_link_mode(cmd, advertising); ethtool_link_ksettings_add_link_mode(cmd, advertising, 10baseT_Half); ethtool_link_ksettings_add_link_mode(cmd, advertising, TP); cmd->base.speed = SPEED_10; cmd->base.duplex = DUPLEX_HALF; cmd->base.port = PORT_TP; cmd->base.phy_address = 0; cmd->base.autoneg = AUTONEG_DISABLE; return 0; } static const struct ethtool_ops ops = { .get_drvinfo = catc_get_drvinfo, .get_link = ethtool_op_get_link, .get_link_ksettings = catc_get_link_ksettings, }; /* * Open, close. */ static int catc_open(struct net_device *netdev) { struct catc *catc = netdev_priv(netdev); int status; catc->irq_urb->dev = catc->usbdev; if ((status = usb_submit_urb(catc->irq_urb, GFP_KERNEL)) < 0) { dev_err(&catc->usbdev->dev, "submit(irq_urb) status %d\n", status); return -1; } netif_start_queue(netdev); if (!catc->is_f5u011) mod_timer(&catc->timer, jiffies + STATS_UPDATE); return 0; } static int catc_stop(struct net_device *netdev) { struct catc *catc = netdev_priv(netdev); netif_stop_queue(netdev); if (!catc->is_f5u011) del_timer_sync(&catc->timer); usb_kill_urb(catc->rx_urb); usb_kill_urb(catc->tx_urb); usb_kill_urb(catc->irq_urb); usb_kill_urb(catc->ctrl_urb); return 0; } static const struct net_device_ops catc_netdev_ops = { .ndo_open = catc_open, .ndo_stop = catc_stop, .ndo_start_xmit = catc_start_xmit, .ndo_tx_timeout = catc_tx_timeout, .ndo_set_rx_mode = catc_set_multicast_list, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; /* * USB probe, disconnect. */ static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct device *dev = &intf->dev; struct usb_device *usbdev = interface_to_usbdev(intf); struct net_device *netdev; struct catc *catc; u8 broadcast[ETH_ALEN]; int pktsz, ret; if (usb_set_interface(usbdev, intf->altsetting->desc.bInterfaceNumber, 1)) { dev_err(dev, "Can't set altsetting 1.\n"); return -EIO; } netdev = alloc_etherdev(sizeof(struct catc)); if (!netdev) return -ENOMEM; catc = netdev_priv(netdev); netdev->netdev_ops = &catc_netdev_ops; netdev->watchdog_timeo = TX_TIMEOUT; netdev->ethtool_ops = &ops; catc->usbdev = usbdev; catc->netdev = netdev; spin_lock_init(&catc->tx_lock); spin_lock_init(&catc->ctrl_lock); timer_setup(&catc->timer, catc_stats_timer, 0); catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL); catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL); catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL); catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL); if ((!catc->ctrl_urb) || (!catc->tx_urb) || (!catc->rx_urb) || (!catc->irq_urb)) { dev_err(&intf->dev, "No free urbs available.\n"); ret = -ENOMEM; goto fail_free; } /* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */ if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 && le16_to_cpu(usbdev->descriptor.idProduct) == 0xa && le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) { dev_dbg(dev, "Testing for f5u011\n"); catc->is_f5u011 = 1; atomic_set(&catc->recq_sz, 0); pktsz = RX_PKT_SZ; } else { pktsz = RX_MAX_BURST * (PKT_SZ + 2); } usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0), NULL, NULL, 0, catc_ctrl_done, catc); usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1), NULL, 0, catc_tx_done, catc); usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1), catc->rx_buf, pktsz, catc_rx_done, catc); usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2), catc->irq_buf, 2, catc_irq_done, catc, 1); if (!catc->is_f5u011) { u32 *buf; int i; dev_dbg(dev, "Checking memory size\n"); buf = kmalloc(4, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto fail_free; } *buf = 0x12345678; catc_write_mem(catc, 0x7a80, buf, 4); *buf = 0x87654321; catc_write_mem(catc, 0xfa80, buf, 4); catc_read_mem(catc, 0x7a80, buf, 4); switch (*buf) { case 0x12345678: catc_set_reg(catc, TxBufCount, 8); catc_set_reg(catc, RxBufCount, 32); dev_dbg(dev, "64k Memory\n"); break; default: dev_warn(&intf->dev, "Couldn't detect memory size, assuming 32k\n"); case 0x87654321: catc_set_reg(catc, TxBufCount, 4); catc_set_reg(catc, RxBufCount, 16); dev_dbg(dev, "32k Memory\n"); break; } kfree(buf); dev_dbg(dev, "Getting MAC from SEEROM.\n"); catc_get_mac(catc, netdev->dev_addr); dev_dbg(dev, "Setting MAC into registers.\n"); for (i = 0; i < 6; i++) catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]); dev_dbg(dev, "Filling the multicast list.\n"); eth_broadcast_addr(broadcast); catc_multicast(broadcast, catc->multicast); catc_multicast(netdev->dev_addr, catc->multicast); catc_write_mem(catc, 0xfa80, catc->multicast, 64); dev_dbg(dev, "Clearing error counters.\n"); for (i = 0; i < 8; i++) catc_set_reg(catc, EthStats + i, 0); catc->last_stats = jiffies; dev_dbg(dev, "Enabling.\n"); catc_set_reg(catc, MaxBurst, RX_MAX_BURST); catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits); catc_set_reg(catc, LEDCtrl, LEDLink); catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast); } else { dev_dbg(dev, "Performing reset\n"); catc_reset(catc); catc_get_mac(catc, netdev->dev_addr); dev_dbg(dev, "Setting RX Mode\n"); catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast; catc->rxmode[1] = 0; f5u011_rxmode(catc, catc->rxmode); } dev_dbg(dev, "Init done.\n"); printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n", netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate", usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr); usb_set_intfdata(intf, catc); SET_NETDEV_DEV(netdev, &intf->dev); ret = register_netdev(netdev); if (ret) goto fail_clear_intfdata; return 0; fail_clear_intfdata: usb_set_intfdata(intf, NULL); fail_free: usb_free_urb(catc->ctrl_urb); usb_free_urb(catc->tx_urb); usb_free_urb(catc->rx_urb); usb_free_urb(catc->irq_urb); free_netdev(netdev); return ret; } static void catc_disconnect(struct usb_interface *intf) { struct catc *catc = usb_get_intfdata(intf); usb_set_intfdata(intf, NULL); if (catc) { unregister_netdev(catc->netdev); usb_free_urb(catc->ctrl_urb); usb_free_urb(catc->tx_urb); usb_free_urb(catc->rx_urb); usb_free_urb(catc->irq_urb); free_netdev(catc->netdev); } } /* * Module functions and tables. */ static const struct usb_device_id catc_id_table[] = { { USB_DEVICE(0x0423, 0xa) }, /* CATC Netmate, Belkin F5U011 */ { USB_DEVICE(0x0423, 0xc) }, /* CATC Netmate II, Belkin F5U111 */ { USB_DEVICE(0x08d1, 0x1) }, /* smartBridges smartNIC */ { } }; MODULE_DEVICE_TABLE(usb, catc_id_table); static struct usb_driver catc_driver = { .name = driver_name, .probe = catc_probe, .disconnect = catc_disconnect, .id_table = catc_id_table, .disable_hub_initiated_lpm = 1, }; module_usb_driver(catc_driver);
hannes/linux
drivers/net/usb/catc.c
C
gpl-2.0
24,487
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2541, 29536, 3501, 15007, 6643, 2615, 18393, 1008, 1008, 4937, 2278, 3449, 12521, 10790, 2050, 5658, 8585, 18833, 26110, 4062, 1008, 1008, 6485, 2011, 10514, 3366, 1008, 1008, 2241, 2006, 199...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_07) on Tue Oct 16 12:57:45 EDT 2007 --> <TITLE> TermNumber </TITLE> <META NAME="keywords" CONTENT="JSHOP2.TermNumber class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="TermNumber"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../JSHOP2/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../JSHOP2/TermList.html" title="class in JSHOP2"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../JSHOP2/TermVariable.html" title="class in JSHOP2"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?JSHOP2/TermNumber.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TermNumber.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> JSHOP2</FONT> <BR> Class TermNumber</H2> <PRE> java.lang.Object <IMG SRC="../resources/inherit.gif" ALT="extended by "><A HREF="../JSHOP2/CompileTimeObject.html" title="class in JSHOP2">JSHOP2.CompileTimeObject</A> <IMG SRC="../resources/inherit.gif" ALT="extended by "><A HREF="../JSHOP2/Term.html" title="class in JSHOP2">JSHOP2.Term</A> <IMG SRC="../resources/inherit.gif" ALT="extended by "><B>JSHOP2.TermNumber</B> </PRE> <HR> <DL> <DT><PRE>public class <B>TermNumber</B><DT>extends <A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A></DL> </PRE> <P> Each numerical term both at compile time and at run time, is an instance of this class. <P> <P> <DL> <DT><B>Version:</B></DT> <DD>1.0.3</DD> <DT><B>Author:</B></DT> <DD>Okhtay Ilghami, <a href="http://www.cs.umd.edu/~okhtay">http://www.cs.umd.edu/~okhtay</a></DD> </DL> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>private &nbsp;double</CODE></FONT></TD> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#number">number</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The value of the numerical term.</TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_JSHOP2.CompileTimeObject"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Fields inherited from class JSHOP2.<A HREF="../JSHOP2/CompileTimeObject.html" title="class in JSHOP2">CompileTimeObject</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../JSHOP2/CompileTimeObject.html#endl">endl</A></CODE></TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#TermNumber(double)">TermNumber</A></B>(double&nbsp;numberIn)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To initialize this numerical term.</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#bind(JSHOP2.Term[])">bind</A></B>(<A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A>[]&nbsp;binding)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Since this term is a numerical term, binding will not change it, therefore, simply this numerical term itself is returned.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#equals(JSHOP2.Term)">equals</A></B>(<A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A>&nbsp;t)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Whether or not another term is equivalent to this numerical term.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#findUnifier(JSHOP2.Term, JSHOP2.Term[])">findUnifier</A></B>(<A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A>&nbsp;t, <A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A>[]&nbsp;binding)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Find a unifier between this numerical term and another given term.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;double</CODE></FONT></TD> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#getNumber()">getNumber</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To get the value of this numerical term.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#isGround()">isGround</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This function always returns <code>true</code> because a numerical term is always ground by definition.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#toCode()">toCode</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This function produces Java code to create this numerical.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../JSHOP2/TermNumber.html#toString()">toString</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This function returns the <code>String</code> representation of the value of this numerical term.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_JSHOP2.Term"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class JSHOP2.<A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../JSHOP2/Term.html#isNil()">isNil</A>, <A HREF="../JSHOP2/Term.html#merge(JSHOP2.Term[][], int)">merge</A>, <A HREF="../JSHOP2/Term.html#merge(JSHOP2.Term[], JSHOP2.Term[])">merge</A>, <A HREF="../JSHOP2/Term.html#print()">print</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="number"><!-- --></A><H3> number</H3> <PRE> private double <B>number</B></PRE> <DL> <DD>The value of the numerical term. <P> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="TermNumber(double)"><!-- --></A><H3> TermNumber</H3> <PRE> public <B>TermNumber</B>(double&nbsp;numberIn)</PRE> <DL> <DD>To initialize this numerical term. <P> <DL> <DT><B>Parameters:</B><DD><CODE>numberIn</CODE> - the value this numerical term is set to have.</DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="bind(JSHOP2.Term[])"><!-- --></A><H3> bind</H3> <PRE> public <A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A> <B>bind</B>(<A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A>[]&nbsp;binding)</PRE> <DL> <DD>Since this term is a numerical term, binding will not change it, therefore, simply this numerical term itself is returned. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../JSHOP2/Term.html#bind(JSHOP2.Term[])">bind</A></CODE> in class <CODE><A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A></CODE></DL> </DD> <DD><DL> <DT><B>Parameters:</B><DD><CODE>binding</CODE> - an array of terms, indexed by the integers associated with variable symbols. <DT><B>Returns:</B><DD>the result of binding.</DL> </DD> </DL> <HR> <A NAME="equals(JSHOP2.Term)"><!-- --></A><H3> equals</H3> <PRE> public boolean <B>equals</B>(<A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A>&nbsp;t)</PRE> <DL> <DD>Whether or not another term is equivalent to this numerical term. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../JSHOP2/Term.html#equals(JSHOP2.Term)">equals</A></CODE> in class <CODE><A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A></CODE></DL> </DD> <DD><DL> <DT><B>Parameters:</B><DD><CODE>t</CODE> - the term being compared to this term. <DT><B>Returns:</B><DD><code>true</code> if the two terms are equal, <code>false</code> otherwise.</DL> </DD> </DL> <HR> <A NAME="findUnifier(JSHOP2.Term, JSHOP2.Term[])"><!-- --></A><H3> findUnifier</H3> <PRE> public boolean <B>findUnifier</B>(<A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A>&nbsp;t, <A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A>[]&nbsp;binding)</PRE> <DL> <DD>Find a unifier between this numerical term and another given term. Since this term is a number, this boils down to whether or not the other given term is equal to this one. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../JSHOP2/Term.html#findUnifier(JSHOP2.Term, JSHOP2.Term[])">findUnifier</A></CODE> in class <CODE><A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A></CODE></DL> </DD> <DD><DL> <DT><B>Parameters:</B><DD><CODE>t</CODE> - the term with which we are finding a unifier.<DD><CODE>binding</CODE> - the unifier to be returned. <DT><B>Returns:</B><DD><code>false</code> if the two terms can not be unified, <code>true</code> otherwise.</DL> </DD> </DL> <HR> <A NAME="getNumber()"><!-- --></A><H3> getNumber</H3> <PRE> public double <B>getNumber</B>()</PRE> <DL> <DD>To get the value of this numerical term. <P> <DD><DL> <DT><B>Returns:</B><DD>the value of this numerical term.</DL> </DD> </DL> <HR> <A NAME="isGround()"><!-- --></A><H3> isGround</H3> <PRE> public boolean <B>isGround</B>()</PRE> <DL> <DD>This function always returns <code>true</code> because a numerical term is always ground by definition. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../JSHOP2/Term.html#isGround()">isGround</A></CODE> in class <CODE><A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A></CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD><code>true</code> if this term is ground, <code>false</code> otherwise.</DL> </DD> </DL> <HR> <A NAME="toCode()"><!-- --></A><H3> toCode</H3> <PRE> public java.lang.String <B>toCode</B>()</PRE> <DL> <DD>This function produces Java code to create this numerical. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../JSHOP2/CompileTimeObject.html#toCode()">toCode</A></CODE> in class <CODE><A HREF="../JSHOP2/CompileTimeObject.html" title="class in JSHOP2">CompileTimeObject</A></CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>the produced code as a <code>String</code>.</DL> </DD> </DL> <HR> <A NAME="toString()"><!-- --></A><H3> toString</H3> <PRE> public java.lang.String <B>toString</B>()</PRE> <DL> <DD>This function returns the <code>String</code> representation of the value of this numerical term. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../JSHOP2/Term.html#toString()">toString</A></CODE> in class <CODE><A HREF="../JSHOP2/Term.html" title="class in JSHOP2">Term</A></CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>the printable <code>String</code> that shows the value of this term.</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../JSHOP2/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../JSHOP2/TermList.html" title="class in JSHOP2"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../JSHOP2/TermVariable.html" title="class in JSHOP2"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?JSHOP2/TermNumber.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TermNumber.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
tranchis/jshop2-rt
doc/JSHOP2/TermNumber.html
HTML
gpl-3.0
18,835
[ 30522, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 16129, 1018, 1012, 5890, 17459, 1013, 1013, 4372, 1000, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, 8917, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.argcv.valhalla.client import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger import com.argcv.valhalla.console.ColorForConsole._ import com.argcv.valhalla.exception.ExceptionHelper.{ SafeExec, SafeExecWithTrace } import com.argcv.valhalla.utils.Awakable import com.mongodb.Bytes import com.mongodb.casbah.Imports import com.mongodb.casbah.Imports._ import com.mongodb.casbah.MongoClientOptions.Builder import com.mongodb.casbah.commons.TypeImports import org.bson.types.ObjectId import scala.concurrent.{ ExecutionContext, Future } import scala.reflect.ClassTag /** * * @author Yu Jing <yu@argcv.com> on 10/31/16 */ case class MongoDBClient( db: String = "admin", auth: Option[(String, String, String)] = None, // user pass, authdb addrs: Array[(String, Int)] = Array[(String, Int)](("localhost", 27017)), // lifeTimeMs: Int = 1000 * 60 * 30, // in ms idleTimeMs: Int = 1000 * 60 * 30, // in ms maxWaitTimeMs: Int = 1000 * 20, // wait for query: 20 sec sockTimeMs: Int = 1000 * 20, // wait for socket connection: 20 sec minPerHostFactor: Double = 1.0, // min connection number: cpu cores * factor maxPerHostFactor: Double = 3.0, // max connection number: cpu cores * factor minPerHost: Int = 1, maxPerHost: Int = 32, threadsAllowedToBlockForConnectionMultiplier: Int = 1500, defaultPreference: ReadPreference = ReadPreference.Nearest) extends Awakable { lazy val d: MongoDB = init(addrs, db, auth, primary = false)(db) lazy val dPrimary: MongoDB = init(addrs, db, auth, primary = true)(db) lazy val nProcessors = MongoDBClient.nProcessors lazy val label = MongoDBClient.label /** * get collection from current db * * @param name collection name */ def coll(name: String, db: MongoDB = d): MongoCollection = db(name) /** * loop a collection * * @param coll collection * @param query query * @param fields fields * @param skip skip * @param limit limit * @param snapshot use option: snapshot * @param persist use option: persist * @param primary use primary data * @param bufferSize buffer size * @param body body */ def parForeach(coll: MongoCollection)(query: DBObject = null, fields: Array[String] = null, skip: Int = 0, limit: Int = 0, snapshot: Boolean = false, persist: Boolean = false, primary: Boolean = false, bufferSize: Int = 4096)(body: DBObject => Unit): Unit = { val buffMaxSize = bufferSize max 1 val buffCSize = new AtomicInteger() foreach(coll = coll)( query = query, fields = fields, skip = skip, limit = limit, snapshot = snapshot, persist = persist, primary = primary ) { obj => while (buffCSize.get() > buffMaxSize) () buffCSize.incrementAndGet() Future { try { SafeExecWithTrace(body(obj)) } finally { buffCSize.decrementAndGet() } }(MongoDBClient.mongoForeachExecutionContext) } while (buffCSize.get > 0) () } /** * loop a collection * * @param coll collection * @param query query * @param fields fields * @param skip skip * @param limit limit * @param snapshot use option: snapshot * @param persist use option: persist * @param primary use primary data * @param body body */ def foreach(coll: MongoCollection)(query: DBObject = null, fields: Array[String] = null, skip: Int = 0, limit: Int = 0, snapshot: Boolean = false, persist: Boolean = false, primary: Boolean = false)(body: DBObject => Unit): Unit = { val hcoll = coll.readPrefs(primary) var reqFields = MongoDBObject() if (fields != null) { fields.foreach { x => reqFields = reqFields ++ (x -> 1) } } var curs = query match { case null => fields match { case null => hcoll.find() case _ => hcoll.find(MongoDBObject(), reqFields) } case _ => fields match { case null => hcoll.find(query) case _ => hcoll.find(query, reqFields) } } if (skip > 0) curs.skip(skip) if (limit > 0) curs.limit(limit) if (snapshot) curs = curs.snapshot() if (persist) curs.options_=(Bytes.QUERYOPTION_NOTIMEOUT) SafeExecWithTrace(while (curs.hasNext) SafeExecWithTrace(body(curs.next()))) SafeExecWithTrace(curs.close()) } /** * Here is a sample : * {{{ * case class Param(...) * val d = Param(values) * loopCollection[]( * coll = someCol, * handle = (obj: DBObject, d: Param) => { * // process your collection * }, * data = d, * persist = true) * }}} * * * It will loop this collection * * @return * @author yu */ def loopCollection[T]( coll: MongoCollection, handle: (DBObject, T) => Unit, data: T = null, // may ignored query: DBObject = null, fields: Array[String] = null, skip: Int = 0, limit: Int = 0, snapshot: Boolean = false, persist: Boolean = false, primary: Boolean = false): Unit = { val hcoll = coll.readPrefs(primary) var reqFields = MongoDBObject() if (fields != null) { fields.foreach { x => reqFields = reqFields ++ (x -> 1) } } var curs = query match { case null => fields match { case null => hcoll.find() case _ => hcoll.find(MongoDBObject(), reqFields) } case _ => fields match { case null => hcoll.find(query) case _ => hcoll.find(query, reqFields) } } if (skip > 0) curs.skip(skip) if (limit > 0) curs.limit(limit) if (snapshot) curs = curs.snapshot() if (persist) curs.options_=(Bytes.QUERYOPTION_NOTIMEOUT) // curs.foreach { x => handle(x, data) } // handle exception SafeExecWithTrace(while (curs.hasNext) SafeExecWithTrace(handle(curs.next(), data))) SafeExecWithTrace(curs.close()) } /** * Here is a sample : * {{{ * var count = 0 * case class Param(...) * val d = Param(values) * loopCollection[]( * coll = someCol, * handle = (obj: DBObject, d: Param) => { * // process your collection * * count = count + 1 * if(count > 100) false // stop loop * else true // continue loop * }, * data = d, * persist = true) * }}} * * * loop will broken if you return false * * @return * @author yu */ def loopCollectionWithBreak[T]( coll: MongoCollection, handle: (DBObject, T) => Boolean, data: T, query: DBObject = null, fields: Array[String] = null, skip: Int = 0, limit: Int = 0, snapshot: Boolean = false, persist: Boolean = false, primary: Boolean = false): Unit = { val hcoll = coll.readPrefs(primary) var reqFields = MongoDBObject() if (fields != null) { fields.foreach { x => reqFields = reqFields ++ (x -> 1) } } var curs = query match { case null => fields match { case null => hcoll.find() case _ => hcoll.find(MongoDBObject(), reqFields) } case _ => fields match { case null => hcoll.find(query) case _ => hcoll.find(query, reqFields) } } if (skip > 0) curs.skip(skip) if (limit > 0) curs.limit(limit) if (snapshot) curs = curs.snapshot() if (persist) curs.options_=(Bytes.QUERYOPTION_NOTIMEOUT) var doContinue = true try { SafeExecWithTrace( while (curs.hasNext && doContinue) SafeExecWithTrace(doContinue = handle(curs.next(), data))) } finally { curs.close() } } def findOneByOid(coll: MongoCollection, oid: String, fields: Array[String] = null, primary: Boolean = false): Option[DBObject] = { val hcoll = coll.readPrefs(primary) oid.oid match { case Some(ooid) => fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.findOne(MongoDBObject("_id" -> ooid), reqFields) case null => hcoll.findOneByID(ooid) } case None => None } } def findOneByKeyValue(coll: MongoCollection, key: String, value: Any, fields: Array[String] = null, primary: Boolean = false): Option[DBObject] = { val hcoll = coll.readPrefs(primary) fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.findOne(MongoDBObject(key -> value), reqFields) case null => hcoll.findOne(MongoDBObject(key -> value)) } } /** * find 0 or several by key and value * * @param coll collection name * @param key key name * @param value value name * @param fields request fields null for all * @tparam T type * @return */ def findByKeyValue[T: ClassTag](coll: MongoCollection, key: String, value: T, fields: Array[String] = null, primary: Boolean = false): Array[DBObject] = { val hcoll = coll.readPrefs(primary) try { fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.find(MongoDBObject(key -> value), reqFields).toArray case null => hcoll.find(MongoDBObject(key -> value)).toArray } } catch { case e: Exception => e.printStackTrace() Array[DBObject]() } } /** * find 0 or several by key and value * * @param coll collection name * @param key key name * @param value value name * @param fields request fields null for all * @tparam T type * @return */ def findSliceByKeyValue[T: ClassTag](coll: MongoCollection, key: String, value: T, offset: Int, size: Int, fields: Array[String] = null, primary: Boolean = false): Array[DBObject] = { val hcoll = coll.readPrefs(primary) try { fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.find(MongoDBObject(key -> value), reqFields).skip(offset).limit(size).toArray case null => hcoll.find(MongoDBObject(key -> value)).skip(offset).limit(size).toArray } } catch { case e: Exception => e.printStackTrace() Array[DBObject]() } } /** * find 0 or several by key and value * * @param coll collection name * @param fields request fields null for all * @tparam T type * @return * @param query query db Object */ def findOneByQuery[T: ClassTag](coll: MongoCollection, query: DBObject, fields: Array[String] = null, primary: Boolean = false): Option[DBObject] = { val hcoll = coll.readPrefs(primary) try { fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.findOne(query, reqFields) case null => hcoll.findOne(query) } } catch { case e: Exception => e.printStackTrace() None } } /** * find 0 or several by key and value * * @param coll collection name * @param fields request fields null for all * @return * @param query query db Object * @param primary force use primary db */ def findByQuery(coll: MongoCollection, query: DBObject, fields: Array[String] = null, primary: Boolean = false): Array[DBObject] = { val hcoll = coll.readPrefs(primary) try { fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.find(query, reqFields).toArray case null => hcoll.find(query).toArray } } catch { case e: Exception => e.printStackTrace() Array[DBObject]() } } /** * find 0 or several by key and value * * @param coll collection name * @param fields request fields null for all * @return * @param query query db Object * @param primary force use primary db */ def findSliceByQuery[T: ClassTag](coll: MongoCollection, query: DBObject, offset: Int, size: Int, fields: Array[String] = null, primary: Boolean = false): Array[DBObject] = { val hcoll = coll.readPrefs(primary) try { fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.find(query, reqFields).skip(offset).limit(size).toArray case null => hcoll.find(query).skip(offset).limit(size).toArray } } catch { case e: Exception => e.printStackTrace() Array[DBObject]() } } /** * find on by ObjectIds * * @param coll collection name * @param ids id array * @param fields field * @return */ def findByOids(coll: MongoCollection, ids: Array[String], fields: Array[String] = null, primary: Boolean = false): Array[DBObject] = { val hcoll = coll.readPrefs(primary) val oids = ids.flatMap(_.oid).toList if (oids.nonEmpty) { try { if (fields == null) { hcoll.find(MongoDBObject("_id" -> MongoDBObject("$in" -> oids))).toArray } else { var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.find(MongoDBObject("_id" -> MongoDBObject("$in" -> oids)), reqFields).toArray } } catch { case t: java.lang.IllegalArgumentException => ids.grouped(ids.length / 10 + 1).toArray.par.flatMap(subIds => findByOids(hcoll, subIds, fields)).toArray case e: Exception => e.printStackTrace() Array[DBObject]() } } else { Array[DBObject]() } } /** * find doc by key and values * * @param coll collection name * @param key name of keyword * @param value value array of keyworrd * @param fields fields to check * @tparam T value type * @return */ def findByKeyValues[T: ClassTag](coll: MongoCollection, key: String, value: Array[T], fields: Array[String] = null, primary: Boolean = false): Array[DBObject] = { val hcoll = coll.readPrefs(primary) try { fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.find(MongoDBObject(key -> MongoDBObject("$in" -> value.toList)), reqFields).toArray case null => hcoll.find(MongoDBObject(key -> MongoDBObject("$in" -> value.toList))).toArray } } catch { case t: java.lang.IllegalArgumentException => value.grouped(value.length / 10 + 1).toArray.par.flatMap(subIds => findByKeyValues[T](hcoll, key, subIds, fields)).toArray case e: Exception => e.printStackTrace() Array[DBObject]() } } /** * find 0 or several by key and value * * @param coll collection name * @param key key name * @param value value name * @param fields request fields null for all * @tparam T type * @return */ def findSliceByKeyValues[T: ClassTag](coll: MongoCollection, key: String, value: Array[T], offset: Int, size: Int, fields: Array[String] = null, primary: Boolean = false): Array[DBObject] = { val hcoll = coll.readPrefs(primary) try { fields match { case f: Array[String] => var reqFields = MongoDBObject() fields.foreach { x => reqFields = reqFields ++ (x -> 1) } hcoll.find(MongoDBObject(key -> MongoDBObject("$in" -> value.toList)), reqFields).skip(offset).limit(size).toArray case null => hcoll.find(MongoDBObject(key -> MongoDBObject("$in" -> value.toList))).skip(offset).limit(size).toArray } } catch { case t: java.lang.IllegalArgumentException => value.grouped(value.length / 10 + 1).toArray.par.flatMap(subIds => findByKeyValues[T](hcoll, key, subIds, fields)).toArray case e: Exception => e.printStackTrace() Array[DBObject]() } } /** * remove doc by ObjectID * * @param coll collection name * @param id id * @return */ def rmByOid(coll: MongoCollection, id: String): Boolean = { rmByQuery(coll, MongoDBObject("_id" -> new ObjectId(id))) } /** * remove by ObjectIDs * * @param coll collection name * @param ids id array * @return */ def rmByOids(coll: MongoCollection, ids: Array[String]): Boolean = { val oids: List[TypeImports.ObjectId] = ids.flatMap(_.oid).toList rmByQuery(coll, MongoDBObject("_id" -> MongoDBObject("$in" -> oids))) } /** * remove by one key * * @param coll collection name * @return * @param query rm query */ def rmByQuery(coll: MongoCollection, query: DBObject): Boolean = SafeExecWithTrace(coll.remove(query)).isDefined /** * remove by one key * * @param coll collection name * @param key keyword name * @param value keyword value * @return */ def rmByKeyValue(coll: MongoCollection, key: String, value: Any): Boolean = rmByQuery(coll, MongoDBObject(key -> value)) /** * safe one object * * @param coll collection name * @param item object to save * @return */ def saveObject(coll: MongoCollection, item: DBObject): Option[WriteResult] = { SafeExecWithTrace(coll.save(item)) } /** * batch insert objects, return bulk write result * * @param coll collection name * @param items DBObject Array * @return */ def batchInsert(coll: MongoCollection, items: Array[DBObject]): Option[BulkWriteResult] = { SafeExecWithTrace { val builder = coll.initializeOrderedBulkOperation items.foreach { x => builder.insert(x) } builder.execute() } } /** * get total count of collection. * this is because of there may something wrong in performance of * `count` function `TokuMX` * * @param coll collection name * @return */ def count(coll: MongoCollection): Int = { SafeExecWithTrace(coll.count()).getOrElse(0) } /** * create a new object id * * @return */ def newObjectId(): ObjectId = new ObjectId() def isValidObjectId(oid: String) = SafeExec(ObjectId.isValid(oid)).getOrElse(false) /** * create a new mongo db connection * * @param addrs addres * @param dbname db name * @param primary primary? * @param auth auth(username and password, or empty) */ private def init(addrs: Array[(String, Int)], dbname: String, auth: Option[(String, String, String)], primary: Boolean = false): MongoClient = { val minConnections = (nProcessors * minPerHostFactor).toInt max minPerHost val maxConnections = (nProcessors * maxPerHostFactor).toInt min maxPerHost max minConnections //def mongoConn(host: String, port: Int, user: String, dbname: String, pass: Array[Char], addrs: Array[(String, Int)]): MongoClient = { //println(MONGO_HOST + "\t" + MONGO_PORT + "\t" + MONGO_USER + "\t" + MONGO_DB) // + "\t" + MONGO_PASS.toString) if (auth.isDefined) { logger.info(s"[$label] auth... user:[${auth.get._1}] db:[$dbname] auth db:[${auth.get._3}]") } else { logger.info(s"[$label] no-auth.. db:[$dbname] ") } addrs.foreach(x => logger.info(s"[$label] server:" + s" ${x._1.toString.withColor(BLUE)}:${x._2.toString.withColor(YELLOW)}")) //val server = new ServerAddress(host, port) val credentials: List[MongoCredential] = auth match { case Some(a) => List[MongoCredential](MongoCredential.createCredential(a._1, auth.get._3, a._2.toCharArray)) case None => List[MongoCredential]() } val optBuilder: Builder = new MongoClientOptions.Builder() optBuilder.maxConnectionLifeTime(lifeTimeMs) optBuilder.maxConnectionIdleTime(idleTimeMs) optBuilder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier) optBuilder.minConnectionsPerHost(minConnections) optBuilder.connectionsPerHost(maxConnections) optBuilder.socketTimeout(sockTimeMs) // 60 seconds of socket read optBuilder.maxWaitTime(maxWaitTimeMs) logger.info(s"[$label] timeouts: " + s"life[$lifeTimeMs](ms), " + s"idle[$idleTimeMs](ms), " + s"sock[$sockTimeMs](s), " + s"wait[$maxWaitTimeMs](s), " + s"min connection[$minConnections](fact. $minPerHostFactor / $minPerHost), " + s"max connection[$maxConnections](fact. $maxPerHostFactor / $maxPerHost), " + s"threads allowed to block for connection multiplier[$threadsAllowedToBlockForConnectionMultiplier]") if (primary) optBuilder.readPreference(ReadPreference.Primary) else optBuilder.readPreference(defaultPreference) val opt: MongoClientOptions = optBuilder.build() val conn: MongoClient = com.mongodb.casbah.Imports.MongoClient( replicaSetSeeds = addrs.toList collect { case addr: (String, Int) => new ServerAddress(addr._1, addr._2) }, credentials = credentials, options = opt) conn } /** * @param c collection */ implicit class CollPreferenceOpt(c: MongoCollection) { def readPrefs(primaryOnly: Boolean = false): Imports.MongoCollection = { if (primaryOnly) { coll(c.getName, dPrimary) } else c } } implicit class SafeToObjectId(id: String) { def oid: Option[ObjectId] = SafeExec(new ObjectId(id)) } } object MongoDBClient extends Awakable { lazy val label = "MongoDBClient".withColor(GREEN) lazy val poolSizeMin = 2 lazy val poolSizeMax = 256 lazy val poolSizeFactor = 2.0 lazy val nProcessors = Runtime.getRuntime.availableProcessors() lazy val poolSize = { val sz = (Runtime.getRuntime.availableProcessors() * poolSizeFactor).toInt max poolSizeMin min poolSizeMax logger.info(s"[$label] fixed thread pool for foreach " + s"min:${poolSizeMin.toString.withColor(GREEN)}, " + s"max:${poolSizeMax.toString.withColor(RED)}, " + s"factor:${poolSizeFactor.toString.withColor(CYAN)}, " + s"real:${sz.toString.withColor(YELLOW)}") sz } lazy implicit val mongoForeachExecutionContext = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(poolSize)) }
yuikns/valhalla
src/main/scala/com/argcv/valhalla/client/MongoDBClient.scala
Scala
mit
22,893
[ 30522, 7427, 4012, 1012, 12098, 18195, 2615, 1012, 11748, 9892, 2050, 1012, 7396, 12324, 9262, 1012, 21183, 4014, 1012, 16483, 1012, 4654, 8586, 16161, 2869, 12324, 9262, 1012, 21183, 4014, 1012, 16483, 1012, 9593, 1012, 9593, 18447, 26320, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include "../../src/oauth/qabstractoauthreplyhandler.h"
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtnetworkauth/include/QtNetworkAuth/qabstractoauthreplyhandler.h
C
gpl-3.0
56
[ 30522, 1001, 2421, 1000, 1012, 1012, 1013, 1012, 1012, 1013, 5034, 2278, 1013, 1051, 4887, 2705, 1013, 1053, 7875, 20528, 6593, 10441, 14317, 2890, 22086, 11774, 3917, 1012, 1044, 1000, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env python #################################### # # --- TEXTPATGEN TEMPLATE --- # # Users can change the output by editing # this file directly. # #################################### import sys sys.stdout.write('####################################\n') sys.stdout.write('#\n') sys.stdout.write('# -- TEXTPATGEN GENERATED FILE --\n') sys.stdout.write('#\n') sys.stdout.write('# -- Created from a Python script.\n') sys.stdout.write('#\n') sys.stdout.write("####################################\n") num=0 for length in range(0, 16): for width in range(0, 15): sys.stdout.write('X-%04X ' % num) num=num+1 width=width+1 length=length+1 sys.stdout.write('X-%04X\n' % num) num=num+1 sys.stdout.write('# -- End of file.\n'); sys.stdout.flush()
kevinleake01/textpatgen
12-workspace-py/tpl-py-0001.py
Python
gpl-2.0
774
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 18750, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #pragma once #include <map> #include <queue> #include <string> #include <thread> #include "port/port.h" #include "rocksdb/status.h" namespace rocksdb { class Env; class Logger; class SstFileManagerImpl; // DeleteScheduler allows the DB to enforce a rate limit on file deletion, // Instead of deleteing files immediately, files are moved to trash_dir // and deleted in a background thread that apply sleep penlty between deletes // if they are happening in a rate faster than rate_bytes_per_sec, // // Rate limiting can be turned off by setting rate_bytes_per_sec = 0, In this // case DeleteScheduler will delete files immediately. class DeleteScheduler { public: DeleteScheduler(Env* env, const std::string& trash_dir, int64_t rate_bytes_per_sec, Logger* info_log, SstFileManagerImpl* sst_file_manager); ~DeleteScheduler(); // Return delete rate limit in bytes per second int64_t GetRateBytesPerSecond() { return rate_bytes_per_sec_; } // Move file to trash directory and schedule it's deletion Status DeleteFile(const std::string& fname); // Wait for all files being deleteing in the background to finish or for // destructor to be called. void WaitForEmptyTrash(); // Return a map containing errors that happened in BackgroundEmptyTrash // file_path => error status std::map<std::string, Status> GetBackgroundErrors(); private: Status MoveToTrash(const std::string& file_path, std::string* path_in_trash); Status DeleteTrashFile(const std::string& path_in_trash, uint64_t* deleted_bytes); void BackgroundEmptyTrash(); Env* env_; // Path to the trash directory std::string trash_dir_; // Maximum number of bytes that should be deleted per second int64_t rate_bytes_per_sec_; // Mutex to protect queue_, pending_files_, bg_errors_, closing_ port::Mutex mu_; // Queue of files in trash that need to be deleted std::queue<std::string> queue_; // Number of files in trash that are waiting to be deleted int32_t pending_files_; // Errors that happened in BackgroundEmptyTrash (file_path => error) std::map<std::string, Status> bg_errors_; // Set to true in ~DeleteScheduler() to force BackgroundEmptyTrash to stop bool closing_; // Condition variable signaled in these conditions // - pending_files_ value change from 0 => 1 // - pending_files_ value change from 1 => 0 // - closing_ value is set to true port::CondVar cv_; // Background thread running BackgroundEmptyTrash std::unique_ptr<std::thread> bg_thread_; // Mutex to protect threads from file name conflicts port::Mutex file_move_mu_; Logger* info_log_; SstFileManagerImpl* sst_file_manager_; static const uint64_t kMicrosInSecond = 1000 * 1000LL; }; } // namespace rocksdb
kostub/dgraph
vendor/github.com/cockroachdb/c-rocksdb/internal/util/delete_scheduler.h
C
apache-2.0
3,104
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2249, 1011, 2556, 1010, 9130, 1010, 4297, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2023, 3120, 3642, 2003, 7000, 2104, 1996, 18667, 2094, 1011, 2806, 6105, 2179, 1999, 1996, 1013, 1013, 6105, 53...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1'> <title>Tejas Bhandari</title> </head> <body> <h1>Hello, Code School!</h1> <ul> <li>ruby</li> <li>JavaScript</li> <li>SQL</li> </ul> </body> </html>
bhandarytejas/HelloCodeSchoolProject
index.html
HTML
mit
373
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1005, 4372, 1005, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1005, 21183, 2546, 1011, 1022, 1005, 1028, 1026, 18804, 8299, 1011, 1041, 15549, 2615, 1027, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package uk.gov.dvsa.motr.web.system.binder.factory; import uk.gov.dvsa.motr.web.config.Config; import uk.gov.dvsa.motr.web.encryption.AwsKmsDecryptor; import uk.gov.dvsa.motr.web.encryption.Decryptor; import javax.inject.Inject; import static com.amazonaws.regions.Region.getRegion; import static com.amazonaws.regions.Regions.fromName; import static uk.gov.dvsa.motr.web.system.SystemVariable.REGION; public class AwsKmsDecryptorFactory implements BaseFactory<Decryptor> { private final Config config; @Inject public AwsKmsDecryptorFactory(Config config) { this.config = config; } @Override public Decryptor provide() { return new AwsKmsDecryptor( getRegion( fromName( config.getValue(REGION) ) ) ); } }
dvsa/motr-webapp
webapp/src/main/java/uk/gov/dvsa/motr/web/system/binder/factory/AwsKmsDecryptorFactory.java
Java
mit
879
[ 30522, 7427, 2866, 1012, 18079, 1012, 1040, 15088, 2050, 1012, 9587, 16344, 1012, 4773, 1012, 2291, 1012, 14187, 2121, 1012, 4713, 1025, 12324, 2866, 1012, 18079, 1012, 1040, 15088, 2050, 1012, 9587, 16344, 1012, 4773, 1012, 9530, 8873, 229...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.samza.test.framework.system.descriptors; import org.apache.samza.system.descriptors.InputDescriptor; import org.apache.samza.serializers.NoOpSerde; /** * A descriptor for an in memory stream of messages that can either have single or multiple partitions. * <p> * An instance of this descriptor may be obtained from an appropriately configured {@link InMemorySystemDescriptor}. * * @param <StreamMessageType> type of messages in input stream */ public class InMemoryInputDescriptor<StreamMessageType> extends InputDescriptor<StreamMessageType, InMemoryInputDescriptor<StreamMessageType>> { /** * Constructs a new InMemoryInputDescriptor from specified components. * @param systemDescriptor name of the system stream is associated with * @param streamId name of the stream */ InMemoryInputDescriptor(String streamId, InMemorySystemDescriptor systemDescriptor) { super(streamId, new NoOpSerde<>(), systemDescriptor, null); } public InMemoryInputDescriptor withPhysicalName(String physicalName) { super.withPhysicalName(physicalName); return this; } }
bharathkk/samza
samza-test/src/main/java/org/apache/samza/test/framework/system/descriptors/InMemoryInputDescriptor.java
Java
apache-2.0
1,923
[ 30522, 1013, 1008, 1008, 7000, 2000, 1996, 15895, 4007, 3192, 1006, 2004, 2546, 1007, 2104, 2028, 1008, 2030, 2062, 12130, 6105, 10540, 1012, 2156, 1996, 5060, 5371, 1008, 5500, 2007, 2023, 2147, 2005, 3176, 2592, 1008, 4953, 9385, 6095, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.rest; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.ShardSearchFailure; import org.elasticsearch.common.ParsingException; import org.elasticsearch.index.Index; import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.rest.FakeRestRequest; import org.elasticsearch.transport.RemoteTransportException; import java.io.FileNotFoundException; import java.io.IOException; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; /** * */ public class BytesRestResponseTests extends ESTestCase { public void testWithHeaders() throws Exception { RestRequest request = new FakeRestRequest(); RestChannel channel = randomBoolean() ? new DetailedExceptionRestChannel(request) : new SimpleExceptionRestChannel(request); BytesRestResponse response = new BytesRestResponse(channel, new WithHeadersException()); assertThat(response.getHeaders().get("n1"), notNullValue()); assertThat(response.getHeaders().get("n1"), contains("v11", "v12")); assertThat(response.getHeaders().get("n2"), notNullValue()); assertThat(response.getHeaders().get("n2"), contains("v21", "v22")); } public void testSimpleExceptionMessage() throws Exception { RestRequest request = new FakeRestRequest(); RestChannel channel = new SimpleExceptionRestChannel(request); Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().toUtf8(); assertThat(text, containsString("ElasticsearchException[an error occurred reading data]")); assertThat(text, not(containsString("FileNotFoundException"))); assertThat(text, not(containsString("/foo/bar"))); assertThat(text, not(containsString("error_trace"))); } public void testDetailedExceptionMessage() throws Exception { RestRequest request = new FakeRestRequest(); RestChannel channel = new DetailedExceptionRestChannel(request); Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().toUtf8(); assertThat(text, containsString("{\"type\":\"exception\",\"reason\":\"an error occurred reading data\"}")); assertThat(text, containsString("{\"type\":\"file_not_found_exception\",\"reason\":\"/foo/bar\"}")); } public void testNonElasticsearchExceptionIsNotShownAsSimpleMessage() throws Exception { RestRequest request = new FakeRestRequest(); RestChannel channel = new SimpleExceptionRestChannel(request); Throwable t = new Throwable("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().toUtf8(); assertThat(text, not(containsString("Throwable[an error occurred reading data]"))); assertThat(text, not(containsString("FileNotFoundException[/foo/bar]"))); assertThat(text, not(containsString("error_trace"))); assertThat(text, containsString("\"error\":\"No ElasticsearchException found\"")); } public void testErrorTrace() throws Exception { RestRequest request = new FakeRestRequest(); request.params().put("error_trace", "true"); RestChannel channel = new DetailedExceptionRestChannel(request); Throwable t = new Throwable("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().toUtf8(); assertThat(text, containsString("\"type\":\"throwable\",\"reason\":\"an error occurred reading data\"")); assertThat(text, containsString("{\"type\":\"file_not_found_exception\"")); assertThat(text, containsString("\"stack_trace\":\"[an error occurred reading data]")); } public void testGuessRootCause() throws IOException { RestRequest request = new FakeRestRequest(); RestChannel channel = new DetailedExceptionRestChannel(request); { Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().toUtf8(); assertThat(text, containsString("{\"root_cause\":[{\"type\":\"exception\",\"reason\":\"an error occurred reading data\"}]")); } { Throwable t = new FileNotFoundException("/foo/bar"); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().toUtf8(); assertThat(text, containsString("{\"root_cause\":[{\"type\":\"file_not_found_exception\",\"reason\":\"/foo/bar\"}]")); } } public void testNullThrowable() throws Exception { RestRequest request = new FakeRestRequest(); RestChannel channel = new SimpleExceptionRestChannel(request); BytesRestResponse response = new BytesRestResponse(channel, null); String text = response.content().toUtf8(); assertThat(text, containsString("\"error\":\"unknown\"")); assertThat(text, not(containsString("error_trace"))); } public void testConvert() throws IOException { RestRequest request = new FakeRestRequest(); RestChannel channel = new DetailedExceptionRestChannel(request); ShardSearchFailure failure = new ShardSearchFailure(new ParsingException(1, 2, "foobar", null), new SearchShardTarget("node_1", new Index("foo", "_na_"), 1)); ShardSearchFailure failure1 = new ShardSearchFailure(new ParsingException(1, 2, "foobar", null), new SearchShardTarget("node_1", new Index("foo", "_na_"), 2)); SearchPhaseExecutionException ex = new SearchPhaseExecutionException("search", "all shards failed", new ShardSearchFailure[] {failure, failure1}); BytesRestResponse response = new BytesRestResponse(channel, new RemoteTransportException("foo", ex)); String text = response.content().toUtf8(); String expected = "{\"error\":{\"root_cause\":[{\"type\":\"parsing_exception\",\"reason\":\"foobar\",\"line\":1,\"col\":2}],\"type\":\"search_phase_execution_exception\",\"reason\":\"all shards failed\",\"phase\":\"search\",\"grouped\":true,\"failed_shards\":[{\"shard\":1,\"index\":\"foo\",\"node\":\"node_1\",\"reason\":{\"type\":\"parsing_exception\",\"reason\":\"foobar\",\"line\":1,\"col\":2}}]},\"status\":400}"; assertEquals(expected.trim(), text.trim()); String stackTrace = ExceptionsHelper.stackTrace(ex); assertTrue(stackTrace.contains("Caused by: ParsingException[foobar]")); } public static class WithHeadersException extends ElasticsearchException { WithHeadersException() { super(""); this.addHeader("n1", "v11", "v12"); this.addHeader("n2", "v21", "v22"); } } private static class SimpleExceptionRestChannel extends AbstractRestChannel { SimpleExceptionRestChannel(RestRequest request) { super(request, false); } @Override public void sendResponse(RestResponse response) { } } private static class DetailedExceptionRestChannel extends AbstractRestChannel { DetailedExceptionRestChannel(RestRequest request) { super(request, true); } @Override public void sendResponse(RestResponse response) { } } }
mmaracic/elasticsearch
core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java
Java
apache-2.0
8,953
[ 30522, 1013, 1008, 1008, 7000, 2000, 21274, 17310, 11140, 2104, 2028, 2030, 2062, 12130, 1008, 6105, 10540, 1012, 2156, 1996, 5060, 5371, 5500, 2007, 1008, 2023, 2147, 2005, 3176, 2592, 4953, 9385, 1008, 6095, 1012, 21274, 17310, 11140, 159...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.7-6-a-297 description: > Object.defineProperties - 'O' is an Arguments object, 'P' is an array index named data property of 'O' but not defined in [[ParameterMap]] of 'O', test TypeError is thrown when updating the [[Configurable]] attribute value of 'P' which is not configurable (10.6 [[DefineOwnProperty]] step 4) includes: [propertyHelper.js] ---*/ var arg; (function fun() { arg = arguments; }()); Object.defineProperty(arg, "0", { value: 0, writable: false, enumerable: false, configurable: false }); try { Object.defineProperties(arg, { "0": { configurable: true } }); $ERROR("Expected an exception."); } catch (e) { verifyEqualTo(arg, "0", 0); verifyNotWritable(arg, "0"); verifyNotEnumerable(arg, "0"); verifyNotConfigurable(arg, "0"); if (!(e instanceof TypeError)) { $ERROR("Expected TypeError, got " + e); } }
m0ppers/arangodb
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Object/defineProperties/15.2.3.7-6-a-297.js
JavaScript
apache-2.0
1,101
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2262, 14925, 2863, 2248, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2023, 3642, 2003, 9950, 2011, 1996, 18667, 2094, 6105, 2179, 1999, 1996, 6105, 5371, 1012, 1013, 1008, 1011, 1011, 1011, 9686, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
var getColor = function (value, p, record) { return "<span style='color:blue;'>" + value + "</span>"; } var getDayNumber = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:blue;'>" + value + "</b>"; } //Lấy số ngày phép được hưởng mỗi tháng var getUsedDayPerMonth = function (value, p, record) { if (value == "" || value == 0) { return ""; } return "<b style='float:right;color:red;'>" + value + "</b>"; } //Lấy số ngày phép được hưởng mỗi năm var getUsedDayPerYear = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:red;'>" + value + "</b>"; } //Lấy tổng số ngày phép được hưởng var getTotalDaysPerYear = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:blue;'>" + value + "</b>"; } var enterKeyPressHandler = function (f, e) { if (e.getKey() == e.ENTER) { PagingToolbar1.pageIndex = 0; PagingToolbar1.doLoad(); Store1.reload(); } } //Xóa các điều kiện lọc var clearFilter = function () { txtMaCB.reset(); txtHoTen.reset(); cbPhongBan.reset(); cbTo.reset(); txtTongSoNgayPhep.reset(); txtSoNgayDaSuDung.reset(); txtSoNgayConLai.reset(); txtCongDonNgayPhep.reset(); txtThamNien.reset(); PagingToolbar1.pageIndex = 0; PagingToolbar1.doLoad(); Store1.reload(); } var ValidateNgayPhep = function () { if (nbfSoNgayPhep.getValue() == '') { alert("Bạn chưa nhập số ngày nghỉ phép năm nay"); nbfSoNgayPhep.focus(); return false; } if (nbfSoNgayPhepCongDonToiDaTrong1Thang.getValue() == '') { alert("Bạn chưa nhập số ngày phép được cộng dồn trong 1 tháng"); nbfSoNgayPhepCongDonToiDaTrong1Thang.focus(); return false; } if (nbfSoNgayPhepThuongThem.getValue() != '' && dfHanDungNgayPhepThuongThem.getValue() == '') { alert("Bạn chưa nhập hạn sử dụng ngày phép được thưởng thêm"); return false; } if (chkNgayNghiPhepNamTruoc.checked == true && dfHanDungNgayPhepNamTruoc.getValue() == '') { alert("Bạn chưa nhập hạn dùng ngày nghỉ phép của năm trước"); return false; } if (rdChiNhungNhanVienDuocChon.checked == false && rdApDungChoTatCaNhanVien.checked == false) { alert("Bạn chưa chọn đối tượng được tính ngày phép"); return false; } return true; } var RenderSoNgayPhepDaSuDung = function (value, p, record) { if (value == "0" || value == null) { return ""; } return value; } var ResetForm = function () { dfHanSuDungNPNamTruoc.reset(); nbfSoNgayPhep.reset(); nbfSoNgayPhepThuongThem.reset(); chkNgayNghiPhepNamTruoc.reset(); dfHanDungNgayPhepNamTruoc.reset(); dfHanDungNgayPhepThuongThem.reset(); nbfSoNgayPhepCongDonToiDaTrong1Thang.reset(); rdApDungChoTatCaNhanVien.enable(); rdChiNhungNhanVienDuocChon.setValue(false); rdApDungChoTatCaNhanVien.setValue(false); } var RenderThamNien = function (value, p, record) { var totalDay = value * 1; if (totalDay == 0) { return ""; } var month = Math.floor(totalDay / 30); var remainDay = totalDay % 30; var year = 0; var remainMonth = 0; var rs = ""; if (month >= 12) { year = Math.floor(month / 12); remainMonth = month % 12; } if (year > 0) { rs = year + " năm "; if (remainMonth > 0) { rs += remainMonth + " tháng"; } } else { rs = month + " tháng "; if (remainDay > 0) { rs += remainDay + " ngày"; } } return rs; }
blackapple2017/qAustfeed
Austfeed/Modules/ChamCongDoanhNghiep/Resource/JsQuanLyNgayPhep.js
JavaScript
apache-2.0
4,131
[ 30522, 13075, 2131, 18717, 1027, 3853, 1006, 3643, 1010, 1052, 1010, 2501, 1007, 1063, 2709, 1000, 1026, 8487, 2806, 1027, 1005, 3609, 1024, 2630, 1025, 1005, 1028, 1000, 1009, 3643, 1009, 1000, 1026, 1013, 8487, 1028, 1000, 1025, 1065, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<md-card md-theme="content-widget"> <md-card-header> <md-card-avatar> <md-icon>{{widget.config.icon}}</md-icon> </md-card-avatar> <md-card-header-text> <span class="md-title">{{widget.config.name[languages[0].slug]}}</span> <span class="md-subhead">{{widget.config.description[languages[0].slug]}}</span> </md-card-header-text> <md-button ng-click="delete($event)" class="md-icon-button" aria-label="Eliminar"> <md-tooltip md-direction="bottom">Eliminar</md-tooltip> <md-icon>delete</md-icon> </md-button> </md-card-header> <md-card-content> <md-input-container> <label>Tipo</label> <md-select class="md-hue-1" ng-model="widget.data.content_type"> <md-option><em>None</em></md-option> <md-option ng-repeat="(key, type) in widget.types" ng-selected="{{widget.data.content_type == key}}" ng-value="key"> {{type.menu.name[languages[0].slug]}} </md-option> </md-select> </md-input-container> </md-card-content> <md-card-footer layout="row"> <md-button ng-show="changed" flex ng-click="save()" class="md-raised md-primary">Guardar</md-button> </md-card-footer> </md-card>
kaoz70/flexcms
flexcms/widgets/content/views/Admin.php
PHP
gpl-3.0
1,385
[ 30522, 1026, 9108, 1011, 4003, 9108, 1011, 4323, 1027, 1000, 4180, 1011, 15536, 24291, 1000, 1028, 1026, 9108, 1011, 4003, 1011, 20346, 1028, 1026, 9108, 1011, 4003, 1011, 22128, 1028, 1026, 9108, 1011, 12696, 1028, 1063, 1063, 15536, 24291...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * The basic test codes to check the AnglogIn. */ #include "mbed.h" static AnalogIn ain_x(A6); // connect joistics' x axis to A6 pin of mbed static AnalogIn ain_y(A5); // connect joistics' y axis to A5 pin of mbed static void printAnalogInput(AnalogIn *xin, AnalogIn *yin) { uint8_t point[2] = { 0 }; point[0] = (uint8_t)(xin->read()*100.0f + 0.5); point[1] = (uint8_t)(yin->read()*100.0f + 0.5); printf("x: %d, y: %d\n", point[0], point[1]); } int main() { while(1) { printAnalogInput(&ain_x, &ain_y); wait(0.2f); } }
Darkblue38/mbedTrust
MiniProjects/AnalogInOut/Joistick/TestAnalogInUsingJoistick.cpp
C++
gpl-3.0
563
[ 30522, 1013, 1008, 1008, 1996, 3937, 3231, 9537, 2000, 4638, 1996, 7819, 11528, 1012, 1008, 1013, 1001, 2421, 1000, 20301, 2094, 1012, 1044, 1000, 10763, 11698, 2378, 7110, 1035, 1060, 1006, 1037, 2575, 1007, 1025, 1013, 1013, 7532, 8183, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import psutil from ajenti.api import * from ajenti.ui import * @plugin class NetworkManager (BasePlugin): def get_devices(self): return psutil.net_io_counters(pernic=True).keys() @interface class INetworkConfig (object): interfaces = {} @property def interface_list(self): return self.interfaces.values() def rescan(self): pass def save(self): pass @interface class INetworkConfigBit (object): def apply(self): pass @plugin class NetworkConfigBit (UIElement, INetworkConfigBit): cls = 'unknown' iface = None title = 'Unknown' typeid = 'box' class NetworkInterface(object): def __init__(self): self.up = False self.auto = False self.name = '' self.devclass = '' self.addressing = 'static' self.bits = [] self.params = {'address': '0.0.0.0'} self.type = '' self.editable = True def __getitem__(self, idx): if idx in self.params: return self.params[idx] else: return '' def __setitem__(self, idx, val): self.params[idx] = val def add_bits(self, ui): for cls in INetworkConfigBit.get_classes(): if cls.cls in self.bit_classes: b = cls.new(ui) b.iface = self b.refresh() self.bits.append(b)
lupyuen/RaspberryPiImage
usr/share/pyshared/ajenti/plugins/network/api.py
Python
apache-2.0
1,407
[ 30522, 12324, 8827, 21823, 2140, 2013, 19128, 4765, 2072, 1012, 17928, 12324, 1008, 2013, 19128, 4765, 2072, 1012, 21318, 12324, 1008, 1030, 13354, 2378, 2465, 2897, 24805, 4590, 1006, 2918, 24759, 15916, 2378, 1007, 1024, 13366, 2131, 1035, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env python2 # coding=utf-8 # # Copyright 2014 Sascha Schirra # # This file is part of Ropper. # # Ropper 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. # # Ropper 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/>.
idl3r/Ropper
ropperapp/loaders/pe_intern/__init__.py
Python
gpl-2.0
729
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 18750, 2475, 1001, 16861, 1027, 21183, 2546, 1011, 1022, 1001, 1001, 9385, 2297, 21871, 7507, 8040, 11961, 2527, 1001, 1001, 2023, 5371, 2003, 2112, 1997, 20996, 18620, 1012,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** ****************************************************************************** * @file TIM/TIM_7PWMOutput/Src/stm32f4xx_it.c * @author MCD Application Team * @version V1.2.5 * @date 29-January-2016 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of STMicroelectronics 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 HOLDER 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f4xx_it.h" /** @addtogroup STM32F4xx_HAL_Examples * @{ */ /** @addtogroup TIM_7PWMOutput * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M4 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { HAL_IncTick(); } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f4xx.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * @param None * @retval None */ /*void PPP_IRQHandler(void) { }*/ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
mariobarbareschi/stm32-compiler-docker
STM32Cube_FW_F4_V1.11.0/Projects/STM324xG_EVAL/Examples/TIM/TIM_7PWMOutput/Src/stm32f4xx_it.c
C
agpl-3.0
5,585
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/******************************************************************************* * Copyright (C) 2006-2013 AITIA International, Inc. * * 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 ai.aitia.meme.paramsweep.gui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import ai.aitia.meme.gui.Preferences; import ai.aitia.meme.gui.PreferencesPage; import ai.aitia.meme.gui.Preferences.Button; import ai.aitia.meme.paramsweep.gui.WizardPreferences.IReinitalizeable; import ai.aitia.meme.paramsweep.platform.PlatformManager; import ai.aitia.meme.paramsweep.platform.PlatformManager.PlatformType; import ai.aitia.meme.paramsweep.utils.Utilities; import ai.aitia.meme.utils.FormsUtils; import ai.aitia.meme.utils.GUIUtils; import ai.aitia.meme.utils.FormsUtils.Separator; public class Page_EMILPrefs extends PreferencesPage implements IReinitalizeable, ActionListener { //===================================================================================== //members private static final long serialVersionUID = 1L; /** The owner component of the page. */ private WizardPreferences owner = null; //===================================================================================== // GUI members private JPanel content = null; private JButton registerButton = new JButton("Register"); private JButton deRegisterButton = new JButton("Deregister"); //===================================================================================== // methods //------------------------------------------------------------------------------------- /** Constructor. * @param owner the owner component of the page */ public Page_EMILPrefs(WizardPreferences owner) { super("EMIL-S Repast"); this.owner = owner; layoutGUI(); reinitialize(); } //===================================================================================== // implemented interfaces //------------------------------------------------------------------------------------- @Override public String getInfoText(Preferences p) { return "EMIL-S Repast properties."; } @Override public boolean onButtonPress(Button b) { return true; } //------------------------------------------------------------------------------------- public void reinitialize() {} //---------------------------------------------------------------------------------------------------- public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if ("REGISTER".equals(cmd)) { PlatformManager.registerPlatform(PlatformType.EMIL,"."); owner.warning(true,"Registration successful!",Preferences.MESSAGE,true); } else if ("DEREGISTER".equals(cmd)) { int result = Utilities.askUser(owner,false,"Confirmation","Are you sure?"); if (result == 1) { PlatformManager.removePlatform(PlatformType.EMIL); owner.warning(true,"Deregistration successful!",Preferences.MESSAGE,true); } } } //===================================================================================== // GUI methods //------------------------------------------------------------------------------------- private void layoutGUI() { JPanel tmp = FormsUtils.build("p ~ p ~ p:g", "01_", registerButton,deRegisterButton).getPanel(); content = FormsUtils.build("p ~ p:g ~ p ", "[DialogBorder]000||" + "111||" + "222|" + "___", "A platform for Trass models", tmp, new Separator("")).getPanel(); this.setLayout(new BorderLayout()); this.add(content,BorderLayout.CENTER); registerButton.setActionCommand("REGISTER"); deRegisterButton.setActionCommand("DEREGISTER"); GUIUtils.addActionListener(this,registerButton,deRegisterButton); } }
lgulyas/MEME
src/ai/aitia/meme/paramsweep/gui/Page_EMILPrefs.java
Java
gpl-3.0
4,536
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Copyright (C) 2016 - 2030 youtongluan. * * 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 org.yx.asm; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.yx.bean.Loader; import org.yx.conf.AppInfo; import org.yx.exception.SumkException; import org.yx.log.Log; import org.yx.log.Logs; import org.yx.main.StartContext; public final class AsmUtils { private static Method defineClass; static { try { defineClass = getMethod(ClassLoader.class, "defineClass", new Class<?>[] { String.class, byte[].class, int.class, int.class }); defineClass.setAccessible(true); } catch (Exception e) { Log.printStack("sumk.error", e); StartContext.startFailed(); } } public static String proxyCalssName(Class<?> clz) { String name = clz.getName(); int index = name.lastIndexOf('.'); return name.substring(0, index) + ".sumkbox" + name.substring(index); } public static int asmVersion() { return AppInfo.getInt("sumk.asm.version", Opcodes.ASM7); } public static int jvmVersion() { return AppInfo.getInt("sumk.asm.jvm.version", Opcodes.V1_8); } public static InputStream openStreamForClass(String name) { String internalName = name.replace('.', '/') + ".class"; return Loader.getResourceAsStream(internalName); } public static boolean sameType(Type[] types, Class<?>[] clazzes) { if (types.length != clazzes.length) { return false; } for (int i = 0; i < types.length; i++) { if (!Type.getType(clazzes[i]).equals(types[i])) { return false; } } return true; } public static List<MethodParamInfo> buildMethodInfos(List<Method> methods) throws IOException { Map<Class<?>, List<Method>> map = new HashMap<>(); for (Method m : methods) { List<Method> list = map.get(m.getDeclaringClass()); if (list == null) { list = new ArrayList<>(); map.put(m.getDeclaringClass(), list); } list.add(m); } List<MethodParamInfo> ret = new ArrayList<>(); for (List<Method> ms : map.values()) { ret.addAll(buildMethodInfos(ms.get(0).getDeclaringClass(), ms)); } return ret; } private static List<MethodParamInfo> buildMethodInfos(Class<?> declaringClass, List<Method> methods) throws IOException { String classFullName = declaringClass.getName(); ClassReader cr = new ClassReader(openStreamForClass(classFullName)); MethodInfoClassVisitor cv = new MethodInfoClassVisitor(methods); cr.accept(cv, 0); return cv.getMethodInfos(); } public static Method getMethod(Class<?> clz, String methodName, Class<?>[] paramTypes) { while (clz != Object.class) { Method[] ms = clz.getDeclaredMethods(); for (Method m : ms) { if (!m.getName().equals(methodName)) { continue; } Class<?>[] paramTypes2 = m.getParameterTypes(); if (!Arrays.equals(paramTypes2, paramTypes)) { continue; } return m; } clz = clz.getSuperclass(); } return null; } public static Class<?> loadClass(String fullName, byte[] b) throws Exception { String clzOutPath = AppInfo.get("sumk.asm.debug.output"); if (clzOutPath != null && clzOutPath.length() > 0) { try { File f = new File(clzOutPath, fullName + ".class"); try (FileOutputStream fos = new FileOutputStream(f)) { fos.write(b); fos.flush(); } } catch (Exception e) { if (Logs.asm().isTraceEnabled()) { Logs.asm().error(e.getLocalizedMessage(), e); } } } synchronized (AsmUtils.class) { try { return Loader.loadClass(fullName); } catch (Throwable e) { if (!(e instanceof ClassNotFoundException)) { Logs.asm().warn(fullName + " 加载失败", e); } } Class<?> clz = (Class<?>) defineClass.invoke(Loader.loader(), fullName, b, 0, b.length); if (clz == null) { throw new SumkException(-235345436, "cannot load class " + fullName); } return clz; } } public static final int BADMODIFIERS = Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.PRIVATE; public static boolean notPublicOnly(int modifiers) { return (modifiers & (Modifier.PUBLIC | BADMODIFIERS)) != Modifier.PUBLIC; } public static boolean canProxy(int modifiers) { return (modifiers & BADMODIFIERS) == 0; } public static List<Object> getImplicitFrame(String desc) { List<Object> locals = new ArrayList<>(5); if (desc.isEmpty()) { return locals; } int i = 0; while (desc.length() > i) { int j = i; switch (desc.charAt(i++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': locals.add(Opcodes.INTEGER); break; case 'F': locals.add(Opcodes.FLOAT); break; case 'J': locals.add(Opcodes.LONG); break; case 'D': locals.add(Opcodes.DOUBLE); break; case '[': while (desc.charAt(i) == '[') { ++i; } if (desc.charAt(i) == 'L') { ++i; while (desc.charAt(i) != ';') { ++i; } } locals.add(desc.substring(j, ++i)); break; case 'L': while (desc.charAt(i) != ';') { ++i; } locals.add(desc.substring(j + 1, i++)); break; default: break; } } return locals; } public static Method getSameMethod(Method method, Class<?> otherClass) { Class<?> clz = method.getDeclaringClass(); if (clz == otherClass) { return method; } String methodName = method.getName(); Class<?>[] argTypes = method.getParameterTypes(); Method[] proxyedMethods = otherClass.getMethods(); for (Method proxyedMethod : proxyedMethods) { if (proxyedMethod.getName().equals(methodName) && Arrays.equals(argTypes, proxyedMethod.getParameterTypes()) && !proxyedMethod.getDeclaringClass().isInterface()) { return proxyedMethod; } } return method; } }
youtongluan/sumk
src/main/java/org/yx/asm/AsmUtils.java
Java
apache-2.0
6,539
[ 30522, 1013, 1008, 1008, 1008, 9385, 1006, 1039, 1007, 2355, 1011, 18540, 2692, 2017, 2669, 23296, 13860, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
require File.expand_path('../spec_helper', __FILE__) module Pod class Sample extend SpecHelper::Fixture def self.yaml <<-LOCKFILE.strip_heredoc PODS: - BananaLib (1.0): - monkey (< 1.0.9, ~> 1.0.1) - JSONKit (1.4) - monkey (1.0.8) DEPENDENCIES: - BananaLib (~> 1.0) - JSONKit (from `path/JSONKit.podspec`) EXTERNAL SOURCES: JSONKit: :podspec: path/JSONKit.podspec CHECKOUT OPTIONS: JSONKit: :podspec: path/JSONKit.podspec SPEC CHECKSUMS: BananaLib: d46ca864666e216300a0653de197668b12e732a1 JSONKit: 92ae5f71b77c8dec0cd8d0744adab79d38560949 PODFILE CHECKSUM: podfile_checksum COCOAPODS: #{CORE_VERSION} LOCKFILE end def self.quotation_marks_yaml <<-LOCKFILE.strip_heredoc PODS: - BananaLib (1.0): - monkey (< 1.0.9, ~> 1.0.1) - JSONKit (1.4) - monkey (1.0.8) DEPENDENCIES: - BananaLib (~> 1.0) - JSONKit (from `path/JSONKit.podspec`) EXTERNAL SOURCES: JSONKit: :podspec: "path/JSONKit.podspec" CHECKOUT OPTIONS: JSONKit: :podspec: path/JSONKit.podspec SPEC CHECKSUMS: BananaLib: d46ca864666e216300a0653de197668b12e732a1 JSONKit: '92ae5f71b77c8dec0cd8d0744adab79d38560949' PODFILE CHECKSUM: podfile_checksum COCOAPODS: #{CORE_VERSION} LOCKFILE end def self.podfile podfile = Podfile.new do platform :ios pod 'BananaLib', '~>1.0' pod 'JSONKit', :podspec => 'path/JSONKit.podspec' end podfile.stubs(:checksum).returns('podfile_checksum') podfile end def self.specs repo_path = 'spec-repos/test_repo/' bananalib_path = repo_path + 'Specs/BananaLib/1.0/BananaLib.podspec' jsonkit_path = repo_path + 'Specs/JSONKit/1.4/JSONKit.podspec' specs = [ Specification.from_file(fixture(bananalib_path)), Specification.from_file(fixture(jsonkit_path)), Specification.new do |s| s.name = 'monkey' s.version = '1.0.8' end, ] specs end def self.checkout_options { 'JSONKit' => { :podspec => 'path/JSONKit.podspec', }, } end end #---------------------------------------------------------------------------# describe Lockfile do describe 'In general' do extend SpecHelper::TemporaryDirectory before do @tmp_path = temporary_directory + 'Podfile.lock' end it 'stores the initialization hash' do lockfile = Lockfile.new(YAMLHelper.load_string(Sample.yaml)) lockfile.internal_data.should == YAMLHelper.load_string(Sample.yaml) end it 'loads from a file' do File.open(@tmp_path, 'w') { |f| f.write(Sample.yaml) } lockfile = Lockfile.from_file(@tmp_path) lockfile.internal_data.should == YAMLHelper.load_string(Sample.yaml) end it "returns nil if it can't find the initialization file" do lockfile = Lockfile.from_file(temporary_directory + 'Podfile.lock_not_existing') lockfile.should.nil? end it 'returns the file in which is defined' do File.open(@tmp_path, 'w') { |f| f.write(Sample.yaml) } lockfile = Lockfile.from_file(@tmp_path) lockfile.defined_in_file.should == @tmp_path end it "raises if the provided YAML doesn't returns a hash" do File.open(@tmp_path, 'w') { |f| f.write('value') } should.raise Informative do Lockfile.from_file(@tmp_path) end.message.should.match /Invalid Lockfile/ end #--------------------------------------# before do @lockfile = Lockfile.generate(Sample.podfile, Sample.specs, Sample.checkout_options) end it 'returns whether it is equal to another' do podfile = Podfile.new do platform :ios pod 'BananaLib', '~>1.0' end @lockfile.should == @lockfile @lockfile.should.not == Lockfile.generate(podfile, Sample.specs, Sample.checkout_options) end it 'returns the list of the names of the installed pods' do @lockfile.pod_names.should == %w(BananaLib JSONKit monkey) end it 'returns the versions of a given pod' do @lockfile.version('BananaLib').should == Version.new('1.0') @lockfile.version('JSONKit').should == Version.new('1.4') @lockfile.version('monkey').should == Version.new('1.0.8') end it 'returns the versions of a given pod handling the case in which the root spec was not stored' do @lockfile.stubs(:pod_versions).returns('BananaLib/Subspec' => Version.new(1.0)) @lockfile.version('BananaLib').should == Version.new('1.0') end it 'returns the checksum for the given Pod' do @lockfile.checksum('BananaLib').should == 'd46ca864666e216300a0653de197668b12e732a1' end it 'returns the dependencies used for the last installation' do json_dep = Dependency.new('JSONKit') json_dep.external_source = { :podspec => 'path/JSONKit.podspec' } @lockfile.dependencies.should == [ Dependency.new('BananaLib', '~>1.0'), json_dep, ] end it 'includes the external source information in the generated dependencies' do dep = @lockfile.dependencies.find { |d| d.name == 'JSONKit' } dep.external_source.should == { :podspec => 'path/JSONKit.podspec' } end it 'returns the dependency that locks the pod with the given name to the installed version' do json_dep = Dependency.new('JSONKit', '1.4') json_dep.external_source = { :podspec => 'path/JSONKit.podspec' } result = @lockfile.dependencies_to_lock_pod_named('JSONKit') result.should == [json_dep] end it 'raises if there is a request for a locking dependency for a not stored Pod' do should.raise StandardError do @lockfile.dependencies_to_lock_pod_named('Missing') end.message.should.match /without a known dependency/ end it 'returns the version of CocoaPods which generated the lockfile' do @lockfile.cocoapods_version.should == Version.new(CORE_VERSION) end end #-------------------------------------------------------------------------# describe 'Comparison with a Podfile' do before do @podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit' end @specs = [ Specification.new do |s| s.name = 'BlocksKit' s.version = '1.0.0' end, Specification.new do |s| s.name = 'JSONKit' s.version = '1.4' end] @checkout_options = {} @lockfile = Lockfile.generate(@podfile, @specs, @checkout_options) end it 'detects an added Pod' do podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit' pod 'TTTAttributedLabel' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => [], :removed => [], :unchanged => %w(BlocksKit JSONKit), :added => ['TTTAttributedLabel'], } end it 'detects a removed Pod' do podfile = Podfile.new do platform :ios pod 'BlocksKit' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => [], :removed => ['JSONKit'], :unchanged => ['BlocksKit'], :added => [], } end it 'detects Pods whose version changed' do podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit', '> 1.4' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => ['JSONKit'], :removed => [], :unchanged => ['BlocksKit'], :added => [], } end it "it doesn't mark as changed Pods whose version changed but is still compatible with the Podfile" do podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit', '> 1.0' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => [], :removed => [], :unchanged => %w(BlocksKit JSONKit), :added => [], } end it 'detects Pods whose external source changed' do podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit', :git => 'example1.com' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => ['JSONKit'], :removed => [], :unchanged => ['BlocksKit'], :added => [], } @lockfile = Lockfile.generate(podfile, @specs, @checkout_options) podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit', :git => 'example2.com' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => ['JSONKit'], :removed => [], :unchanged => ['BlocksKit'], :added => [], } end end #-------------------------------------------------------------------------# describe 'Serialization' do before do @lockfile = Lockfile.generate(Sample.podfile, Sample.specs, Sample.checkout_options) end it 'can be store itself at the given path' do path = SpecHelper.temporary_directory + 'Podfile.lock' @lockfile.write_to_disk(path) loaded = Lockfile.from_file(path) loaded.should == @lockfile end it "won't write to disk if the equivalent lockfile is already there" do path = SpecHelper.temporary_directory + 'Podfile.lock' old_yaml = %(---\nhi: "./hi"\n) path.open('w') { |f| f.write old_yaml } @lockfile.stubs(:to_hash).returns('hi' => './hi') @lockfile.stubs(:to_yaml).returns("---\nhi: ./hi\n") path.expects(:open).with('w').never @lockfile.write_to_disk(path) path.read.should == old_yaml end it 'overwrites a different lockfile' do path = SpecHelper.temporary_directory + 'Podfile.lock' path.delete if path.exist? @lockfile.write_to_disk(path) @lockfile = Lockfile.new('COCOAPODS' => '0.0.0') @lockfile.write_to_disk(path) @lockfile.should == Lockfile.from_file(path) end it 'fix strange quotation marks in lockfile' do yaml_string = Sample.quotation_marks_yaml yaml_string = yaml_string.tr("'", '') yaml_string = yaml_string.tr('"', '') yaml_string.should == Sample.yaml end it 'generates a hash representation' do hash = @lockfile.to_hash hash.should == { 'PODS' => [ { 'BananaLib (1.0)' => ['monkey (< 1.0.9, ~> 1.0.1)'] }, 'JSONKit (1.4)', 'monkey (1.0.8)'], 'DEPENDENCIES' => ['BananaLib (~> 1.0)', 'JSONKit (from `path/JSONKit.podspec`)'], 'EXTERNAL SOURCES' => { 'JSONKit' => { :podspec => 'path/JSONKit.podspec' } }, 'CHECKOUT OPTIONS' => { 'JSONKit' => { :podspec => 'path/JSONKit.podspec' } }, 'SPEC CHECKSUMS' => { 'BananaLib' => 'd46ca864666e216300a0653de197668b12e732a1', 'JSONKit' => '92ae5f71b77c8dec0cd8d0744adab79d38560949' }, 'PODFILE CHECKSUM' => 'podfile_checksum', 'COCOAPODS' => CORE_VERSION, } end it 'handles when the podfile has no checksum' do podfile = Sample.podfile podfile.stubs(:checksum).returns(nil) @lockfile = Lockfile.generate(podfile, Sample.specs, Sample.checkout_options) @lockfile.to_hash.should.not.key?('PODFILE CHECKSUM') end it 'generates an ordered YAML representation' do @lockfile.to_yaml.should == Sample.yaml end it 'generates a valid YAML representation' do YAMLHelper.load_string(@lockfile.to_yaml).should == YAMLHelper.load_string(Sample.yaml) end it 'serializes correctly external dependencies' do podfile = Podfile.new do platform :ios pod 'BananaLib', :git => 'www.example.com', :tag => '1.0' end specs = [ Specification.new do |s| s.name = 'BananaLib' s.version = '1.0' end, Specification.new do |s| s.name = 'monkey' s.version = '1.0.8' end, ] checkout_options = { 'BananaLib' => { :git => 'www.example.com', :tag => '1.0' }, } lockfile = Lockfile.generate(podfile, specs, checkout_options) lockfile.internal_data['DEPENDENCIES'][0].should == 'BananaLib (from `www.example.com`, tag `1.0`)' lockfile.internal_data['EXTERNAL SOURCES']['BananaLib'].should == { :git => 'www.example.com', :tag => '1.0' } end end #-------------------------------------------------------------------------# describe 'Generation from a Podfile' do before do @lockfile = Lockfile.generate(Sample.podfile, Sample.specs, Sample.checkout_options) end it 'stores the information of the installed pods and of their dependencies' do @lockfile.internal_data['PODS'].should == [ { 'BananaLib (1.0)' => ['monkey (< 1.0.9, ~> 1.0.1)'] }, 'JSONKit (1.4)', 'monkey (1.0.8)', ] end it 'stores the information of the dependencies of the Podfile' do @lockfile.internal_data['DEPENDENCIES'].should == [ 'BananaLib (~> 1.0)', 'JSONKit (from `path/JSONKit.podspec`)' ] end it 'stores the information of the external sources' do @lockfile.internal_data['EXTERNAL SOURCES'].should == { 'JSONKit' => { :podspec => 'path/JSONKit.podspec' }, } end it 'stores the checksum of the specifications' do @lockfile.internal_data['SPEC CHECKSUMS'].should == { 'BananaLib' => 'd46ca864666e216300a0653de197668b12e732a1', 'JSONKit' => '92ae5f71b77c8dec0cd8d0744adab79d38560949', } end it 'store the version of the CocoaPods Core gem' do @lockfile.internal_data['COCOAPODS'].should == CORE_VERSION end it 'it includes all the information that it is expected to store' do @lockfile.internal_data.should == YAMLHelper.load_string(Sample.yaml) end end #-------------------------------------------------------------------------# describe 'Private helpers' do describe '#generate_pods_data' do it 'groups multiple dependencies for the same pod' do specs = [ Specification.new do |s| s.name = 'BananaLib' s.version = '1.0' s.dependency 'monkey', '< 1.0.9' end, Specification.new do |s| s.name = 'BananaLib' s.version = '1.0' s.dependency 'tree', '~> 1.0.1' end, ] pods_data = Lockfile.send(:generate_pods_data, specs) pods_data.should == [{ 'BananaLib (1.0)' => ['monkey (< 1.0.9)', 'tree (~> 1.0.1)'], }] end end end end end
dacaiguoguogmail/Core
spec/lockfile_spec.rb
Ruby
mit
15,656
[ 30522, 5478, 5371, 1012, 7818, 1035, 4130, 1006, 1005, 1012, 1012, 1013, 28699, 1035, 2393, 2121, 1005, 1010, 1035, 1035, 5371, 1035, 1035, 1007, 11336, 17491, 2465, 7099, 7949, 28699, 16001, 4842, 1024, 1024, 15083, 13366, 2969, 1012, 8038...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
module Airbrake # NoticeNotifier is reponsible for sending notices to Airbrake. It supports # synchronous and asynchronous delivery. # # @see Airbrake::Config The list of options # @since v1.0.0 # @api public class NoticeNotifier # @return [Array<Class>] filters to be executed first DEFAULT_FILTERS = [ Airbrake::Filters::SystemExitFilter, Airbrake::Filters::GemRootFilter, # Optional filters (must be included by users): # Airbrake::Filters::ThreadFilter ].freeze include Inspectable include Loggable def initialize @config = Airbrake::Config.instance @filter_chain = FilterChain.new @async_sender = AsyncSender.new(:post, self.class.name) @sync_sender = SyncSender.new DEFAULT_FILTERS.each { |filter| add_filter(filter.new) } add_filter(Airbrake::Filters::ContextFilter.new) add_filter(Airbrake::Filters::ExceptionAttributesFilter.new) end # @see Airbrake.notify def notify(exception, params = {}, &block) send_notice(exception, params, default_sender, &block) end # @see Airbrake.notify_sync def notify_sync(exception, params = {}, &block) send_notice(exception, params, @sync_sender, &block).value end # @see Airbrake.add_filte def add_filter(filter = nil, &block) @filter_chain.add_filter(block_given? ? block : filter) end # @see Airbrake.delete_filter def delete_filter(filter_class) @filter_chain.delete_filter(filter_class) end # @see Airbrake.build_notice def build_notice(exception, params = {}) if @async_sender.closed? raise Airbrake::Error, "Airbrake is closed; can't build exception: " \ "#{exception.class}: #{exception}" end if exception.is_a?(Airbrake::Notice) exception[:params].merge!(params) exception else Notice.new(convert_to_exception(exception), params.dup) end end # @see Airbrake.close def close @async_sender.close end # @see Airbrake.configured? def configured? @config.valid? end # @see Airbrake.merge_context def merge_context(context) Airbrake::Context.current.merge!(context) end # @return [Boolean] # @since v4.14.0 def has_filter?(filter_class) # rubocop:disable Naming/PredicateName @filter_chain.includes?(filter_class) end private def convert_to_exception(ex) if ex.is_a?(Exception) || Backtrace.java_exception?(ex) # Manually created exceptions don't have backtraces, so we create a fake # one, whose first frame points to the place where Airbrake was called # (normally via `notify`). ex.set_backtrace(clean_backtrace) unless ex.backtrace return ex end e = RuntimeError.new(ex.to_s) e.set_backtrace(clean_backtrace) e end def send_notice(exception, params, sender) promise = @config.check_configuration return promise if promise.rejected? notice = build_notice(exception, params) yield notice if block_given? @filter_chain.refine(notice) promise = Airbrake::Promise.new return promise.reject("#{notice} was marked as ignored") if notice.ignored? sender.send(notice, promise) end def default_sender return @async_sender if @async_sender.has_workers? logger.warn( "#{LOG_LABEL} falling back to sync delivery because there are no " \ "running async workers", ) @sync_sender end def clean_backtrace caller_copy = Kernel.caller clean_bt = caller_copy.drop_while { |frame| frame.include?('/lib/airbrake') } # If true, then it's likely an internal library error. In this case return # at least some backtrace to simplify debugging. return caller_copy if clean_bt.empty? clean_bt end end end
airbrake/airbrake-ruby
lib/airbrake-ruby/notice_notifier.rb
Ruby
mit
3,943
[ 30522, 11336, 2250, 10024, 3489, 1001, 5060, 17048, 18095, 2003, 16360, 5644, 7028, 2005, 6016, 14444, 2000, 2250, 10024, 3489, 1012, 2009, 6753, 1001, 26351, 8093, 17175, 2271, 1998, 2004, 6038, 2818, 4948, 3560, 6959, 1012, 1001, 1001, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace NiclasHedam; class ColorName { public static $colors = [ 'Acid Green' => [176, 191, 26], 'Aero' => [124, 185, 232], 'Aero Blue' => [201, 255, 229], 'African Violet' => [178, 132, 190], 'Air Force Blue (RAF)' => [93, 138, 168], 'Air Force Blue (USAF)' => [0, 48, 143], 'Air Superiority Blue' => [114, 160, 193], 'Alabama Crimson' => [175, 0, 42], 'Alice Blue' => [240, 248, 255], 'Alizarin Crimson' => [227, 38, 54], 'Alloy Orange' => [196, 98, 16], 'Almond' => [239, 222, 205], 'Amaranth' => [229, 43, 80], 'Amaranth Deep Purple' => [171, 39, 79], 'Amaranth Pink' => [241, 156, 187], 'Amaranth Purple' => [171, 39, 79], 'Amaranth Red' => [211, 33, 45], 'Amazon' => [59, 122, 87], 'Amber' => [255, 191, 0], 'Amber (SAE/ECE)' => [255, 126, 0], 'American Rose' => [255, 3, 62], 'Amethyst' => [153, 102, 204], 'Android Green' => [164, 198, 57], 'Anti-Flash White' => [242, 243, 244], 'Antique Brass' => [205, 149, 117], 'Antique Bronze' => [102, 93, 30], 'Antique Fuchsia' => [145, 92, 131], 'Antique Ruby' => [132, 27, 45], 'Antique White' => [250, 235, 215], 'Ao (English)' => [0, 128, 0], 'Apple Green' => [141, 182, 0], 'Apricot' => [251, 206, 177], 'Aqua' => [0, 255, 255], 'Aquamarine' => [127, 255, 212], 'Arctic Lime' => [208, 255, 20], 'Army Green' => [75, 83, 32], 'Arsenic' => [59, 68, 75], 'Artichoke' => [143, 151, 121], 'Arylide Yellow' => [233, 214, 107], 'Ash Grey' => [178, 190, 181], 'Asparagus' => [135, 169, 107], 'Atomic Tangerine' => [255, 153, 102], 'Auburn' => [165, 42, 42], 'Aureolin' => [253, 238, 0], 'AuroMetalSaurus' => [110, 127, 128], 'Avocado' => [86, 130, 3], 'Azure' => [0, 127, 255], 'Azure (Web Color)' => [240, 255, 255], 'Azure Mist' => [240, 255, 255], 'Azureish White' => [219, 233, 244], 'Baby Blue' => [137, 207, 240], 'Baby Blue Eyes' => [161, 202, 241], 'Baby Pink' => [244, 194, 194], 'Baby Powder' => [254, 254, 250], 'Baker-Miller Pink' => [255, 145, 175], 'Ball Blue' => [33, 171, 205], 'Banana Mania' => [250, 231, 181], 'Banana Yellow' => [255, 225, 53], 'Bangladesh Green' => [0, 106, 78], 'Barbie Pink' => [224, 33, 138], 'Barn Red' => [124, 10, 2], 'Battleship Grey' => [132, 132, 130], 'Bazaar' => [152, 119, 123], 'Beau Blue' => [188, 212, 230], 'Beaver' => [159, 129, 112], 'Beige' => [245, 245, 220], "B'dazzled Blue" => [46, 88, 148], 'Big Dip O’ruby' => [156, 37, 66], 'Bisque' => [255, 228, 196], 'Bistre' => [61, 43, 31], 'Bistre Brown' => [150, 113, 23], 'Bitter Lemon' => [202, 224, 13], 'Bitter Lime' => [191, 255, 0], 'Bittersweet' => [254, 111, 94], 'Bittersweet Shimmer' => [191, 79, 81], 'Black' => [0, 0, 0], 'Black Bean' => [61, 12, 2], 'Black Leather Jacket' => [37, 53, 41], 'Black Olive' => [59, 60, 54], 'Blanched Almond' => [255, 235, 205], 'Blast-Off Bronze' => [165, 113, 100], 'Bleu De France' => [49, 140, 231], 'Blizzard Blue' => [172, 229, 238], 'Blond' => [250, 240, 190], 'Blue' => [0, 0, 255], 'Blue (Crayola)' => [31, 117, 254], 'Blue (Munsell)' => [0, 147, 175], 'Blue (NCS)' => [0, 135, 189], 'Blue (Pantone)' => [0, 24, 168], 'Blue (Pigment)' => [51, 51, 153], 'Blue (RYB)' => [2, 71, 254], 'Blue Bell' => [162, 162, 208], 'Blue-Gray' => [102, 153, 204], 'Blue-Green' => [13, 152, 186], 'Blue Lagoon' => [172, 229, 238], 'Blue-Magenta Violet' => [85, 53, 146], 'Blue Sapphire' => [18, 97, 128], 'Blue-Violet' => [138, 43, 226], 'Blue Yonder' => [80, 114, 167], 'Blueberry' => [79, 134, 247], 'Bluebonnet' => [28, 28, 240], 'Blush' => [222, 93, 131], 'Bole' => [121, 68, 59], 'Bondi Blue' => [0, 149, 182], 'Bone' => [227, 218, 201], 'Boston University Red' => [204, 0, 0], 'Bottle Green' => [0, 106, 78], 'Boysenberry' => [135, 50, 96], 'Brandeis Blue' => [0, 112, 255], 'Brass' => [181, 166, 66], 'Brick Red' => [203, 65, 84], 'Bright Cerulean' => [29, 172, 214], 'Bright Green' => [102, 255, 0], 'Bright Lavender' => [191, 148, 228], 'Bright Lilac' => [216, 145, 239], 'Bright Maroon' => [195, 33, 72], 'Bright Navy Blue' => [25, 116, 210], 'Bright Pink' => [255, 0, 127], 'Bright Turquoise' => [8, 232, 222], 'Bright Ube' => [209, 159, 232], 'Brilliant Azure' => [51, 153, 255], 'Brilliant Lavender' => [244, 187, 255], 'Brilliant Rose' => [255, 85, 163], 'Brink Pink' => [251, 96, 127], 'British Racing Green' => [0, 66, 37], 'Bronze' => [205, 127, 50], 'Bronze Yellow' => [115, 112, 0], 'Brown (Traditional)' => [150, 75, 0], 'Brown (Web)' => [165, 42, 42], 'Brown-Nose' => [107, 68, 35], 'Brown Yellow' => [204, 153, 102], 'Brunswick Green' => [27, 77, 62], 'Bubble Gum' => [255, 193, 204], 'Bubbles' => [231, 254, 255], 'Buff' => [240, 220, 130], 'Bud Green' => [123, 182, 97], 'Bulgarian Rose' => [72, 6, 7], 'Burgundy' => [128, 0, 32], 'Burlywood' => [222, 184, 135], 'Burnt Orange' => [204, 85, 0], 'Burnt Sienna' => [233, 116, 81], 'Burnt Umber' => [138, 51, 36], 'Byzantine' => [189, 51, 164], 'Byzantium' => [112, 41, 99], 'Cadet' => [83, 104, 114], 'Cadet Blue' => [95, 158, 160], 'Cadet Grey' => [145, 163, 176], 'Cadmium Green' => [0, 107, 60], 'Cadmium Orange' => [237, 135, 45], 'Cadmium Red' => [227, 0, 34], 'Cadmium Yellow' => [255, 246, 0], 'Café Au Lait' => [166, 123, 91], 'Café Noir' => [75, 54, 33], 'Cal Poly Green' => [30, 77, 43], 'Cambridge Blue' => [163, 193, 173], 'Camel' => [193, 154, 107], 'Cameo Pink' => [239, 187, 204], 'Camouflage Green' => [120, 134, 107], 'Canary Yellow' => [255, 239, 0], 'Candy Apple Red' => [255, 8, 0], 'Candy Pink' => [228, 113, 122], 'Capri' => [0, 191, 255], 'Caput Mortuum' => [89, 39, 32], 'Cardinal' => [196, 30, 58], 'Caribbean Green' => [0, 204, 153], 'Carmine' => [150, 0, 24], 'Carmine (M&P)' => [215, 0, 64], 'Carmine Pink' => [235, 76, 66], 'Carmine Red' => [255, 0, 56], 'Carnation Pink' => [255, 166, 201], 'Carnelian' => [179, 27, 27], 'Carolina Blue' => [86, 160, 211], 'Carrot Orange' => [237, 145, 33], 'Castleton Green' => [0, 86, 63], 'Catalina Blue' => [6, 42, 120], 'Catawba' => [112, 54, 66], 'Cedar Chest' => [201, 90, 73], 'Ceil' => [146, 161, 207], 'Celadon' => [172, 225, 175], 'Celadon Blue' => [0, 123, 167], 'Celadon Green' => [47, 132, 124], 'Celeste' => [178, 255, 255], 'Celestial Blue' => [73, 151, 208], 'Cerise' => [222, 49, 99], 'Cerise Pink' => [236, 59, 131], 'Cerulean' => [0, 123, 167], 'Cerulean Blue' => [42, 82, 190], 'Cerulean Frost' => [109, 155, 195], 'CG Blue' => [0, 122, 165], 'CG Red' => [224, 60, 49], 'Chamoisee' => [160, 120, 90], 'Champagne' => [247, 231, 206], 'Charcoal' => [54, 69, 79], 'Charleston Green' => [35, 43, 43], 'Charm Pink' => [230, 143, 172], 'Chartreuse (Traditional)' => [223, 255, 0], 'Chartreuse (Web)' => [127, 255, 0], 'Cherry' => [222, 49, 99], 'Cherry Blossom Pink' => [255, 183, 197], 'Chestnut' => [149, 69, 53], 'China Pink' => [222, 111, 161], 'China Rose' => [168, 81, 110], 'Chinese Red' => [170, 56, 30], 'Chinese Violet' => [133, 96, 136], 'Chocolate (Traditional)' => [123, 63, 0], 'Chocolate (Web)' => [210, 105, 30], 'Chrome Yellow' => [255, 167, 0], 'Cinereous' => [152, 129, 123], 'Cinnabar' => [227, 66, 52], 'Cinnamon[Citation Needed]' => [210, 105, 30], 'Citrine' => [228, 208, 10], 'Citron' => [159, 169, 31], 'Claret' => [127, 23, 52], 'Classic Rose' => [251, 204, 231], 'Cobalt Blue' => [0, 71, 171], 'Cocoa Brown' => [210, 105, 30], 'Coconut' => [150, 90, 62], 'Coffee' => [111, 78, 55], 'Columbia Blue' => [196, 216, 226], 'Congo Pink' => [248, 131, 121], 'Cool Black' => [0, 46, 99], 'Cool Grey' => [140, 146, 172], 'Copper' => [184, 115, 51], 'Copper (Crayola)' => [218, 138, 103], 'Copper Penny' => [173, 111, 105], 'Copper Red' => [203, 109, 81], 'Copper Rose' => [153, 102, 102], 'Coquelicot' => [255, 56, 0], 'Coral' => [255, 127, 80], 'Coral Pink' => [248, 131, 121], 'Coral Red' => [255, 64, 64], 'Cordovan' => [137, 63, 69], 'Corn' => [251, 236, 93], 'Cornell Red' => [179, 27, 27], 'Cornflower Blue' => [100, 149, 237], 'Cornsilk' => [255, 248, 220], 'Cosmic Latte' => [255, 248, 231], 'Coyote Brown' => [129, 97, 62], 'Cotton Candy' => [255, 188, 217], 'Cream' => [255, 253, 208], 'Crimson' => [220, 20, 60], 'Crimson Glory' => [190, 0, 50], 'Crimson Red' => [153, 0, 0], 'Cyan' => [0, 255, 255], 'Cyan Azure' => [78, 130, 180], 'Cyan-Blue Azure' => [70, 130, 191], 'Cyan Cobalt Blue' => [40, 88, 156], 'Cyan Cornflower Blue' => [24, 139, 194], 'Cyan (Process)' => [0, 183, 235], 'Cyber Grape' => [88, 66, 124], 'Cyber Yellow' => [255, 211, 0], 'Daffodil' => [255, 255, 49], 'Dandelion' => [240, 225, 48], 'Dark Blue' => [0, 0, 139], 'Dark Blue-Gray' => [102, 102, 153], 'Dark Brown' => [101, 67, 33], 'Dark Brown-Tangelo' => [136, 101, 78], 'Dark Byzantium' => [93, 57, 84], 'Dark Candy Apple Red' => [164, 0, 0], 'Dark Cerulean' => [8, 69, 126], 'Dark Chestnut' => [152, 105, 96], 'Dark Coral' => [205, 91, 69], 'Dark Cyan' => [0, 139, 139], 'Dark Electric Blue' => [83, 104, 120], 'Dark Goldenrod' => [184, 134, 11], 'Dark Gray (X11)' => [169, 169, 169], 'Dark Green' => [1, 50, 32], 'Dark Green (X11)' => [0, 100, 0], 'Dark Gunmetal' => [0, 100, 0], 'Dark Imperial Blue' => [110, 110, 249], 'Dark Jungle Green' => [26, 36, 33], 'Dark Khaki' => [189, 183, 107], 'Dark Lava' => [72, 60, 50], 'Dark Lavender' => [115, 79, 150], 'Dark Liver' => [83, 75, 79], 'Dark Liver (Horses)' => [84, 61, 55], 'Dark Magenta' => [139, 0, 139], 'Dark Medium Gray' => [169, 169, 169], 'Dark Midnight Blue' => [0, 51, 102], 'Dark Moss Green' => [74, 93, 35], 'Dark Olive Green' => [85, 107, 47], 'Dark Orange' => [255, 140, 0], 'Dark Orchid' => [153, 50, 204], 'Dark Pastel Blue' => [119, 158, 203], 'Dark Pastel Green' => [3, 192, 60], 'Dark Pastel Purple' => [150, 111, 214], 'Dark Pastel Red' => [194, 59, 34], 'Dark Pink' => [231, 84, 128], 'Dark Powder Blue' => [0, 51, 153], 'Dark Puce' => [79, 58, 60], 'Dark Purple' => [48, 25, 52], 'Dark Raspberry' => [135, 38, 87], 'Dark Red' => [139, 0, 0], 'Dark Salmon' => [233, 150, 122], 'Dark Scarlet' => [86, 3, 25], 'Dark Sea Green' => [143, 188, 143], 'Dark Sienna' => [60, 20, 20], 'Dark Sky Blue' => [140, 190, 214], 'Dark Slate Blue' => [72, 61, 139], 'Dark Slate Gray' => [47, 79, 79], 'Dark Spring Green' => [23, 114, 69], 'Dark Tan' => [145, 129, 81], 'Dark Tangerine' => [255, 168, 18], 'Dark Taupe' => [72, 60, 50], 'Dark Terra Cotta' => [204, 78, 92], 'Dark Turquoise' => [0, 206, 209], 'Dark Vanilla' => [209, 190, 168], 'Dark Violet' => [148, 0, 211], 'Dark Yellow' => [155, 135, 12], 'Dartmouth Green' => [0, 112, 60], "Davy's Grey" => [85, 85, 85], 'Debian Red' => [215, 10, 83], 'Deep Aquamarine' => [64, 130, 109], 'Deep Carmine' => [169, 32, 62], 'Deep Carmine Pink' => [239, 48, 56], 'Deep Carrot Orange' => [233, 105, 44], 'Deep Cerise' => [218, 50, 135], 'Deep Champagne' => [250, 214, 165], 'Deep Chestnut' => [185, 78, 72], 'Deep Coffee' => [112, 66, 65], 'Deep Fuchsia' => [193, 84, 193], 'Deep Green' => [5, 102, 8], 'Deep Green-Cyan Turquoise' => [14, 124, 97], 'Deep Jungle Green' => [0, 75, 73], 'Deep Koamaru' => [51, 51, 102], 'Deep Lemon' => [245, 199, 26], 'Deep Lilac' => [153, 85, 187], 'Deep Magenta' => [204, 0, 204], 'Deep Maroon' => [130, 0, 0], 'Deep Mauve' => [212, 115, 212], 'Deep Moss Green' => [53, 94, 59], 'Deep Peach' => [255, 203, 164], 'Deep Pink' => [255, 20, 147], 'Deep Puce' => [169, 92, 104], 'Deep Red' => [133, 1, 1], 'Deep Ruby' => [132, 63, 91], 'Deep Saffron' => [255, 153, 51], 'Deep Sky Blue' => [0, 191, 255], 'Deep Space Sparkle' => [74, 100, 108], 'Deep Spring Bud' => [85, 107, 47], 'Deep Taupe' => [126, 94, 96], 'Deep Tuscan Red' => [102, 66, 77], 'Deep Violet' => [51, 0, 102], 'Deer' => [186, 135, 89], 'Denim' => [21, 96, 189], 'Desaturated Cyan' => [102, 153, 153], 'Desert' => [193, 154, 107], 'Desert Sand' => [237, 201, 175], 'Desire' => [234, 60, 83], 'Diamond' => [185, 242, 255], 'Dim Gray' => [105, 105, 105], 'Dirt' => [155, 118, 83], 'Dodger Blue' => [30, 144, 255], 'Dogwood Rose' => [215, 24, 104], 'Dollar Bill' => [133, 187, 101], 'Donkey Brown' => [102, 76, 40], 'Drab' => [150, 113, 23], 'Duke Blue' => [0, 0, 156], 'Dust Storm' => [229, 204, 201], 'Dutch White' => [239, 223, 187], 'Earth Yellow' => [225, 169, 95], 'Ebony' => [85, 93, 80], 'Ecru' => [194, 178, 128], 'Eerie Black' => [27, 27, 27], 'Eggplant' => [97, 64, 81], 'Eggshell' => [240, 234, 214], 'Egyptian Blue' => [16, 52, 166], 'Electric Blue' => [125, 249, 255], 'Electric Crimson' => [255, 0, 63], 'Electric Cyan' => [0, 255, 255], 'Electric Green' => [0, 255, 0], 'Electric Indigo' => [111, 0, 255], 'Electric Lavender' => [244, 187, 255], 'Electric Lime' => [204, 255, 0], 'Electric Purple' => [191, 0, 255], 'Electric Ultramarine' => [63, 0, 255], 'Electric Violet' => [143, 0, 255], 'Electric Yellow' => [255, 255, 51], 'Emerald' => [80, 200, 120], 'Eminence' => [108, 48, 130], 'English Green' => [27, 77, 62], 'English Lavender' => [180, 131, 149], 'English Red' => [171, 75, 82], 'English Violet' => [86, 60, 92], 'Eton Blue' => [150, 200, 162], 'Eucalyptus' => [68, 215, 168], 'Fallow' => [193, 154, 107], 'Falu Red' => [128, 24, 24], 'Fandango' => [181, 51, 137], 'Fandango Pink' => [222, 82, 133], 'Fashion Fuchsia' => [244, 0, 161], 'Fawn' => [229, 170, 112], 'Feldgrau' => [77, 93, 83], 'Feldspar' => [253, 213, 177], 'Fern Green' => [79, 121, 66], 'Ferrari Red' => [255, 40, 0], 'Field Drab' => [108, 84, 30], 'Firebrick' => [178, 34, 34], 'Fire Engine Red' => [206, 32, 41], 'Flame' => [226, 88, 34], 'Flamingo Pink' => [252, 142, 172], 'Flattery' => [107, 68, 35], 'Flavescent' => [247, 233, 142], 'Flax' => [238, 220, 130], 'Flirt' => [162, 0, 109], 'Floral White' => [255, 250, 240], 'Fluorescent Orange' => [255, 191, 0], 'Fluorescent Pink' => [255, 20, 147], 'Fluorescent Yellow' => [204, 255, 0], 'Folly' => [255, 0, 79], 'Forest Green (Traditional)' => [1, 68, 33], 'Forest Green (Web)' => [34, 139, 34], 'French Beige' => [166, 123, 91], 'French Bistre' => [133, 109, 77], 'French Blue' => [0, 114, 187], 'French Fuchsia' => [253, 63, 146], 'French Lilac' => [134, 96, 142], 'French Lime' => [158, 253, 56], 'French Mauve' => [212, 115, 212], 'French Pink' => [253, 108, 158], 'French Plum' => [129, 20, 83], 'French Puce' => [78, 22, 9], 'French Raspberry' => [199, 44, 72], 'French Rose' => [246, 74, 138], 'French Sky Blue' => [119, 181, 254], 'French Violet' => [136, 6, 206], 'French Wine' => [172, 30, 68], 'Fresh Air' => [166, 231, 255], 'Fuchsia' => [255, 0, 255], 'Fuchsia (Crayola)' => [193, 84, 193], 'Fuchsia Pink' => [255, 119, 255], 'Fuchsia Purple' => [204, 57, 123], 'Fuchsia Rose' => [199, 67, 117], 'Fulvous' => [228, 132, 0], 'Fuzzy Wuzzy' => [204, 102, 102], 'Gainsboro' => [220, 220, 220], 'Gamboge' => [228, 155, 15], 'Gamboge Orange (Brown)' => [153, 102, 0], 'Generic Viridian' => [0, 127, 102], 'Ghost White' => [248, 248, 255], 'Giants Orange' => [254, 90, 29], 'Ginger' => [176, 101, 0], 'Glaucous' => [96, 130, 182], 'Glitter' => [230, 232, 250], 'GO Green' => [0, 171, 102], 'Gold (Metallic)' => [212, 175, 55], 'Gold (Web) (Golden)' => [255, 215, 0], 'Gold Fusion' => [133, 117, 78], 'Golden Brown' => [153, 101, 21], 'Golden Poppy' => [252, 194, 0], 'Golden Yellow' => [255, 223, 0], 'Goldenrod' => [218, 165, 32], 'Granny Smith Apple' => [168, 228, 160], 'Grape' => [111, 45, 168], 'Gray' => [128, 128, 128], 'Gray (HTML/CSS Gray)' => [128, 128, 128], 'Gray (X11 Gray)' => [190, 190, 190], 'Gray-Asparagus' => [70, 89, 69], 'Gray-Blue' => [140, 146, 172], 'Green (Color Wheel) (X11 Green)' => [0, 255, 0], 'Green (Crayola)' => [28, 172, 120], 'Green (HTML/CSS Color)' => [0, 128, 0], 'Green (Munsell)' => [0, 168, 119], 'Green (NCS)' => [0, 159, 107], 'Green (Pantone)' => [0, 173, 67], 'Green (Pigment)' => [0, 165, 80], 'Green (RYB)' => [102, 176, 50], 'Green-Blue' => [17, 100, 180], 'Green-Cyan' => [0, 153, 102], 'Green-Yellow' => [173, 255, 47], 'Grizzly' => [136, 88, 24], 'Grullo' => [169, 154, 134], 'Guppie Green' => [0, 255, 127], 'Gunmetal' => [42, 52, 57], 'Halayà Úbe' => [102, 56, 84], 'Han Blue' => [68, 108, 207], 'Han Purple' => [82, 24, 250], 'Hansa Yellow' => [233, 214, 107], 'Harlequin' => [63, 255, 0], 'Harlequin Green' => [70, 203, 24], 'Harvard Crimson' => [201, 0, 22], 'Harvest Gold' => [218, 145, 0], 'Heart Gold' => [128, 128, 0], 'Heliotrope' => [223, 115, 255], 'Heliotrope Gray' => [170, 152, 169], 'Heliotrope Magenta' => [170, 0, 187], 'Hollywood Cerise' => [244, 0, 161], 'Honeydew' => [240, 255, 240], 'Honolulu Blue' => [0, 109, 176], "Hooker's Green" => [73, 121, 107], 'Hot Magenta' => [255, 29, 206], 'Hot Pink' => [255, 105, 180], 'Hunter Green' => [53, 94, 59], 'Iceberg' => [113, 166, 210], 'Icterine' => [252, 247, 94], 'Illuminating Emerald' => [49, 145, 119], 'Imperial' => [96, 47, 107], 'Imperial Blue' => [0, 35, 149], 'Imperial Purple' => [102, 2, 60], 'Imperial Red' => [237, 41, 57], 'Inchworm' => [178, 236, 93], 'Independence' => [76, 81, 109], 'India Green' => [19, 136, 8], 'Indian Red' => [205, 92, 92], 'Indian Yellow' => [227, 168, 87], 'Indigo' => [75, 0, 130], 'Indigo Dye' => [9, 31, 146], 'Indigo (Web)' => [75, 0, 130], 'International Klein Blue' => [0, 47, 167], 'International Orange (Aerospace)' => [255, 79, 0], 'International Orange (Engineering)' => [186, 22, 12], 'International Orange (Golden Gate Bridge)' => [192, 54, 44], 'Iris' => [90, 79, 207], 'Irresistible' => [179, 68, 108], 'Isabelline' => [244, 240, 236], 'Islamic Green' => [0, 144, 0], 'Italian Sky Blue' => [178, 255, 255], 'Ivory' => [255, 255, 240], 'Jade' => [0, 168, 107], 'Japanese Carmine' => [157, 41, 51], 'Japanese Indigo' => [38, 67, 72], 'Japanese Violet' => [91, 50, 86], 'Jasmine' => [248, 222, 126], 'Jasper' => [215, 59, 62], 'Jazzberry Jam' => [165, 11, 94], 'Jelly Bean' => [218, 97, 78], 'Jet' => [52, 52, 52], 'Jonquil' => [244, 202, 22], 'Jordy Blue' => [138, 185, 241], 'June Bud' => [189, 218, 87], 'Jungle Green' => [41, 171, 135], 'Kelly Green' => [76, 187, 23], 'Kenyan Copper' => [124, 28, 5], 'Keppel' => [58, 176, 158], 'Khaki (HTML/CSS) (Khaki)' => [195, 176, 145], 'Khaki (X11) (Light Khaki)' => [240, 230, 140], 'Kobe' => [136, 45, 23], 'Kobi' => [231, 159, 196], 'Kobicha' => [107, 68, 35], 'Kombu Green' => [53, 66, 48], 'KU Crimson' => [232, 0, 13], 'La Salle Green' => [8, 120, 48], 'Languid Lavender' => [214, 202, 221], 'Lapis Lazuli' => [38, 97, 156], 'Laser Lemon' => [255, 255, 102], 'Laurel Green' => [169, 186, 157], 'Lava' => [207, 16, 32], 'Lavender (Floral)' => [181, 126, 220], 'Lavender (Web)' => [230, 230, 250], 'Lavender Blue' => [204, 204, 255], 'Lavender Blush' => [255, 240, 245], 'Lavender Gray' => [196, 195, 208], 'Lavender Indigo' => [148, 87, 235], 'Lavender Magenta' => [238, 130, 238], 'Lavender Mist' => [230, 230, 250], 'Lavender Pink' => [251, 174, 210], 'Lavender Purple' => [150, 123, 182], 'Lavender Rose' => [251, 160, 227], 'Lawn Green' => [124, 252, 0], 'Lemon' => [255, 247, 0], 'Lemon Chiffon' => [255, 250, 205], 'Lemon Curry' => [204, 160, 29], 'Lemon Glacier' => [253, 255, 0], 'Lemon Lime' => [227, 255, 0], 'Lemon Meringue' => [246, 234, 190], 'Lemon Yellow' => [255, 244, 79], 'Lenurple' => [186, 147, 216], 'Licorice' => [26, 17, 16], 'Liberty' => [84, 90, 167], 'Light Apricot' => [253, 213, 177], 'Light Blue' => [173, 216, 230], 'Light Brilliant Red' => [254, 46, 46], 'Light Brown' => [181, 101, 29], 'Light Carmine Pink' => [230, 103, 113], 'Light Cobalt Blue' => [136, 172, 224], 'Light Coral' => [240, 128, 128], 'Light Cornflower Blue' => [147, 204, 234], 'Light Crimson' => [245, 105, 145], 'Light Cyan' => [224, 255, 255], 'Light Deep Pink' => [255, 92, 205], 'Light French Beige' => [200, 173, 127], 'Light Fuchsia Pink' => [249, 132, 239], 'Light Goldenrod Yellow' => [250, 250, 210], 'Light Gray' => [211, 211, 211], 'Light Grayish Magenta' => [204, 153, 204], 'Light Green' => [144, 238, 144], 'Light Hot Pink' => [255, 179, 222], 'Light Khaki' => [240, 230, 140], 'Light Medium Orchid' => [211, 155, 203], 'Light Moss Green' => [173, 223, 173], 'Light Orchid' => [230, 168, 215], 'Light Pastel Purple' => [177, 156, 217], 'Light Pink' => [255, 182, 193], 'Light Red Ochre' => [233, 116, 81], 'Light Salmon' => [255, 160, 122], 'Light Salmon Pink' => [255, 153, 153], 'Light Sea Green' => [32, 178, 170], 'Light Sky Blue' => [135, 206, 250], 'Light Slate Gray' => [119, 136, 153], 'Light Steel Blue' => [176, 196, 222], 'Light Taupe' => [179, 139, 109], 'Light Thulian Pink' => [230, 143, 172], 'Light Yellow' => [255, 255, 224], 'Lilac' => [200, 162, 200], 'Lime (Color Wheel)' => [191, 255, 0], 'Lime (Web) (X11 Green)' => [0, 255, 0], 'Lime Green' => [50, 205, 50], 'Limerick' => [157, 194, 9], 'Lincoln Green' => [25, 89, 5], 'Linen' => [250, 240, 230], 'Lion' => [193, 154, 107], 'Liseran Purple' => [222, 111, 161], 'Little Boy Blue' => [108, 160, 220], 'Liver' => [103, 76, 71], 'Liver (Dogs)' => [184, 109, 41], 'Liver (Organ)' => [108, 46, 31], 'Liver Chestnut' => [152, 116, 86], 'Livid' => [102, 153, 204], 'Lumber' => [255, 228, 205], 'Lust' => [230, 32, 32], 'Macaroni And Cheese' => [255, 189, 136], 'Magenta' => [255, 0, 255], 'Magenta (Crayola)' => [255, 85, 163], 'Magenta (Dye)' => [202, 31, 123], 'Magenta (Pantone)' => [208, 65, 126], 'Magenta (Process)' => [255, 0, 144], 'Magenta Haze' => [159, 69, 118], 'Magenta-Pink' => [204, 51, 139], 'Magic Mint' => [170, 240, 209], 'Magnolia' => [248, 244, 255], 'Mahogany' => [192, 64, 0], 'Maize' => [251, 236, 93], 'Majorelle Blue' => [96, 80, 220], 'Malachite' => [11, 218, 81], 'Manatee' => [151, 154, 170], 'Mango Tango' => [255, 130, 67], 'Mantis' => [116, 195, 101], 'Mardi Gras' => [136, 0, 133], 'Marigold' => [234, 162, 33], 'Maroon (Crayola)' => [195, 33, 72], 'Maroon (HTML/CSS)' => [128, 0, 0], 'Maroon (X11)' => [176, 48, 96], 'Mauve' => [224, 176, 255], 'Mauve Taupe' => [145, 95, 109], 'Mauvelous' => [239, 152, 170], 'May Green' => [76, 145, 65], 'Maya Blue' => [115, 194, 251], 'Meat Brown' => [229, 183, 59], 'Medium Aquamarine' => [102, 221, 170], 'Medium Blue' => [0, 0, 205], 'Medium Candy Apple Red' => [226, 6, 44], 'Medium Carmine' => [175, 64, 53], 'Medium Champagne' => [243, 229, 171], 'Medium Electric Blue' => [3, 80, 150], 'Medium Jungle Green' => [28, 53, 45], 'Medium Lavender Magenta' => [221, 160, 221], 'Medium Orchid' => [186, 85, 211], 'Medium Persian Blue' => [0, 103, 165], 'Medium Purple' => [147, 112, 219], 'Medium Red-Violet' => [187, 51, 133], 'Medium Ruby' => [170, 64, 105], 'Medium Sea Green' => [60, 179, 113], 'Medium Sky Blue' => [128, 218, 235], 'Medium Slate Blue' => [123, 104, 238], 'Medium Spring Bud' => [201, 220, 135], 'Medium Spring Green' => [0, 250, 154], 'Medium Taupe' => [103, 76, 71], 'Medium Turquoise' => [72, 209, 204], 'Medium Tuscan Red' => [121, 68, 59], 'Medium Vermilion' => [217, 96, 59], 'Medium Violet-Red' => [199, 21, 133], 'Mellow Apricot' => [248, 184, 120], 'Mellow Yellow' => [248, 222, 126], 'Melon' => [253, 188, 180], 'Metallic Seaweed' => [10, 126, 140], 'Metallic Sunburst' => [156, 124, 56], 'Mexican Pink' => [228, 0, 124], 'Midnight Blue' => [25, 25, 112], 'Midnight Green (Eagle Green)' => [0, 73, 83], 'Mikado Yellow' => [255, 196, 12], 'Mindaro' => [227, 249, 136], 'Ming' => [54, 116, 125], 'Mint' => [62, 180, 137], 'Mint Cream' => [245, 255, 250], 'Mint Green' => [152, 255, 152], 'Misty Rose' => [255, 228, 225], 'Moccasin' => [250, 235, 215], 'Mode Beige' => [150, 113, 23], 'Moonstone Blue' => [115, 169, 194], 'Mordant Red 19' => [174, 12, 0], 'Moss Green' => [138, 154, 91], 'Mountain Meadow' => [48, 186, 143], 'Mountbatten Pink' => [153, 122, 141], 'MSU Green' => [24, 69, 59], 'Mughal Green' => [48, 96, 48], 'Mulberry' => [197, 75, 140], 'Mustard' => [255, 219, 88], 'Myrtle Green' => [49, 120, 115], 'Nadeshiko Pink' => [246, 173, 198], 'Napier Green' => [42, 128, 0], 'Naples Yellow' => [250, 218, 94], 'Navajo White' => [255, 222, 173], 'Navy' => [0, 0, 128], 'Navy Purple' => [148, 87, 235], 'Neon Carrot' => [255, 163, 67], 'Neon Fuchsia' => [254, 65, 100], 'Neon Green' => [57, 255, 20], 'New Car' => [33, 79, 198], 'New York Pink' => [215, 131, 127], 'Non-Photo Blue' => [164, 221, 237], 'North Texas Green' => [5, 144, 51], 'Nyanza' => [233, 255, 219], 'Ocean Boat Blue' => [0, 119, 190], 'Ochre' => [204, 119, 34], 'Office Green' => [0, 128, 0], 'Old Burgundy' => [67, 48, 46], 'Old Gold' => [207, 181, 59], 'Old Heliotrope' => [86, 60, 92], 'Old Lace' => [253, 245, 230], 'Old Lavender' => [121, 104, 120], 'Old Mauve' => [103, 49, 71], 'Old Moss Green' => [134, 126, 54], 'Old Rose' => [192, 128, 129], 'Old Silver' => [132, 132, 130], 'Olive' => [128, 128, 0], 'Olive Drab (' => [107, 142, 35], 'Olive Drab' => [60, 52, 31], 'Olivine' => [154, 185, 115], 'Onyx' => [53, 56, 57], 'Opera Mauve' => [183, 132, 167], 'Orange (Color Wheel)' => [255, 127, 0], 'Orange (Crayola)' => [255, 117, 56], 'Orange (Pantone)' => [255, 88, 0], 'Orange (RYB)' => [251, 153, 2], 'Orange (Web)' => [255, 165, 0], 'Orange Peel' => [255, 159, 0], 'Orange-Red' => [255, 69, 0], 'Orange-Yellow' => [248, 213, 104], 'Orchid' => [218, 112, 214], 'Orchid Pink' => [242, 189, 205], 'Orioles Orange' => [251, 79, 20], 'Otter Brown' => [101, 67, 33], 'Outer Space' => [65, 74, 76], 'Outrageous Orange' => [255, 110, 74], 'Oxford Blue' => [0, 33, 71], 'OU Crimson Red' => [153, 0, 0], 'Pacific Blue' => [28, 169, 201], 'Pakistan Green' => [0, 102, 0], 'Palatinate Blue' => [39, 59, 226], 'Palatinate Purple' => [104, 40, 96], 'Pale Aqua' => [188, 212, 230], 'Pale Blue' => [175, 238, 238], 'Pale Brown' => [152, 118, 84], 'Pale Carmine' => [175, 64, 53], 'Pale Cerulean' => [155, 196, 226], 'Pale Chestnut' => [221, 173, 175], 'Pale Copper' => [218, 138, 103], 'Pale Cornflower Blue' => [171, 205, 239], 'Pale Cyan' => [135, 211, 248], 'Pale Gold' => [230, 190, 138], 'Pale Goldenrod' => [238, 232, 170], 'Pale Green' => [152, 251, 152], 'Pale Lavender' => [220, 208, 255], 'Pale Magenta' => [249, 132, 229], 'Pale Magenta-Pink' => [255, 153, 204], 'Pale Pink' => [250, 218, 221], 'Pale Plum' => [221, 160, 221], 'Pale Red-Violet' => [219, 112, 147], 'Pale Robin Egg Blue' => [150, 222, 209], 'Pale Silver' => [201, 192, 187], 'Pale Spring Bud' => [236, 235, 189], 'Pale Taupe' => [188, 152, 126], 'Pale Turquoise' => [175, 238, 238], 'Pale Violet' => [204, 153, 255], 'Pale Violet-Red' => [219, 112, 147], 'Pansy Purple' => [120, 24, 74], 'Paolo Veronese Green' => [0, 155, 125], 'Papaya Whip' => [255, 239, 213], 'Paradise Pink' => [230, 62, 98], 'Paris Green' => [80, 200, 120], 'Pastel Blue' => [174, 198, 207], 'Pastel Brown' => [131, 105, 83], 'Pastel Gray' => [207, 207, 196], 'Pastel Green' => [119, 221, 119], 'Pastel Magenta' => [244, 154, 194], 'Pastel Orange' => [255, 179, 71], 'Pastel Pink' => [222, 165, 164], 'Pastel Purple' => [179, 158, 181], 'Pastel Red' => [255, 105, 97], 'Pastel Violet' => [203, 153, 201], 'Pastel Yellow' => [253, 253, 150], 'Patriarch' => [128, 0, 128], "Payne's Grey" => [83, 104, 120], 'Peach' => [255, 203, 164], 'Peach-Orange' => [255, 204, 153], 'Peach Puff' => [255, 218, 185], 'Peach-Yellow' => [250, 223, 173], 'Pear' => [209, 226, 49], 'Pearl' => [234, 224, 200], 'Pearl Aqua' => [136, 216, 192], 'Pearly Purple' => [183, 104, 162], 'Peridot' => [230, 226, 0], 'Periwinkle' => [204, 204, 255], 'Permanent Geranium Lake' => [225, 44, 44], 'Persian Blue' => [28, 57, 187], 'Persian Green' => [0, 166, 147], 'Persian Indigo' => [50, 18, 122], 'Persian Orange' => [217, 144, 88], 'Persian Pink' => [247, 127, 190], 'Persian Plum' => [112, 28, 28], 'Persian Red' => [204, 51, 51], 'Persian Rose' => [254, 40, 162], 'Persimmon' => [236, 88, 0], 'Peru' => [205, 133, 63], 'Phlox' => [223, 0, 255], 'Phthalo Blue' => [0, 15, 137], 'Phthalo Green' => [18, 53, 36], 'Picton Blue' => [69, 177, 232], 'Pictorial Carmine' => [195, 11, 78], 'Piggy Pink' => [253, 221, 230], 'Pine Green' => [1, 121, 111], 'Pineapple' => [86, 60, 92], 'Pink' => [255, 192, 203], 'Pink (Pantone)' => [215, 72, 148], 'Pink Flamingo' => [252, 116, 253], 'Pink Lace' => [255, 221, 244], 'Pink Lavender' => [216, 178, 209], 'Pink-Orange' => [255, 153, 102], 'Pink Pearl' => [231, 172, 207], 'Pink Raspberry' => [152, 0, 54], 'Pink Sherbet' => [247, 143, 167], 'Pistachio' => [147, 197, 114], 'Platinum' => [229, 228, 226], 'Plum' => [142, 69, 133], 'Plum (Web)' => [221, 160, 221], 'Pomp And Power' => [134, 96, 142], 'Popstar' => [190, 79, 98], 'Portland Orange' => [255, 90, 54], 'Powder Blue' => [176, 224, 230], 'Princeton Orange' => [245, 128, 37], 'Prune' => [112, 28, 28], 'Prussian Blue' => [0, 49, 83], 'Psychedelic Purple' => [223, 0, 255], 'Puce' => [204, 136, 153], 'Puce Red' => [114, 47, 55], 'Pullman Brown (UPS Brown)' => [100, 65, 23], 'Pullman Green' => [59, 51, 28], 'Pumpkin' => [255, 117, 24], 'Purple (HTML)' => [128, 0, 128], 'Purple (Munsell)' => [159, 0, 197], 'Purple (X11)' => [160, 32, 240], 'Purple Heart' => [105, 53, 156], 'Purple Mountain Majesty' => [150, 120, 182], 'Purple Navy' => [78, 81, 128], 'Purple Pizzazz' => [254, 78, 218], 'Purple Taupe' => [80, 64, 77], 'Purpureus' => [154, 78, 174], 'Quartz' => [81, 72, 79], 'Queen Blue' => [67, 107, 149], 'Queen Pink' => [232, 204, 215], 'Quinacridone Magenta' => [142, 58, 89], 'Rackley' => [93, 138, 168], 'Radical Red' => [255, 53, 94], 'Raisin Black' => [36, 33, 36], 'Rajah' => [251, 171, 96], 'Raspberry' => [227, 11, 93], 'Raspberry Glace' => [145, 95, 109], 'Raspberry Pink' => [226, 80, 152], 'Raspberry Rose' => [179, 68, 108], 'Raw Sienna' => [214, 138, 89], 'Raw Umber' => [130, 102, 68], 'Razzle Dazzle Rose' => [255, 51, 204], 'Razzmatazz' => [227, 37, 107], 'Razzmic Berry' => [141, 78, 133], 'Rebecca Purple' => [102, 51, 153], 'Red' => [255, 0, 0], 'Red (Crayola)' => [238, 32, 77], 'Red (Munsell)' => [242, 0, 60], 'Red (NCS)' => [196, 2, 51], 'Red (Pantone)' => [237, 41, 57], 'Red (Pigment)' => [237, 28, 36], 'Red (RYB)' => [254, 39, 18], 'Red-Brown' => [165, 42, 42], 'Red Devil' => [134, 1, 17], 'Red-Orange' => [255, 83, 73], 'Red-Purple' => [228, 0, 120], 'Red-Violet' => [199, 21, 133], 'Redwood' => [164, 90, 82], 'Regalia' => [82, 45, 128], 'Registration Black' => [0, 0, 0], 'Resolution Blue' => [0, 35, 135], 'Rhythm' => [119, 118, 150], 'Rich Black' => [0, 64, 64], 'Rich Black (FOGRA29)' => [1, 11, 19], 'Rich Black (FOGRA39)' => [1, 2, 3], 'Rich Brilliant Lavender' => [241, 167, 254], 'Rich Carmine' => [215, 0, 64], 'Rich Electric Blue' => [8, 146, 208], 'Rich Lavender' => [167, 107, 207], 'Rich Lilac' => [182, 102, 210], 'Rich Maroon' => [176, 48, 96], 'Rifle Green' => [68, 76, 56], 'Roast Coffee' => [112, 66, 65], 'Robin Egg Blue' => [0, 204, 204], 'Rocket Metallic' => [138, 127, 128], 'Roman Silver' => [131, 137, 150], 'Rose' => [255, 0, 127], 'Rose Bonbon' => [249, 66, 158], 'Rose Ebony' => [103, 72, 70], 'Rose Gold' => [183, 110, 121], 'Rose Madder' => [227, 38, 54], 'Rose Pink' => [255, 102, 204], 'Rose Quartz' => [170, 152, 169], 'Rose Red' => [194, 30, 86], 'Rose Taupe' => [144, 93, 93], 'Rose Vale' => [171, 78, 82], 'Rosewood' => [101, 0, 11], 'Rosso Corsa' => [212, 0, 0], 'Rosy Brown' => [188, 143, 143], 'Royal Azure' => [0, 56, 168], 'Royal Blue' => [65, 105, 225], 'Royal Fuchsia' => [202, 44, 146], 'Royal Purple' => [120, 81, 169], 'Royal Yellow' => [250, 218, 94], 'Ruber' => [206, 70, 118], 'Rubine Red' => [209, 0, 86], 'Ruby' => [224, 17, 95], 'Ruby Red' => [155, 17, 30], 'Ruddy' => [255, 0, 40], 'Ruddy Brown' => [187, 101, 40], 'Ruddy Pink' => [225, 142, 150], 'Rufous' => [168, 28, 7], 'Russet' => [128, 70, 27], 'Russian Green' => [103, 146, 103], 'Russian Violet' => [50, 23, 77], 'Rust' => [183, 65, 14], 'Rusty Red' => [218, 44, 67], 'Sacramento State Green' => [0, 86, 63], 'Saddle Brown' => [139, 69, 19], 'Safety Orange' => [255, 120, 0], 'Safety Orange (Blaze Orange)' => [255, 103, 0], 'Safety Yellow' => [238, 210, 2], 'Saffron' => [244, 196, 48], 'Sage' => [188, 184, 138], "St. Patrick's Blue" => [35, 41, 122], 'Salmon' => [250, 128, 114], 'Salmon Pink' => [255, 145, 164], 'Sand' => [194, 178, 128], 'Sand Dune' => [150, 113, 23], 'Sandstorm' => [236, 213, 64], 'Sandy Brown' => [244, 164, 96], 'Sandy Taupe' => [150, 113, 23], 'Sangria' => [146, 0, 10], 'Sap Green' => [80, 125, 42], 'Sapphire' => [15, 82, 186], 'Sapphire Blue' => [0, 103, 165], 'Satin Sheen Gold' => [203, 161, 53], 'Scarlet' => [253, 14, 53], 'Schauss Pink' => [255, 145, 175], 'School Bus Yellow' => [255, 216, 0], "Screamin' Green" => [118, 255, 122], 'Sea Blue' => [0, 105, 148], 'Sea Green' => [46, 139, 87], 'Seal Brown' => [89, 38, 11], 'Seashell' => [255, 245, 238], 'Selective Yellow' => [255, 186, 0], 'Sepia' => [112, 66, 20], 'Shadow' => [138, 121, 93], 'Shadow Blue' => [119, 139, 165], 'Shampoo' => [255, 207, 241], 'Shamrock Green' => [0, 158, 96], 'Sheen Green' => [143, 212, 0], 'Shimmering Blush' => [217, 134, 149], 'Shocking Pink' => [252, 15, 192], 'Shocking Pink (Crayola)' => [255, 111, 255], 'Sienna' => [136, 45, 23], 'Silver' => [192, 192, 192], 'Silver Chalice' => [172, 172, 172], 'Silver Lake Blue' => [93, 137, 186], 'Silver Pink' => [196, 174, 173], 'Silver Sand' => [191, 193, 194], 'Sinopia' => [203, 65, 11], 'Skobeloff' => [0, 116, 116], 'Sky Blue' => [135, 206, 235], 'Sky Magenta' => [207, 113, 175], 'Slate Blue' => [106, 90, 205], 'Slate Gray' => [112, 128, 144], 'Smalt (Dark Powder Blue)' => [0, 51, 153], 'Smitten' => [200, 65, 134], 'Smoke' => [115, 130, 118], 'Smoky Black' => [16, 12, 8], 'Smoky Topaz' => [147, 61, 65], 'Snow' => [255, 250, 250], 'Soap' => [206, 200, 239], 'Solid Pink' => [137, 56, 67], 'Sonic Silver' => [117, 117, 117], 'Spartan Crimson' => [158, 19, 22], 'Space Cadet' => [29, 41, 81], 'Spanish Bistre' => [128, 117, 50], 'Spanish Blue' => [0, 112, 184], 'Spanish Carmine' => [209, 0, 71], 'Spanish Crimson' => [229, 26, 76], 'Spanish Gray' => [152, 152, 152], 'Spanish Green' => [0, 145, 80], 'Spanish Orange' => [232, 97, 0], 'Spanish Pink' => [247, 191, 190], 'Spanish Red' => [230, 0, 38], 'Spanish Sky Blue' => [0, 255, 255], 'Spanish Violet' => [76, 40, 130], 'Spanish Viridian' => [0, 127, 92], 'Spicy Mix' => [139, 95, 77], 'Spiro Disco Ball' => [15, 192, 252], 'Spring Bud' => [167, 252, 0], 'Spring Green' => [0, 255, 127], 'Star Command Blue' => [0, 123, 184], 'Steel Blue' => [70, 130, 180], 'Steel Pink' => [204, 51, 204], 'Stil De Grain Yellow' => [250, 218, 94], 'Stizza' => [153, 0, 0], 'Stormcloud' => [79, 102, 106], 'Straw' => [228, 217, 111], 'Strawberry' => [252, 90, 141], 'Sunglow' => [255, 204, 51], 'Sunray' => [227, 171, 87], 'Sunset' => [250, 214, 165], 'Sunset Orange' => [253, 94, 83], 'Super Pink' => [207, 107, 169], 'Tan' => [210, 180, 140], 'Tangelo' => [249, 77, 0], 'Tangerine' => [242, 133, 0], 'Tangerine Yellow' => [255, 204, 0], 'Tango Pink' => [228, 113, 122], 'Taupe' => [72, 60, 50], 'Taupe Gray' => [139, 133, 137], 'Tea Green' => [208, 240, 192], 'Tea Rose' => [244, 194, 194], 'Teal' => [0, 128, 128], 'Teal Blue' => [54, 117, 136], 'Teal Deer' => [153, 230, 179], 'Teal Green' => [0, 130, 127], 'Telemagenta' => [207, 52, 118], 'Tenné' => [205, 87, 0], 'Terra Cotta' => [226, 114, 91], 'Thistle' => [216, 191, 216], 'Thulian Pink' => [222, 111, 161], 'Tickle Me Pink' => [252, 137, 172], 'Tiffany Blue' => [10, 186, 181], "Tiger's Eye" => [224, 141, 60], 'Timberwolf' => [219, 215, 210], 'Titanium Yellow' => [238, 230, 0], 'Tomato' => [255, 99, 71], 'Toolbox' => [116, 108, 192], 'Topaz' => [255, 200, 124], 'Tractor Red' => [253, 14, 53], 'Trolley Grey' => [128, 128, 128], 'Tropical Rain Forest' => [0, 117, 94], 'Tropical Violet' => [205, 164, 222], 'True Blue' => [0, 115, 207], 'Tufts Blue' => [65, 125, 193], 'Tulip' => [255, 135, 141], 'Tumbleweed' => [222, 170, 136], 'Turkish Rose' => [181, 114, 129], 'Turquoise' => [64, 224, 208], 'Turquoise Blue' => [0, 255, 239], 'Turquoise Green' => [160, 214, 180], 'Tuscan' => [250, 214, 165], 'Tuscan Brown' => [111, 78, 55], 'Tuscan Red' => [124, 72, 72], 'Tuscan Tan' => [166, 123, 91], 'Tuscany' => [192, 153, 153], 'Twilight Lavender' => [138, 73, 107], 'Tyrian Purple' => [102, 2, 60], 'UA Blue' => [0, 51, 170], 'UA Red' => [217, 0, 76], 'Ube' => [136, 120, 195], 'UCLA Blue' => [83, 104, 149], 'UCLA Gold' => [255, 179, 0], 'UFO Green' => [60, 208, 112], 'Ultramarine' => [63, 0, 255], 'Ultramarine Blue' => [65, 102, 245], 'Ultra Pink' => [255, 111, 255], 'Ultra Red' => [252, 108, 133], 'Umber' => [99, 81, 71], 'Unbleached Silk' => [255, 221, 202], 'United Nations Blue' => [91, 146, 229], 'University Of California Gold' => [183, 135, 39], 'Unmellow Yellow' => [255, 255, 102], 'UP Forest Green' => [1, 68, 33], 'UP Maroon' => [123, 17, 19], 'Upsdell Red' => [174, 32, 41], 'Urobilin' => [225, 173, 33], 'USAFA Blue' => [0, 79, 152], 'USC Cardinal' => [153, 0, 0], 'USC Gold' => [255, 204, 0], 'University Of Tennessee Orange' => [247, 127, 0], 'Utah Crimson' => [211, 0, 63], 'Vanilla' => [243, 229, 171], 'Vanilla Ice' => [243, 143, 169], 'Vegas Gold' => [197, 179, 88], 'Venetian Red' => [200, 8, 21], 'Verdigris' => [67, 179, 174], 'Vermilion' => [217, 56, 30], 'Veronica' => [160, 32, 240], 'Very Light Azure' => [116, 187, 251], 'Very Light Blue' => [102, 102, 255], 'Very Light Malachite Green' => [100, 233, 134], 'Very Light Tangelo' => [255, 176, 119], 'Very Pale Orange' => [255, 223, 191], 'Very Pale Yellow' => [255, 255, 191], 'Violet' => [143, 0, 255], 'Violet (Color Wheel)' => [127, 0, 255], 'Violet (RYB)' => [134, 1, 175], 'Violet (Web)' => [238, 130, 238], 'Violet-Blue' => [50, 74, 178], 'Violet-Red' => [247, 83, 148], 'Viridian' => [64, 130, 109], 'Viridian Green' => [0, 150, 152], 'Vista Blue' => [124, 158, 217], 'Vivid Amber' => [204, 153, 0], 'Vivid Auburn' => [146, 39, 36], 'Vivid Burgundy' => [159, 29, 53], 'Vivid Cerise' => [218, 29, 129], 'Vivid Cerulean' => [0, 170, 238], 'Vivid Crimson' => [204, 0, 51], 'Vivid Gamboge' => [255, 153, 0], 'Vivid Lime Green' => [166, 214, 8], 'Vivid Malachite' => [0, 204, 51], 'Vivid Mulberry' => [184, 12, 227], 'Vivid Orange' => [255, 95, 0], 'Vivid Orange Peel' => [255, 160, 0], 'Vivid Orchid' => [204, 0, 255], 'Vivid Raspberry' => [255, 0, 108], 'Vivid Red' => [247, 13, 26], 'Vivid Red-Tangelo' => [223, 97, 36], 'Vivid Sky Blue' => [0, 204, 255], 'Vivid Tangelo' => [240, 116, 39], 'Vivid Tangerine' => [255, 160, 137], 'Vivid Vermilion' => [229, 96, 36], 'Vivid Violet' => [159, 0, 255], 'Vivid Yellow' => [255, 227, 2], 'Volt' => [206, 255, 0], 'Warm Black' => [0, 66, 66], 'Waterspout' => [164, 244, 249], 'Weldon Blue' => [124, 152, 171], 'Wenge' => [100, 84, 82], 'Wheat' => [245, 222, 179], 'White' => [255, 255, 255], 'White Smoke' => [245, 245, 245], 'Wild Blue Yonder' => [162, 173, 208], 'Wild Orchid' => [212, 112, 162], 'Wild Strawberry' => [255, 67, 164], 'Wild Watermelon' => [252, 108, 133], 'Willpower Orange' => [253, 88, 0], 'Windsor Tan' => [167, 85, 2], 'Wine' => [114, 47, 55], 'Wine Dregs' => [103, 49, 71], 'Wisteria' => [201, 160, 220], 'Wood Brown' => [193, 154, 107], 'Xanadu' => [115, 134, 120], 'Yale Blue' => [15, 77, 146], 'Yankees Blue' => [28, 40, 65], 'Yellow' => [255, 255, 0], 'Yellow (Crayola)' => [252, 232, 131], 'Yellow (Munsell)' => [239, 204, 0], 'Yellow (NCS)' => [255, 211, 0], 'Yellow (Pantone)' => [254, 223, 0], 'Yellow (Process)' => [255, 239, 0], 'Yellow (RYB)' => [254, 254, 51], 'Yellow-Green' => [154, 205, 50], 'Yellow Orange' => [255, 174, 66], 'Yellow Rose' => [255, 240, 0], 'Zaffre' => [0, 20, 168], 'Zinnwaldite Brown' => [44, 22, 8], 'Zomp' => [57, 167, 142], ]; public static function nameFromColor(Color $color) { $bestMatch = ''; $bestDifference = 100.0; foreach (static::$colors as $key => $RawOtherColor) { $otherColor = Color::fromRGB($RawOtherColor[0], $RawOtherColor[1], $RawOtherColor[2]); $difference = $color->differenceBetween($otherColor); if ($bestDifference > $difference) { $bestMatch = $key; $bestDifference = $difference; } } return $bestMatch; } }
NiclasHedam/color
src/ColorName.php
PHP
mit
83,557
[ 30522, 1026, 1029, 25718, 3415, 15327, 27969, 27067, 11960, 2213, 1025, 2465, 3609, 18442, 1063, 2270, 10763, 1002, 6087, 1027, 1031, 1005, 5648, 2665, 1005, 1027, 1028, 1031, 18561, 1010, 19871, 1010, 2656, 1033, 1010, 1005, 18440, 1005, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace App\Util; use Illuminate\Support\Facades\DB; class Access { // list all perm // if the returned array is empty then user dont have permission to list the perms public static function listPerm($userid, $appcode) { if (self::can_editPerm($userid, $appcode) == false) return []; $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; return DB::table('user_app') ->join('users', 'user_app.userid', '=', 'users.id') ->where('user_app.appid', $app->id)->get(); } // used to delete user from app // return // -1 acess deny // -3 appid doesn't exist // -4 cannot delte owner // public static function deletePerm($userid, $otherid, $appcode) { // get owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if ($otherid == $app->ownerid) return -4; if (self::can_editPerm($userid, $app->id)) { DB::table('user_app')->where('appid', $app->id)->where('userid', $otherid)->delete(); return 0; } return -1; } // used to add new user to app // or $userid set perm for $otheruserid, // if $can_perm is differ than null, then its value is valid // if $can_struct is differ than null, then its value is valid // if $can_reportis differ than null, then its value is valid // 0 means unset, 1 means set // return 0 if sucecss // -1: access deny // -2 other user not exist in app, must add first // -3 appid doesn't exist // -4 cannot set perm for owner // -5 if user doesn't exist public static function setPerm($userid, $otheruser, $appcode, $can_perm, $can_struct, $can_report) { //check if user existed if (DB::table('users')->where('id', $otheruser)->count() + DB::table('users')->where('id', $userid)->count() != 2) return -5; // get owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if (self::can_editPerm($userid, $appcode)) { $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $otheruser)->first(); if ($perm == null) { if ($app->ownerid == $otheruser) DB::table('user_app')->insert( ['appid' => $app->id, 'userid' => $otheruser, 'can_perm' => 1, 'can_struct' => 1, 'can_report' => 1] ); else DB::table('user_app')->insert( ['appid' => $app->id, 'userid' => $otheruser, 'can_perm' => 0, 'can_struct' => 0, 'can_report' => 1] ); } else { if ($app->ownerid == $otheruser) { return -4; } } $permrecord = []; if ($can_perm != null) $permrecord['can_perm'] = $can_perm; if ($can_struct != null) $permrecord['can_struct'] = $can_struct; if ($can_report != null) $permrecord['can_report'] = $can_report; if (count($permrecord) != 0) { DB::table('user_app')->where('appid', $app->id)->where('userid', $otheruser)->update($permrecord); } return 0; } abort(500, "sdfdf"); return -1; } public static function isBanned($id){ $user = DB::table('users')->where('id',$id)->first(); if($user == null) return true; if(!$user->banned) return false; return true; } public static function can_editPerm($userid, $appcode) { // full access for app owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if(self::isBanned($app->ownerid)) return false; if ($app->ownerid == $userid) return true; $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $userid)->first(); if ($perm == null) return false; if ($perm->can_perm == 1) return true; return false; } public static function can_editStruct($userid, $appcode) { // full access for app owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if(self::isBanned($app->ownerid)) return false; if ($app->ownerid == $userid) return true; $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $userid)->first(); if ($perm == null) return false; if ($perm->can_struct == 1) return true; return false; } public static function can_view($userid, $appcode) { // full access for app owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if(self::isBanned($app->ownerid)) return false; if ($app->ownerid == $userid) return true; $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $userid)->first(); if ($perm == null) return false; return true; } public static function can_editReport($userid, $appcode) { // full access for app owner $app = DB::table('apps')->where('code', $appcode)->first(); if ($app == null) return -3; if(self::isBanned($app->ownerid)) return false; if ($app->ownerid == $userid) return true; $perm = DB::table('user_app')->where('appid', $app->id)->where('userid', $userid)->first(); if ($perm == null) return false; if ($perm->can_report == 1) return true; return false; } }
meotrics/meotrics
dashboard/app/Util/Access.php
PHP
apache-2.0
4,937
[ 30522, 1026, 1029, 25718, 3415, 15327, 10439, 1032, 21183, 4014, 1025, 2224, 5665, 12717, 12556, 1032, 2490, 1032, 28708, 1032, 16962, 1025, 2465, 3229, 1063, 1013, 1013, 2862, 2035, 2566, 2213, 1013, 1013, 2065, 1996, 2513, 9140, 2003, 406...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace Repository; class AccessoRepository extends Repository { public function getTableName() { return 'accesso'; } }
savez/presence-detector
ws/src/Repository/AccessoRepository.php
PHP
gpl-2.0
149
[ 30522, 1026, 1029, 25718, 3415, 15327, 22409, 1025, 2465, 3229, 5686, 6873, 28307, 2100, 8908, 22409, 1063, 2270, 3853, 2131, 10880, 18442, 1006, 1007, 1063, 2709, 1005, 3229, 2080, 1005, 1025, 1065, 1065, 102, 0, 0, 0, 0, 0, 0, 0, 0,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHOR 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. */ 'use strict'; var _ = require('underscore'); var common = require('./common'); var groups = function(groups) { var buf = this.buf; buf.appendUInt32BE(groups.length); _.each(groups, function(group) { common.appendString(buf, group); }); return this; }; exports.encode = function(version) { var ret = common.encode(common.DESCRIBEGROUP_API, version); ret.groups = groups; return ret; };
pelger/Kafkaesque
lib/message/request/describeGroups.js
JavaScript
mit
1,146
[ 30522, 1013, 1008, 1008, 2023, 4007, 2003, 3024, 1036, 1036, 2004, 2003, 1005, 1005, 1998, 2151, 5228, 2030, 13339, 1008, 10943, 3111, 1010, 2164, 1010, 2021, 2025, 3132, 2000, 1010, 1996, 13339, 10943, 3111, 1008, 1997, 6432, 8010, 1998, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/common/bidding.proto package com.google.ads.googleads.v9.common; /** * <pre> * An automated bid strategy that sets your bids to help get as many clicks * as possible within your budget. * </pre> * * Protobuf type {@code google.ads.googleads.v9.common.TargetSpend} */ public final class TargetSpend extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v9.common.TargetSpend) TargetSpendOrBuilder { private static final long serialVersionUID = 0L; // Use TargetSpend.newBuilder() to construct. private TargetSpend(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TargetSpend() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new TargetSpend(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TargetSpend( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 24: { bitField0_ |= 0x00000001; targetSpendMicros_ = input.readInt64(); break; } case 32: { bitField0_ |= 0x00000002; cpcBidCeilingMicros_ = input.readInt64(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.common.TargetSpend.class, com.google.ads.googleads.v9.common.TargetSpend.Builder.class); } private int bitField0_; public static final int TARGET_SPEND_MICROS_FIELD_NUMBER = 3; private long targetSpendMicros_; /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return Whether the targetSpendMicros field is set. */ @java.lang.Override @java.lang.Deprecated public boolean hasTargetSpendMicros() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return The targetSpendMicros. */ @java.lang.Override @java.lang.Deprecated public long getTargetSpendMicros() { return targetSpendMicros_; } public static final int CPC_BID_CEILING_MICROS_FIELD_NUMBER = 4; private long cpcBidCeilingMicros_; /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return Whether the cpcBidCeilingMicros field is set. */ @java.lang.Override public boolean hasCpcBidCeilingMicros() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return The cpcBidCeilingMicros. */ @java.lang.Override public long getCpcBidCeilingMicros() { return cpcBidCeilingMicros_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeInt64(3, targetSpendMicros_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeInt64(4, cpcBidCeilingMicros_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(3, targetSpendMicros_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(4, cpcBidCeilingMicros_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v9.common.TargetSpend)) { return super.equals(obj); } com.google.ads.googleads.v9.common.TargetSpend other = (com.google.ads.googleads.v9.common.TargetSpend) obj; if (hasTargetSpendMicros() != other.hasTargetSpendMicros()) return false; if (hasTargetSpendMicros()) { if (getTargetSpendMicros() != other.getTargetSpendMicros()) return false; } if (hasCpcBidCeilingMicros() != other.hasCpcBidCeilingMicros()) return false; if (hasCpcBidCeilingMicros()) { if (getCpcBidCeilingMicros() != other.getCpcBidCeilingMicros()) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasTargetSpendMicros()) { hash = (37 * hash) + TARGET_SPEND_MICROS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTargetSpendMicros()); } if (hasCpcBidCeilingMicros()) { hash = (37 * hash) + CPC_BID_CEILING_MICROS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getCpcBidCeilingMicros()); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.common.TargetSpend parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v9.common.TargetSpend prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * An automated bid strategy that sets your bids to help get as many clicks * as possible within your budget. * </pre> * * Protobuf type {@code google.ads.googleads.v9.common.TargetSpend} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.common.TargetSpend) com.google.ads.googleads.v9.common.TargetSpendOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.common.TargetSpend.class, com.google.ads.googleads.v9.common.TargetSpend.Builder.class); } // Construct using com.google.ads.googleads.v9.common.TargetSpend.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); targetSpendMicros_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); cpcBidCeilingMicros_ = 0L; bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_descriptor; } @java.lang.Override public com.google.ads.googleads.v9.common.TargetSpend getDefaultInstanceForType() { return com.google.ads.googleads.v9.common.TargetSpend.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v9.common.TargetSpend build() { com.google.ads.googleads.v9.common.TargetSpend result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v9.common.TargetSpend buildPartial() { com.google.ads.googleads.v9.common.TargetSpend result = new com.google.ads.googleads.v9.common.TargetSpend(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.targetSpendMicros_ = targetSpendMicros_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.cpcBidCeilingMicros_ = cpcBidCeilingMicros_; to_bitField0_ |= 0x00000002; } result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v9.common.TargetSpend) { return mergeFrom((com.google.ads.googleads.v9.common.TargetSpend)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v9.common.TargetSpend other) { if (other == com.google.ads.googleads.v9.common.TargetSpend.getDefaultInstance()) return this; if (other.hasTargetSpendMicros()) { setTargetSpendMicros(other.getTargetSpendMicros()); } if (other.hasCpcBidCeilingMicros()) { setCpcBidCeilingMicros(other.getCpcBidCeilingMicros()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v9.common.TargetSpend parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v9.common.TargetSpend) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long targetSpendMicros_ ; /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return Whether the targetSpendMicros field is set. */ @java.lang.Override @java.lang.Deprecated public boolean hasTargetSpendMicros() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return The targetSpendMicros. */ @java.lang.Override @java.lang.Deprecated public long getTargetSpendMicros() { return targetSpendMicros_; } /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @param value The targetSpendMicros to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setTargetSpendMicros(long value) { bitField0_ |= 0x00000001; targetSpendMicros_ = value; onChanged(); return this; } /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return This builder for chaining. */ @java.lang.Deprecated public Builder clearTargetSpendMicros() { bitField0_ = (bitField0_ & ~0x00000001); targetSpendMicros_ = 0L; onChanged(); return this; } private long cpcBidCeilingMicros_ ; /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return Whether the cpcBidCeilingMicros field is set. */ @java.lang.Override public boolean hasCpcBidCeilingMicros() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return The cpcBidCeilingMicros. */ @java.lang.Override public long getCpcBidCeilingMicros() { return cpcBidCeilingMicros_; } /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @param value The cpcBidCeilingMicros to set. * @return This builder for chaining. */ public Builder setCpcBidCeilingMicros(long value) { bitField0_ |= 0x00000002; cpcBidCeilingMicros_ = value; onChanged(); return this; } /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return This builder for chaining. */ public Builder clearCpcBidCeilingMicros() { bitField0_ = (bitField0_ & ~0x00000002); cpcBidCeilingMicros_ = 0L; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.common.TargetSpend) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v9.common.TargetSpend) private static final com.google.ads.googleads.v9.common.TargetSpend DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v9.common.TargetSpend(); } public static com.google.ads.googleads.v9.common.TargetSpend getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TargetSpend> PARSER = new com.google.protobuf.AbstractParser<TargetSpend>() { @java.lang.Override public TargetSpend parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TargetSpend(input, extensionRegistry); } }; public static com.google.protobuf.Parser<TargetSpend> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TargetSpend> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v9.common.TargetSpend getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/common/TargetSpend.java
Java
apache-2.0
25,132
[ 30522, 1013, 1013, 7013, 2011, 1996, 8778, 17698, 21624, 1012, 2079, 2025, 10086, 999, 1013, 1013, 3120, 1024, 8224, 1013, 14997, 1013, 8224, 19303, 1013, 1058, 2683, 1013, 2691, 1013, 17534, 1012, 15053, 7427, 4012, 1012, 8224, 1012, 14997...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<a href="https://www.codewars.com/users/vladkha/"> <img src="https://www.codewars.com/users/vladkha/badges/large" width="50%" height="50" align="right"> </a> Code from my solutions to [Codewars](https://www.codewars.com) katas.
VladKha/CodeWars
README.md
Markdown
gpl-3.0
230
[ 30522, 1026, 1037, 17850, 12879, 1027, 1000, 16770, 1024, 1013, 1013, 7479, 1012, 3642, 9028, 2015, 1012, 4012, 1013, 5198, 1013, 19163, 15256, 1013, 1000, 1028, 1026, 10047, 2290, 5034, 2278, 1027, 1000, 16770, 1024, 1013, 1013, 7479, 1012...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; namespace DMCTS.GrainInterfaces { public interface INodeView<TAction> where TAction : IAction { Guid Id { get; set; } TAction Action { get; set; } bool IsFinished { get; set; } double Score { get; set; } } }
alexandrnikitin/algorithm-sandbox
DistributedMonteCarloTreeSearch.NET/src/DMCTS.GrainInterfaces/INodeView.cs
C#
mit
269
[ 30522, 2478, 2291, 1025, 3415, 15327, 1040, 12458, 3215, 1012, 8982, 18447, 2121, 12172, 2015, 1063, 2270, 8278, 1999, 10244, 8584, 1026, 11937, 7542, 1028, 2073, 11937, 7542, 1024, 24264, 7542, 1063, 26458, 2094, 8909, 1063, 2131, 1025, 22...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...