code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package leafnodes_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/internal/leafnodes" . "github.com/onsi/gomega" "reflect" "runtime" "time" "github.com/onsi/ginkgo/internal/codelocation" Failer "github.com/onsi/ginkgo/internal/failer" "github.com/onsi/ginkgo/types" ) type runnable interface { Run() (outcome types.SpecState, failure types.SpecFailure) CodeLocation() types.CodeLocation } func SynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { var ( outcome types.SpecState failure types.SpecFailure failer *Failer.Failer componentCodeLocation types.CodeLocation innerCodeLocation types.CodeLocation didRun bool ) BeforeEach(func() { failer = Failer.New() componentCodeLocation = codelocation.New(0) innerCodeLocation = codelocation.New(0) didRun = false }) Describe("synchronous functions", func() { Context("when the function passes", func() { BeforeEach(func() { outcome, failure = build(func() { didRun = true }, 0, failer, componentCodeLocation).Run() }) It("should have a succesful outcome", func() { Ω(didRun).Should(BeTrue()) Ω(outcome).Should(Equal(types.SpecStatePassed)) Ω(failure).Should(BeZero()) }) }) Context("when a failure occurs", func() { BeforeEach(func() { outcome, failure = build(func() { didRun = true failer.Fail("bam", innerCodeLocation) panic("should not matter") }, 0, failer, componentCodeLocation).Run() }) It("should return the failure", func() { Ω(didRun).Should(BeTrue()) Ω(outcome).Should(Equal(types.SpecStateFailed)) Ω(failure).Should(Equal(types.SpecFailure{ Message: "bam", Location: innerCodeLocation, ForwardedPanic: nil, ComponentIndex: componentIndex, ComponentType: componentType, ComponentCodeLocation: componentCodeLocation, })) }) }) Context("when a panic occurs", func() { BeforeEach(func() { outcome, failure = build(func() { didRun = true innerCodeLocation = codelocation.New(0) panic("ack!") }, 0, failer, componentCodeLocation).Run() }) It("should return the panic", func() { Ω(didRun).Should(BeTrue()) Ω(outcome).Should(Equal(types.SpecStatePanicked)) innerCodeLocation.LineNumber++ Ω(failure).Should(Equal(types.SpecFailure{ Message: "Test Panicked", Location: innerCodeLocation, ForwardedPanic: "ack!", ComponentIndex: componentIndex, ComponentType: componentType, ComponentCodeLocation: componentCodeLocation, })) }) }) }) } func AsynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { var ( outcome types.SpecState failure types.SpecFailure failer *Failer.Failer componentCodeLocation types.CodeLocation innerCodeLocation types.CodeLocation didRun bool ) BeforeEach(func() { failer = Failer.New() componentCodeLocation = codelocation.New(0) innerCodeLocation = codelocation.New(0) didRun = false }) Describe("asynchronous functions", func() { var timeoutDuration time.Duration BeforeEach(func() { timeoutDuration = time.Duration(1 * float64(time.Second)) }) Context("when running", func() { It("should run the function as a goroutine, and block until it's done", func() { initialNumberOfGoRoutines := runtime.NumGoroutine() numberOfGoRoutines := 0 build(func(done Done) { didRun = true numberOfGoRoutines = runtime.NumGoroutine() close(done) }, timeoutDuration, failer, componentCodeLocation).Run() Ω(didRun).Should(BeTrue()) Ω(numberOfGoRoutines).Should(BeNumerically(">=", initialNumberOfGoRoutines+1)) }) }) Context("when the function passes", func() { BeforeEach(func() { outcome, failure = build(func(done Done) { didRun = true close(done) }, timeoutDuration, failer, componentCodeLocation).Run() }) It("should have a succesful outcome", func() { Ω(didRun).Should(BeTrue()) Ω(outcome).Should(Equal(types.SpecStatePassed)) Ω(failure).Should(BeZero()) }) }) Context("when the function fails", func() { BeforeEach(func() { outcome, failure = build(func(done Done) { didRun = true failer.Fail("bam", innerCodeLocation) time.Sleep(20 * time.Millisecond) panic("doesn't matter") close(done) }, 10*time.Millisecond, failer, componentCodeLocation).Run() }) It("should return the failure", func() { Ω(didRun).Should(BeTrue()) Ω(outcome).Should(Equal(types.SpecStateFailed)) Ω(failure).Should(Equal(types.SpecFailure{ Message: "bam", Location: innerCodeLocation, ForwardedPanic: nil, ComponentIndex: componentIndex, ComponentType: componentType, ComponentCodeLocation: componentCodeLocation, })) }) }) Context("when the function times out", func() { BeforeEach(func() { outcome, failure = build(func(done Done) { didRun = true time.Sleep(20 * time.Millisecond) panic("doesn't matter") close(done) }, 10*time.Millisecond, failer, componentCodeLocation).Run() }) It("should return the timeout", func() { Ω(didRun).Should(BeTrue()) Ω(outcome).Should(Equal(types.SpecStateTimedOut)) Ω(failure).Should(Equal(types.SpecFailure{ Message: "Timed out", Location: componentCodeLocation, ForwardedPanic: nil, ComponentIndex: componentIndex, ComponentType: componentType, ComponentCodeLocation: componentCodeLocation, })) }) }) Context("when the function panics", func() { BeforeEach(func() { outcome, failure = build(func(done Done) { didRun = true innerCodeLocation = codelocation.New(0) panic("ack!") }, 100*time.Millisecond, failer, componentCodeLocation).Run() }) It("should return the panic", func() { Ω(didRun).Should(BeTrue()) Ω(outcome).Should(Equal(types.SpecStatePanicked)) innerCodeLocation.LineNumber++ Ω(failure).Should(Equal(types.SpecFailure{ Message: "Test Panicked", Location: innerCodeLocation, ForwardedPanic: "ack!", ComponentIndex: componentIndex, ComponentType: componentType, ComponentCodeLocation: componentCodeLocation, })) }) }) }) } func InvalidSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType) { var ( failer *Failer.Failer componentCodeLocation types.CodeLocation innerCodeLocation types.CodeLocation ) BeforeEach(func() { failer = Failer.New() componentCodeLocation = codelocation.New(0) innerCodeLocation = codelocation.New(0) }) Describe("invalid functions", func() { Context("when passed something that's not a function", func() { It("should panic", func() { Ω(func() { build("not a function", 0, failer, componentCodeLocation) }).Should(Panic()) }) }) Context("when the function takes the wrong kind of argument", func() { It("should panic", func() { Ω(func() { build(func(oops string) {}, 0, failer, componentCodeLocation) }).Should(Panic()) }) }) Context("when the function takes more than one argument", func() { It("should panic", func() { Ω(func() { build(func(done Done, oops string) {}, 0, failer, componentCodeLocation) }).Should(Panic()) }) }) }) } var _ = Describe("Shared RunnableNode behavior", func() { Describe("It Nodes", func() { build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { return NewItNode("", body, types.FlagTypeFocused, componentCodeLocation, timeout, failer, 3) } SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeIt) }) Describe("Measure Nodes", func() { build := func(body interface{}, _ time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { return NewMeasureNode("", func(Benchmarker) { reflect.ValueOf(body).Call([]reflect.Value{}) }, types.FlagTypeFocused, componentCodeLocation, 10, failer, 3) } SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeMeasure, 3) }) Describe("BeforeEach Nodes", func() { build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { return NewBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) } SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach) }) Describe("AfterEach Nodes", func() { build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { return NewAfterEachNode(body, componentCodeLocation, timeout, failer, 3) } SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach) }) Describe("JustBeforeEach Nodes", func() { build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { return NewJustBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) } SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach) }) })
starkandwayne/cf-cli
Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go
GO
apache-2.0
10,464
// Copyright 2016-2019 Authors of Cilium // // 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 policy import ( "github.com/cilium/cilium/pkg/labels" "github.com/cilium/cilium/pkg/lock" "github.com/cilium/cilium/pkg/logging" "github.com/cilium/cilium/pkg/logging/logfields" ) var ( log = logging.DefaultLogger.WithField(logfields.LogSubsys, "policy") mutex lock.RWMutex // Protects enablePolicy enablePolicy string // Whether policy enforcement is enabled. ) // SetPolicyEnabled sets the policy enablement configuration. Valid values are: // - endpoint.AlwaysEnforce // - endpoint.NeverEnforce // - endpoint.DefaultEnforcement func SetPolicyEnabled(val string) { mutex.Lock() enablePolicy = val mutex.Unlock() } // GetPolicyEnabled returns the policy enablement configuration func GetPolicyEnabled() string { mutex.RLock() val := enablePolicy mutex.RUnlock() return val } // AddOptions are options which can be passed to PolicyAdd type AddOptions struct { // Replace if true indicates that existing rules with identical labels should be replaced Replace bool // ReplaceWithLabels if present indicates that existing rules with the // given LabelArray should be deleted. ReplaceWithLabels labels.LabelArray // Generated should be set as true to signalize a the policy being inserted // was generated by cilium-agent, e.g. dns poller. Generated bool // The source of this policy, one of api, fqdn or k8s Source string }
tgraf/cilium
pkg/policy/config.go
GO
apache-2.0
1,981
package org.wikipedia; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Parcelable; import android.preference.PreferenceManager; import android.telephony.TelephonyManager; import android.text.InputType; import android.text.format.DateUtils; import android.util.Base64; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Toast; import com.squareup.otto.Bus; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.mediawiki.api.json.ApiResult; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.events.WikipediaZeroInterstitialEvent; import org.wikipedia.events.WikipediaZeroStateChangeEvent; import org.wikipedia.settings.PrefKeys; import org.wikipedia.zero.WikipediaZeroTask; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Contains utility methods that Java doesn't have because we can't make code look too good, can we? */ public final class Utils { private static final int MCC_LENGTH = 3; private static final int KB16 = 16 * 1024; /** * Private constructor, so nobody can construct Utils. * * THEIR EVIL PLANS HAVE BEEN THWARTED!!!1 */ private Utils() { } /** * Compares two strings properly, even when one of them is null - without throwing up * * @param str1 The first string * @param str2 Guess? * @return true if they are both equal (even if both are null) */ public static boolean compareStrings(String str1, String str2) { return (str1 == null ? str2 == null : str1.equals(str2)); } /** * Creates an MD5 hash of the provided string & returns its base64 representation * @param s String to hash * @return Base64'd MD5 representation of the string passed in */ public static String md5base64(final String s) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes("utf-8")); byte[] messageDigest = digest.digest(); return Base64.encodeToString(messageDigest, Base64.URL_SAFE | Base64.NO_WRAP); } catch (NoSuchAlgorithmException e) { // This will never happen, yes. throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { // This will never happen, yes. throw new RuntimeException(e); } } /** * Creates an MD5 hash of the provided string and returns its ASCII representation * @param s String to hash * @return ASCII MD5 representation of the string passed in */ public static String md5string(String s) { StringBuilder hexStr = new StringBuilder(); try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes("utf-8")); byte[] messageDigest = digest.digest(); final int maxByteVal = 0xFF; for (byte b : messageDigest) { hexStr.append(Integer.toHexString(maxByteVal & b)); } } catch (NoSuchAlgorithmException e) { // This will never happen, yes. throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { // This will never happen, yes. throw new RuntimeException(e); } return hexStr.toString(); } /** * Deletes a file or directory, with optional recursion. * @param path File or directory to delete. * @param recursive Whether to delete all subdirectories and files. */ public static void delete(File path, boolean recursive) { if (recursive && path.isDirectory()) { String[] children = path.list(); for (String child : children) { delete(new File(path, child), recursive); } } path.delete(); } /** * Formats provided date relative to the current system time * @param date Date to format * @return String representing the relative time difference of the paramter from current time */ public static String formatDateRelative(Date date) { return DateUtils.getRelativeTimeSpanString(date.getTime(), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS, 0).toString(); } /** * Ensures that the calling method is on the main thread. */ public static void ensureMainThread() { if (Looper.getMainLooper().getThread() != Thread.currentThread()) { throw new IllegalStateException("Method must be called from the Main Thread"); } } /** * Attempt to hide the Android Keyboard. * * FIXME: This should not need to exist. * I do not know why Android does not handle this automatically. * * @param activity The current activity */ public static void hideSoftKeyboard(Activity activity) { InputMethodManager keyboard = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); // Not using getCurrentFocus as that sometimes is null, but the keyboard is still up. keyboard.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0); } /** * Attempt to display the Android keyboard. * * FIXME: This should not need to exist. * Android should always show the keyboard at the appropriate time. This method allows you to display the keyboard * when Android fails to do so. * * @param activity The current activity * @param view The currently focused view that will receive the keyboard input */ public static void showSoftKeyboard(Activity activity, View view) { InputMethodManager keyboard = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.showSoftInput(view, InputMethodManager.SHOW_FORCED); } /** * Same as showSoftKeyboard(), but posted to the message queue of the current thread, so that it's executed * after the current block of code is finished. * @param activity The current activity * @param view The currently focused view that will receive the keyboard input */ public static void showSoftKeyboardAsync(final Activity activity, final View view) { view.post(new Runnable() { @Override public void run() { Utils.showSoftKeyboard(activity, view); } }); } public static void setupShowPasswordCheck(final CheckBox check, final EditText edit) { check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { // EditText loses the cursor position when you change the InputType int curPos = edit.getSelectionStart(); if (isChecked) { edit.setInputType(InputType.TYPE_CLASS_TEXT); } else { edit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } edit.setSelection(curPos); } }); } /* Inspect an API response, and fire an event to update the UI for Wikipedia Zero On/Off. * * @param app The application object * @param result An API result to inspect for Wikipedia Zero headers */ public static void processHeadersForZero(final WikipediaApp app, final ApiResult result) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Map<String, List<String>> headers = result.getHeaders(); boolean responseZeroState = headers.containsKey("X-CS"); if (responseZeroState) { String xcs = headers.get("X-CS").get(0); if (!xcs.equals(WikipediaApp.getXcs())) { identifyZeroCarrier(app, xcs); } } else if (WikipediaApp.getWikipediaZeroDisposition()) { WikipediaApp.setXcs(""); WikipediaApp.setCarrierMessage(""); WikipediaApp.setWikipediaZeroDisposition(responseZeroState); app.getBus().post(new WikipediaZeroStateChangeEvent()); } } }); } private static final int MESSAGE_ZERO = 1; public static void identifyZeroCarrier(final WikipediaApp app, final String xcs) { Handler wikipediaZeroHandler = new Handler(new Handler.Callback(){ private WikipediaZeroTask curZeroTask; @Override public boolean handleMessage(Message msg) { WikipediaZeroTask zeroTask = new WikipediaZeroTask(app.getAPIForSite(app.getPrimarySite()), app) { @Override public void onFinish(String message) { Log.d("Wikipedia", "Wikipedia Zero message: " + message); if (message != null) { WikipediaApp.setXcs(xcs); WikipediaApp.setCarrierMessage(message); WikipediaApp.setWikipediaZeroDisposition(true); Bus bus = app.getBus(); bus.post(new WikipediaZeroStateChangeEvent()); curZeroTask = null; } } @Override public void onCatch(Throwable caught) { // oh snap Log.d("Wikipedia", "Wikipedia Zero Eligibility Check Exception Caught"); curZeroTask = null; } }; if (curZeroTask != null) { // if this connection was hung, clean up a bit curZeroTask.cancel(); } curZeroTask = zeroTask; curZeroTask.execute(); return true; } }); wikipediaZeroHandler.removeMessages(MESSAGE_ZERO); Message zeroMessage = Message.obtain(); zeroMessage.what = MESSAGE_ZERO; zeroMessage.obj = "zero_eligible_check"; wikipediaZeroHandler.sendMessage(zeroMessage); } /** * Read the MCC-MNC (mobile operator code) if available and the cellular data connection is the active one. * http://lists.wikimedia.org/pipermail/wikimedia-l/2014-April/071131.html * @param ctx Application context. * @return The MCC-MNC, typically as ###-##, or null if unable to ascertain (e.g., no actively used cellular) */ public static String getMccMnc(Context ctx) { String mccMncNetwork; String mccMncSim; try { ConnectivityManager conn = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED && (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE || networkInfo.getType() == ConnectivityManager.TYPE_WIMAX)) { TelephonyManager t = (TelephonyManager)ctx.getSystemService(WikipediaApp.TELEPHONY_SERVICE); if (t != null && t.getPhoneType() >= 0) { mccMncNetwork = t.getNetworkOperator(); if (mccMncNetwork != null) { mccMncNetwork = mccMncNetwork.substring(0, MCC_LENGTH) + "-" + mccMncNetwork.substring(MCC_LENGTH); } else { mccMncNetwork = "000-00"; } // TelephonyManager documentation refers to MCC-MNC unreliability on CDMA, // and we actually see that network and SIM MCC-MNC don't always agree, // so let's check the SIM, too. Let's not worry if it's CDMA, as the def of CDMA is complex. mccMncSim = t.getSimOperator(); if (mccMncSim != null) { mccMncSim = mccMncSim.substring(0, MCC_LENGTH) + "-" + mccMncSim.substring(MCC_LENGTH); } else { mccMncSim = "000-00"; } return mccMncNetwork + "," + mccMncSim; } } return null; } catch (Throwable t) { // Because, despite best efforts, things can go wrong and we don't want to crash the app: return null; } } /** * Takes a language code (as returned by Android) and returns a wiki code, as used by wikipedia. * * @param langCode Language code (as returned by Android) * @return Wiki code, as used by wikipedia. */ public static String langCodeToWikiLang(String langCode) { // Convert deprecated language codes to modern ones. // See https://developer.android.com/reference/java/util/Locale.html if (langCode.equals("iw")) { return "he"; // Hebrew } else if (langCode.equals("in")) { return "id"; // Indonesian } else if (langCode.equals("ji")) { return "yi"; // Yiddish } return langCode; } /** * List of wiki language codes for which the content is primarily RTL. * * Ensure that this is always sorted alphabetically. */ private static final String[] RTL_LANGS = { "ar", "arc", "arz", "bcc", "bqi", "ckb", "dv", "fa", "glk", "ha", "he", "khw", "ks", "mzn", "pnb", "ps", "sd", "ug", "ur", "yi" }; /** * Returns true if the given wiki language is to be displayed RTL. * * @param lang Wiki code for the language to check for directionality * @return true if it is RTL, false if LTR */ public static boolean isLangRTL(String lang) { return Arrays.binarySearch(RTL_LANGS, lang, null) >= 0; } /** * Setup directionality for both UI and content elements in a webview. * * @param contentLang The Content language to use to set directionality. Wiki Language code. * @param uiLang The UI language to use to set directionality. Java language code. * @param bridge The CommunicationBridge to use to communicate with the WebView */ public static void setupDirectionality(String contentLang, String uiLang, CommunicationBridge bridge) { JSONObject payload = new JSONObject(); try { if (isLangRTL(contentLang)) { payload.put("contentDirection", "rtl"); } else { payload.put("contentDirection", "ltr"); } if (isLangRTL(langCodeToWikiLang(uiLang))) { payload.put("uiDirection", "rtl"); } else { payload.put("uiDirection", "ltr"); } } catch (JSONException e) { throw new RuntimeException(e); } bridge.sendMessage("setDirectionality", payload); } /** * Sets text direction (RTL / LTR) for given view based on given lang. * * Doesn't do anything on pre Android 4.2, since their RTL support is terrible. * * @param view View to set direction of * @param lang Wiki code for the language based on which to set direction */ public static void setTextDirection(View view, String lang) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { view.setTextDirection(Utils.isLangRTL(lang) ? View.TEXT_DIRECTION_RTL : View.TEXT_DIRECTION_LTR); } } /** * Returns db name for given site * * WARNING: HARDCODED TO WORK FOR WIKIPEDIA ONLY * * @param site Site object to get dbname for * @return dbname for given site object */ public static String getDBNameForSite(Site site) { return site.getLanguage() + "wiki"; } public static void handleExternalLink(final Context context, final Uri uri) { if (WikipediaApp.isWikipediaZeroDevmodeOn() && WikipediaApp.getWikipediaZeroDisposition()) { SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context); if (sharedPref.getBoolean(PrefKeys.getZeroInterstitial(), true)) { WikipediaApp.getInstance().getBus().post(new WikipediaZeroInterstitialEvent(uri)); } else { Utils.visitInExternalBrowser(context, uri); } } else { Utils.visitInExternalBrowser(context, uri); } } /** * Open the specified URI in an external browser (even if our app's intent filter * matches the given URI) * * @param context Context of the calling app * @param uri URI to open in an external browser */ public static void visitInExternalBrowser(final Context context, Uri uri) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(uri); List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0); if (!resInfo.isEmpty()) { List<Intent> browserIntents = new ArrayList<Intent>(); for (ResolveInfo resolveInfo : resInfo) { String packageName = resolveInfo.activityInfo.packageName; // remove our apps from the selection! // This ensures that all the variants of the Wiki app (Alpha, Beta, Stable) are never shown if (packageName.startsWith("org.wikipedia")) { continue; } Intent newIntent = new Intent(Intent.ACTION_VIEW); newIntent.setData(uri); newIntent.setPackage(packageName); browserIntents.add(newIntent); } if (browserIntents.size() > 0) { // initialize the chooser intent with one of the browserIntents, and remove that // intent from the list, since the chooser already has it, and we don't need to // add it again in putExtra. (initialize with the last item in the list, to preserve order) Intent chooserIntent = Intent.createChooser(browserIntents.remove(browserIntents.size() - 1), null); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, browserIntents.toArray(new Parcelable[]{})); context.startActivity(chooserIntent); return; } } // This means that there was no way to handle this link. // We will just show a toast now. FIXME: Make this more visible? Toast.makeText(context, R.string.error_can_not_process_link, Toast.LENGTH_LONG).show(); } /** * Utility method to detect whether an Email app is installed, * for conditionally enabling/disabling email links. * @param context Context of the calling app. * @return True if an Email app exists, false otherwise. */ public static boolean mailAppExists(Context context) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SENDTO); intent.setData(Uri.parse("mailto:test@wikimedia.org")); List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0); return resInfo.size() > 0; } /** * Utility method to copy a stream into another stream. * * Uses a 16KB buffer. * * @param in Stream to copy from. * @param out Stream to copy to. * @throws IOException */ public static void copyStreams(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[KB16]; // 16kb buffer int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } /** * Write a JSON object to a file * @param file file to be written * @param jsonObject content of file * @throws IOException when writing failed */ public static void writeToFile(File file, JSONObject jsonObject) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)); try { writer.write(jsonObject.toString()); } finally { writer.close(); } } /** * Reads the contents of this page from storage. * @return Page object with the contents of the page. * @throws IOException * @throws JSONException */ public static JSONObject readJSONFile(File f) throws IOException, JSONException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); try { StringBuilder stringBuilder = new StringBuilder(); String readStr; while ((readStr = reader.readLine()) != null) { stringBuilder.append(readStr); } return new JSONObject(stringBuilder.toString()); } finally { reader.close(); } } /** * Format for formatting/parsing dates to/from the ISO 8601 standard */ private static final String ISO8601_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Parse a date formatted in ISO8601 format. * * @param dateString Date String to parse * @return Parsed Date object. * @throws ParseException */ public static Date parseISO8601(String dateString) throws ParseException { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_FORMAT_STRING, Locale.ROOT); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); date.setTime(sdf.parse(dateString).getTime()); return date; } /** * Format a date to an ISO8601 formatted string. * * @param date Date to format. * @return The given date formatted in ISO8601 format. */ public static String formatISO8601(Date date) { SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_FORMAT_STRING, Locale.ROOT); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(date); } /** * Convert a JSONArray object to a String Array. * * @param array a JSONArray containing only Strings * @return a String[] with all the items in the JSONArray */ public static String[] jsonArrayToStringArray(JSONArray array) { if (array == null) { return null; } String[] stringArray = new String[array.length()]; for (int i = 0; i < array.length(); i++) { stringArray[i] = array.optString(i); } return stringArray; } /** * Resolves a potentially protocol relative URL to a 'full' URL * * @param url Url to check for (and fix) protocol relativeness * @return A fully qualified, protocol specified URL */ public static String resolveProtocolRelativeUrl(String url) { String fullUrl; if (url.startsWith("//")) { // That's a protocol specific link! Make it https! fullUrl = WikipediaApp.getInstance().getNetworkProtocol() + ":" + url; } else { fullUrl = url; } return fullUrl; } /** * Ask user to try connecting again upon (hopefully) recoverable network failure. */ public static void toastFail() { Toast.makeText(WikipediaApp.getInstance(), R.string.error_network_error_try_again, Toast.LENGTH_LONG).show(); } /** * * @param actual The exception object * @param expected The class you're trying to find, usually tossed by ExceptionImpl.class, for example. * @return boolean true if the Throwable type was found in the nested exception change, else false. */ public static boolean throwableContainsSpecificType(Throwable actual, Class expected) { if (actual == null) { return false; } else if (actual.getClass() == expected) { return true; } else { return throwableContainsSpecificType(actual.getCause(), expected); } } /** * Calculates the actual font size for the current device, based on an "sp" measurement. * @param window The window on which the font will be rendered. * @param fontSp Measurement in "sp" units of the font. * @return Actual font size for the given sp amount. */ public static float getFontSizeFromSp(Window window, float fontSp) { final DisplayMetrics metrics = new DisplayMetrics(); window.getWindowManager().getDefaultDisplay().getMetrics(metrics); return fontSp / metrics.scaledDensity; } /** * Resolves the resource ID of a theme-dependent attribute (for example, a color value * that changes based on the selected theme) * @param activity The activity whose theme contains the attribute. * @param id Theme-dependent attribute ID to be resolved. * @return The actual resource ID of the requested theme-dependent attribute. */ public static int getThemedAttributeId(Activity activity, int id) { TypedValue tv = new TypedValue(); activity.getTheme().resolveAttribute(id, tv, true); return tv.resourceId; } /** * Returns the distribution channel for the app from AndroidManifest.xml * @param ctx * @return The channel (the empty string if not defined) */ public static String getChannelDescriptor(Context ctx) { try { ApplicationInfo a = ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA); String channel = a.metaData.getString(PrefKeys.getChannel()); return channel != null ? channel : ""; } catch (Throwable t) { // oops return ""; } } /** * Sets the distribution channel for the app into SharedPreferences * @param ctx */ public static void setChannel(Context ctx) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); String channel = getChannelDescriptor(ctx); prefs.edit().putString(PrefKeys.getChannel(), channel).commit(); } /** * Gets the distribution channel for the app from SharedPreferences * @param ctx */ public static String getChannel(Context ctx) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); String channel = prefs.getString(PrefKeys.getChannel(), null); if (channel != null) { return channel; } else { setChannel(ctx); return getChannel(ctx); } } }
creaITve/apps-android-tbrc-works
wikipedia/src/main/java/org/wikipedia/Utils.java
Java
apache-2.0
28,052
#include <boost/test/unit_test.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <iostream> #include <sstream> #include <3rdparty/zookeeper/ZooKeeper.hpp> #include <3rdparty/zookeeper/ZooKeeperWatcher.hpp> #include <3rdparty/zookeeper/ZooKeeperEvent.hpp> using namespace std; using namespace boost; using namespace boost::lambda; using namespace izenelib::zookeeper; class WorkerSearch : public ZooKeeperEventHandler { public: virtual void onSessionConnected() { } virtual void onNodeCreated(const std::string& path) { cout << "[WorkerSearch] onNodeCreated " << path <<endl; path_ = path; } virtual void onNodeDeleted(const std::string& path) { cout << "[WorkerSearch] onNodeDeleted " << path <<endl; } virtual void onDataChanged(const std::string& path) { cout << "[WorkerSearch] onDataChanged " << path <<endl; path_ = path; } std::string path_; }; class WorkerMining : public ZooKeeperEventHandler { public: virtual void onSessionConnected() { } virtual void onNodeCreated(const std::string& path) { cout << "[WorkerMining] onNodeCreated " << path <<endl; } virtual void onNodeDeleted(const std::string& path) { cout << "[WorkerMining] onNodeDeleted " << path <<endl; } virtual void onDataChanged(const std::string& path) { cout << "[WorkerMining] onDataChanged " << path <<endl; } }; static const std::string gHosts = "localhost:2181"; //"127.16.0.161:2181,127.16.0.162:2181,127.16.0.163:2181"; //#define ENABLE_ZK_TEST BOOST_AUTO_TEST_SUITE( t_zookeeper ) BOOST_AUTO_TEST_CASE( check_zookeeper_service ) { std::cout << "---> Note: start ZooKeeper Service firstly before test." << std::endl; std::cout << " ZooKeeper Service: "<< gHosts << std::endl; } BOOST_AUTO_TEST_CASE( zookeeper_client_basic ) { std::cout << "---> Test ZooKeeper Client basic functions" << std::endl; #ifndef ENABLE_ZK_TEST return; #endif std::string hosts = gHosts; int recvTimeout = 3000; // Zookeeper Client ZooKeeper cli(hosts, recvTimeout); sleep(2); if (!cli.isConnected()) return; // remove all cli.deleteZNode("/SF1", true); // create std::string path = "/SF1"; std::string data = "distributed search"; cli.createZNode(path, data, ZooKeeper::ZNODE_NORMAL); BOOST_CHECK_EQUAL(cli.isZNodeExists(path), true); BOOST_CHECK_EQUAL(cli.createZNode(path, data, ZooKeeper::ZNODE_NORMAL), false); // create ephemeral node if (false) // disable { ZooKeeper tmpCli(hosts, recvTimeout); tmpCli.createZNode("/SF1/ephemeral", "", ZooKeeper::ZNODE_EPHEMERAL); BOOST_CHECK_EQUAL(tmpCli.isZNodeExists("/SF1/ephemeral"), true); } //tmpCli exited... sleep(1); BOOST_CHECK_EQUAL(cli.isZNodeExists("/SF1/ephemeral"), false); // create sequence node cli.createZNode("/SF1/sequence", "", ZooKeeper::ZNODE_SEQUENCE); string s1 = cli.getLastCreatedNodePath(); BOOST_CHECK_EQUAL(cli.isZNodeExists(s1), true); cli.createZNode("/SF1/sequence", "", ZooKeeper::ZNODE_SEQUENCE); string s2 = cli.getLastCreatedNodePath(); BOOST_CHECK_EQUAL(cli.isZNodeExists(s2), true); cli.deleteZNode(s1); cli.deleteZNode(s2); // get std::string data_get; cli.getZNodeData(path, data_get); BOOST_CHECK_EQUAL(data_get, data); // set std::string data2 = "distributed search (sf1-kite)"; BOOST_CHECK_EQUAL(cli.setZNodeData(path, data2), true); cli.getZNodeData(path, data_get); BOOST_CHECK_EQUAL(data_get, data2); // children std::string master = "/SF1/Master"; std::string worker1 = "/SF1/Worker1"; std::string worker2 = "/SF1/Worker2"; BOOST_CHECK_EQUAL(cli.createZNode(master, "this is master node"), true); BOOST_CHECK_EQUAL(cli.createZNode(worker1, "remote worker1"), true); BOOST_CHECK_EQUAL(cli.createZNode(worker2, "remote worker2"), true); std::vector<std::string> children; cli.getZNodeChildren("/SF1", children); BOOST_CHECK_EQUAL(children.size(), 3); BOOST_CHECK_EQUAL(children[0], master); BOOST_CHECK_EQUAL(children[1], worker1); BOOST_CHECK_EQUAL(children[2], worker2); // display //cli.showZKNamespace("/SF1"); } BOOST_AUTO_TEST_CASE( zookeeper_watch ) { std::cout << "---> Test ZooKeeper Watcher" << std::endl; #ifndef ENABLE_ZK_TEST return; #endif // Client std::string hosts = gHosts; int recvTimeout = 2000; ZooKeeper cli(hosts, recvTimeout); sleep(1); if (!cli.isConnected()) return; // set event handlers for watcher WorkerSearch wkSearch; WorkerMining wkMining; cli.registerEventHandler(&wkSearch); cli.registerEventHandler(&wkMining); // 1. get and watch znode for changes std::string path = "/SF1/Master"; std::string data_get; cli.getZNodeData(path, data_get, ZooKeeper::WATCH); BOOST_CHECK_EQUAL(data_get, "this is master node"); // set in former test case cli.setZNodeData(path, "master data changed!"); sleep(1); //ensure watcher notified // master was notified by watcher on znode changed BOOST_CHECK_EQUAL(wkSearch.path_, path); cli.getZNodeData(wkSearch.path_, data_get); BOOST_CHECK_EQUAL(data_get, "master data changed!"); // 2. check exists and watch znode for creation std::string path2 = "/NotExistedNode"; cli.deleteZNode(path2, true); BOOST_CHECK_EQUAL(cli.isZNodeExists(path2, ZooKeeper::WATCH), false); cli.createZNode(path2, "nodata"); sleep(1); //ensure watcher notified // master was notified by watcher on znode created BOOST_CHECK_EQUAL(wkSearch.path_, path2); cli.getZNodeData(wkSearch.path_, data_get); BOOST_CHECK_EQUAL(data_get, "nodata"); // clear test data from zookeeper servers cli.deleteZNode(path2, true); cli.deleteZNode("/SF1", true); } BOOST_AUTO_TEST_SUITE_END()
izenecloud/izenelib
test/3rdparty/zookeeper/t_zookeeper.cpp
C++
apache-2.0
6,019
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { // [START compute_v1_generated_RegionInstanceGroupManagers_ListPerInstanceConfigs_async] using Google.Api.Gax; using Google.Cloud.Compute.V1; using System; using System.Linq; using System.Threading.Tasks; public sealed partial class GeneratedRegionInstanceGroupManagersClientSnippets { /// <summary>Snippet for ListPerInstanceConfigsAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task ListPerInstanceConfigsRequestObjectAsync() { // Create client RegionInstanceGroupManagersClient regionInstanceGroupManagersClient = await RegionInstanceGroupManagersClient.CreateAsync(); // Initialize request argument(s) ListPerInstanceConfigsRegionInstanceGroupManagersRequest request = new ListPerInstanceConfigsRegionInstanceGroupManagersRequest { Region = "", OrderBy = "", Project = "", InstanceGroupManager = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<RegionInstanceGroupManagersListInstanceConfigsResp, PerInstanceConfig> response = regionInstanceGroupManagersClient.ListPerInstanceConfigsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PerInstanceConfig item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((RegionInstanceGroupManagersListInstanceConfigsResp page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PerInstanceConfig item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PerInstanceConfig> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PerInstanceConfig item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END compute_v1_generated_RegionInstanceGroupManagers_ListPerInstanceConfigs_async] }
googleapis/google-cloud-dotnet
apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/RegionInstanceGroupManagersClient.ListPerInstanceConfigsRequestObjectAsyncSnippet.g.cs
C#
apache-2.0
3,764
<?php /* * Copyright 2016 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. */ /** * The "sinks" collection of methods. * Typical usage is: * <code> * $loggingService = new Google_Service_Logging(...); * $sinks = $loggingService->sinks; * </code> */ class Google_Service_Logging_Resource_OrganizationsSinks extends Google_Service_Resource { /** * Creates a sink. (sinks.create) * * @param string $parent Required. The resource in which to create the sink. * Example: `"projects/my-project-id"`. The new sink must be provided in the * request. * @param Google_Service_Logging_LogSink $postBody * @param array $optParams Optional parameters. * * @opt_param bool uniqueWriterIdentity Optional. Whether the sink will have a * dedicated service account returned in the sink's writer_identity. Set this * field to be true to export logs from one project to a different project. This * field is ignored for non-project sinks (e.g. organization sinks) because * those sinks are required to have dedicated service accounts. * @return Google_Service_Logging_LogSink */ public function create($parent, Google_Service_Logging_LogSink $postBody, $optParams = array()) { $params = array('parent' => $parent, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('create', array($params), "Google_Service_Logging_LogSink"); } /** * Deletes a sink. (sinks.delete) * * @param string $sinkName Required. The resource name of the sink to delete, * including the parent resource and the sink identifier. Example: `"projects * /my-project-id/sinks/my-sink-id"`. It is an error if the sink does not * exist. * @param array $optParams Optional parameters. * @return Google_Service_Logging_LoggingEmpty */ public function delete($sinkName, $optParams = array()) { $params = array('sinkName' => $sinkName); $params = array_merge($params, $optParams); return $this->call('delete', array($params), "Google_Service_Logging_LoggingEmpty"); } /** * Gets a sink. (sinks.get) * * @param string $sinkName Required. The resource name of the sink to return. * Example: `"projects/my-project-id/sinks/my-sink-id"`. * @param array $optParams Optional parameters. * @return Google_Service_Logging_LogSink */ public function get($sinkName, $optParams = array()) { $params = array('sinkName' => $sinkName); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_Logging_LogSink"); } /** * Lists sinks. (sinks.listOrganizationsSinks) * * @param string $parent Required. The resource name where this sink was * created. Example: `"projects/my-logging-project"`. * @param array $optParams Optional parameters. * * @opt_param int pageSize Optional. The maximum number of results to return * from this request. Non-positive values are ignored. The presence of * `nextPageToken` in the response indicates that more results might be * available. * @opt_param string pageToken Optional. If present, then retrieve the next * batch of results from the preceding call to this method. `pageToken` must be * the value of `nextPageToken` from the previous response. The values of other * method parameters should be identical to those in the previous call. * @return Google_Service_Logging_ListSinksResponse */ public function listOrganizationsSinks($parent, $optParams = array()) { $params = array('parent' => $parent); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_Logging_ListSinksResponse"); } /** * Updates or creates a sink. (sinks.update) * * @param string $sinkName Required. The resource name of the sink to update, * including the parent resource and the sink identifier. If the sink does not * exist, this method creates the sink. Example: `"projects/my-project-id/sinks * /my-sink-id"`. * @param Google_Service_Logging_LogSink $postBody * @param array $optParams Optional parameters. * * @opt_param bool uniqueWriterIdentity Optional. Whether the sink will have a * dedicated service account returned in the sink's writer_identity. Set this * field to be true to export logs from one project to a different project. This * field is ignored for non-project sinks (e.g. organization sinks) because * those sinks are required to have dedicated service accounts. * @return Google_Service_Logging_LogSink */ public function update($sinkName, Google_Service_Logging_LogSink $postBody, $optParams = array()) { $params = array('sinkName' => $sinkName, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('update', array($params), "Google_Service_Logging_LogSink"); } }
googleapis/discovery-artifact-manager
clients/php/google-api-php-client-services/src/Google/Service/Logging/Resource/OrganizationsSinks.php
PHP
apache-2.0
5,423
/*** Copyright (c) 2008-2012 CommonsWare, LLC 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. Covered in detail in the book _The Busy Coder's Guide to Android Development_ https://commonsware.com/Android */ package com.commonsware.abj.interp; import android.app.Activity; import android.app.IntentService; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.util.Log; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; public class InterpreterService extends IntentService { public static final String SCRIPT="_script"; public static final String BUNDLE="_bundle"; public static final String RESULT="_result"; public static final String BROADCAST_ACTION="com.commonsware.abj.interp.BROADCAST_ACTION"; public static final String BROADCAST_PACKAGE="com.commonsware.abj.interp.BROADCAST_PACKAGE"; public static final String PENDING_RESULT="com.commonsware.abj.interp.PENDING_RESULT"; public static final String RESULT_CODE="com.commonsware.abj.interp.RESULT_CODE"; public static final String ERROR="com.commonsware.abj.interp.ERROR"; public static final String TRACE="com.commonsware.abj.interp.TRACE"; public static final int SUCCESS=1337; public static final int FAILURE=-1; private HashMap<String, I_Interpreter> interpreters=new HashMap<String, I_Interpreter>(); public InterpreterService() { super("InterpreterService"); } @Override protected void onHandleIntent(Intent intent) { String action=intent.getAction(); I_Interpreter interpreter=interpreters.get(action); if (interpreter==null) { try { interpreter=(I_Interpreter)Class.forName(action).newInstance(); interpreters.put(action, interpreter); } catch (Throwable t) { Log.e("InterpreterService", "Error creating interpreter", t); } } if (interpreter==null) { failure(intent, "Could not create interpreter: "+intent.getAction()); } else { try { success(intent, interpreter.executeScript(intent.getBundleExtra(BUNDLE))); } catch (Throwable t) { Log.e("InterpreterService", "Error executing script", t); try { failure(intent, t); } catch (Throwable t2) { Log.e("InterpreterService", "Error returning exception to client", t2); } } } } private void success(Intent intent, Bundle result) { Intent data=new Intent(); data.putExtras(result); data.putExtra(RESULT_CODE, SUCCESS); send(intent, data); } private void failure(Intent intent, String message) { Intent data=new Intent(); data.putExtra(ERROR, message); data.putExtra(RESULT_CODE, FAILURE); send(intent, data); } private void failure(Intent intent, Throwable t) { Intent data=new Intent(); data.putExtra(ERROR, t.getMessage()); data.putExtra(TRACE, getStackTrace(t)); data.putExtra(RESULT_CODE, FAILURE); send(intent, data); } private void send(Intent intent, Intent data) { String broadcast=intent.getStringExtra(BROADCAST_ACTION); if (broadcast==null) { PendingIntent pi=(PendingIntent)intent.getParcelableExtra(PENDING_RESULT); if (pi!=null) { try { pi.send(this, Activity.RESULT_OK, data); } catch (PendingIntent.CanceledException e) { // no-op -- client must be gone } } } else { data.setPackage(intent.getStringExtra(BROADCAST_PACKAGE)); data.setAction(broadcast); sendBroadcast(data); } } private String getStackTrace(Throwable t) { final StringWriter result=new StringWriter(); final PrintWriter printWriter=new PrintWriter(result); t.printStackTrace(printWriter); return(result.toString()); } }
alexsh/cw-omnibus
JVM/InterpreterService/src/com/commonsware/abj/interp/InterpreterService.java
Java
apache-2.0
4,412
package com.pacoapp.paco.os; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.pacoapp.paco.R; import com.pacoapp.paco.UserPreferences; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; public class RingtoneUtil { private static Logger Log = LoggerFactory.getLogger(RingtoneUtil.class); private static final String RINGTONE_TITLE_COLUMN_NAME = "title"; private static final String PACO_BARK_RINGTONE_TITLE = "Paco Bark"; private static final String BARK_RINGTONE_FILENAME = "deepbark_trial.mp3"; public static final String ALTERNATE_RINGTONE_FILENAME = "PBSRingtone_2.mp3"; public static final String ALTERNATE_RINGTONE_TITLE = "Paco Alternate Alert"; public static final String ALTERNATE_RINGTONE_TITLE_V2 = "Paco Alternate Alert Tone"; public static final String ALTERNATE_RINGTONE_TITLE_V2_FULLPATH = "/assets/ringtone/Paco Alternate Alert Tone"; private Context context; private UserPreferences userPreferences; public static final int RINGTONE_REQUESTCODE = 945; public RingtoneUtil(Context context) { super(); this.context = context.getApplicationContext(); } public void XXXinstallPacoBarkRingtone() { userPreferences = new UserPreferences(context); if (userPreferences.hasInstalledPacoBarkRingtone()) { return; } File f = copyRingtoneFromAssetsToSdCard(BARK_RINGTONE_FILENAME); if (f == null) { return; } insertRingtoneFile(f); } public void installPacoBarkRingtone() { UserPreferences userPreferences = new UserPreferences(context); if (!userPreferences.hasInstalledAlternateRingtone()) { installRingtone(userPreferences, ALTERNATE_RINGTONE_FILENAME, ALTERNATE_RINGTONE_TITLE, true); } // only try once userPreferences.setAlternateRingtoneInstalled(); if (!userPreferences.hasInstalledPacoBarkRingtone()) { installRingtone(userPreferences, BARK_RINGTONE_FILENAME, PACO_BARK_RINGTONE_TITLE, false); } // only try once userPreferences.setPacoBarkRingtoneInstalled(); } public void installRingtone(UserPreferences userPreferences, String ringtoneFilename, String ringtoneTitle, boolean altRingtone) { File f = copyRingtoneFromAssetsToSdCard(ringtoneFilename); if (f == null) { return; } ContentValues values = createBarkRingtoneDatabaseEntry(f, ringtoneTitle); Uri uri = MediaStore.Audio.Media.getContentUriForPath(f.getAbsolutePath()); ContentResolver mediaStoreContentProvider = context.getContentResolver(); Cursor existingRingtoneCursor = mediaStoreContentProvider.query(uri, null, null, null, null); // Note: i want to just retrieve MediaStore.MediaColumns.TITLE and to search on the match, but it is returning null for the TITLE value!!! Cursor c = mediaStoreContentProvider.query(uri, null, null, null, null); boolean alreadyInstalled = false; while (c.moveToNext()) { int titleColumnIndex = c.getColumnIndex(RINGTONE_TITLE_COLUMN_NAME); String existingRingtoneTitle = c.getString(titleColumnIndex); if (existingRingtoneTitle.equals(ringtoneTitle)) { alreadyInstalled = true; } } existingRingtoneCursor.close(); if (!alreadyInstalled) { Uri newUri = mediaStoreContentProvider.insert(uri, values); if (newUri != null) { if (!altRingtone) { userPreferences.setRingtoneUri(newUri.toString()); userPreferences.setRingtoneName(ringtoneTitle); } else { userPreferences.setAltRingtoneUri(newUri.toString()); userPreferences.setAltRingtoneName(ALTERNATE_RINGTONE_TITLE); } } } } private File copyRingtoneFromAssetsToSdCard(String ringtoneFilename) { InputStream fis = null; OutputStream fos = null; try { fis = context.getAssets().open(ringtoneFilename); if (fis == null) { return null; } File path = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + context.getPackageName() + "/"); if (!path.exists()) { path.mkdirs(); } File f = new File(path, ringtoneFilename); fos = new FileOutputStream(f); byte[] buf = new byte[1024]; int len; while ((len = fis.read(buf)) > 0) { fos.write(buf, 0, len); } return f; } catch (FileNotFoundException e) { Log.error("Could not create ringtone file on sd card. Error = " + e.getMessage()); } catch (IOException e) { Log.error("Either Could not open ringtone from assets. Or could not write to sd card. Error = " + e.getMessage()); return null; } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { Log.error("could not close sd card file handle. Error = " + e.getMessage()); } } if (fis != null) { try { fis.close(); } catch (IOException e) { Log.error("could not close asset file handle. Error = " + e.getMessage()); } } } return null; } private ContentValues createBarkRingtoneDatabaseEntry(File f, String ringtoneTitle) { ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, f.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, ringtoneTitle); values.put(MediaStore.MediaColumns.SIZE, f.length()); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3"); values.put(MediaStore.Audio.Media.ARTIST, "Paco"); // values.put(MediaStore.Audio.Media.DURATION, ""); This is not needed values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); return values; } /** * From Stackoverflow issue: * http://stackoverflow.com/questions/22184729/sqliteconstraintexception-thrown-when-trying-to-insert * @param filename * @return */ Uri insertRingtoneFile(File filename) { Uri toneUri = MediaStore.Audio.Media.getContentUriForPath(filename.getAbsolutePath()); // SDK 11+ has the Files store, which already indexed... everything // We need the file's URI though, so we'll be forced to query if (Build.VERSION.SDK_INT >= 11) { Uri uri = null; Uri filesUri = MediaStore.Files.getContentUri("external"); String[] projection = {MediaStore.MediaColumns._ID, MediaStore.MediaColumns.TITLE}; String selection = MediaStore.MediaColumns.DATA + " = ?"; String[] args = {filename.getAbsolutePath()}; Cursor c = context.getContentResolver().query(filesUri, projection, selection, args, null); // We expect a single unique record to be returned, since _data is unique if (c.getCount() == 1) { c.moveToFirst(); long rowId = c.getLong(c.getColumnIndex(MediaStore.MediaColumns._ID)); String title = c.getString(c.getColumnIndex(MediaStore.MediaColumns.TITLE)); c.close(); uri = MediaStore.Files.getContentUri("external", rowId); // Since all this stuff was added automatically, it might not have the metadata you want, // like Title, or Artist, or IsRingtone if (!title.equals(PACO_BARK_RINGTONE_TITLE)) { ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.TITLE, PACO_BARK_RINGTONE_TITLE); if (context.getContentResolver().update(toneUri, values, null, null) < 1) { Log.error("could not update ringtome metadata"); } // Apparently this is best practice, although I have no idea what the Media Scanner // does with the new data context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, toneUri)); } } else if (c.getCount() == 0) { // I suppose the MediaScanner hasn't run yet, we'll insert it // ... ommitted } else { throw new UnsupportedOperationException(); // it's expected to be unique! } return uri; } // For the legacy way, I'm assuming that the file we're working with is in a .nomedia // folder, so we are the ones who created it in the MediaStore. If this isn't the case, // consider querying for it and updating the existing record. You should store the URIs // you create in case you need to delete them from the MediaStore, otherwise you're a // litter bug :P else { ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, filename.getAbsolutePath()); values.put(MediaStore.MediaColumns.SIZE, filename.length()); values.put(MediaStore.MediaColumns.DISPLAY_NAME, filename.getName()); values.put(MediaStore.MediaColumns.TITLE, PACO_BARK_RINGTONE_TITLE); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg3"); values.put(MediaStore.Audio.Media.ARTIST, "Paco App"); values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, true); values.put(MediaStore.Audio.Media.IS_MUSIC, false); Uri newToneUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values); userPreferences.setRingtoneUri(newToneUri.toString()); userPreferences.setRingtoneName(PACO_BARK_RINGTONE_TITLE); userPreferences.setPacoBarkRingtoneInstalled(); // Apparently this is best practice, although I have no idea what the Media Scanner // does with the new data context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newToneUri)); return newToneUri; } } public static boolean isOkRingtoneResult(int requestCode, int resultCode) { return requestCode == RINGTONE_REQUESTCODE && resultCode == Activity.RESULT_OK; } public static void updateRingtone(Intent data, final Activity activity) { Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); final UserPreferences userPreferences = new UserPreferences(activity); if (uri != null) { userPreferences.setRingtoneUri(uri.toString()); String name= getNameOfRingtone(activity, uri); userPreferences.setRingtoneName(name); } else { userPreferences.clearRingtone(); } } public static void launchRingtoneChooserFor(final Activity activity) { UserPreferences userPreferences = new UserPreferences(activity); String uri = userPreferences.getRingtoneUri(); Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, R.string.select_signal_tone); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true); if (uri != null) { intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse(uri)); } else { intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); } activity.startActivityForResult(intent, RingtoneUtil.RINGTONE_REQUESTCODE); } public static String getNameOfRingtone(Context context, Uri uri) { Ringtone ringtone = RingtoneManager.getRingtone(context, uri); return ringtone.getTitle(context); } }
hlecuanda/paco
Paco/src/com/pacoapp/paco/os/RingtoneUtil.java
Java
apache-2.0
12,217
#region using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Tabster.Core.Plugins; using Tabster.Utilities; #endregion namespace Tabster.Plugins { public class PluginInstance { private bool _enabled; private List<Type> _types = new List<Type>(); public PluginInstance(Assembly assembly, ITabsterPlugin plugin, FileInfo fileInfo) { Assembly = assembly; Plugin = plugin; FileInfo = fileInfo; } public Assembly Assembly { get; private set; } public ITabsterPlugin Plugin { get; private set; } public FileInfo FileInfo { get; private set; } public Boolean Enabled { get { return _enabled; } set { if (value) { try { Plugin.Activate(); } catch (Exception ex) { Logging.GetLogger().Error(string.Format("Error occured while activating plugin: {0}", FileInfo.FullName), ex); } } else { try { Plugin.Deactivate(); } catch (Exception ex) { Logging.GetLogger().Error(string.Format("Error occured while deactivating plugin: {0}", FileInfo.FullName), ex); } } _enabled = value; } } public IEnumerable<T> GetClassInstances<T>() { var instances = new List<T>(); var cType = typeof (T); _types.Clear(); try { _types = Assembly.GetTypes().Where(x => x.IsPublic && !x.IsAbstract && !x.IsInterface).ToList(); } catch (Exception ex) { Logging.GetLogger().Error(string.Format("Error occured while loading plugin types: {0}", FileInfo.FullName), ex); } foreach (var type in _types) { if (cType.IsAssignableFrom(type)) { try { var instance = (T) Activator.CreateInstance(type); instances.Add(instance); } catch (Exception ex) { Logging.GetLogger().Error(string.Format("Error occured while creating plugin type instance: '{0}' in {1}", type.FullName, FileInfo.FullName), ex); } } } return instances; } public bool Contains(Type type) { return _types.Contains(type); } } }
GetTabster/Tabster
Tabster/Plugins/PluginInstance.cs
C#
apache-2.0
2,948
package com.beecavegames.common.handlers.admin; import java.io.Serializable; import org.joda.time.DateTime; import lombok.AllArgsConstructor; @AllArgsConstructor public class PlayerBackupMetadata implements Serializable { private static final long serialVersionUID = -485633840234547452L; public long beeId; public DateTime timestamp; }
sgmiller/hiveelements
core/src/main/java/common/handlers/admin/PlayerBackupMetadata.java
Java
apache-2.0
349
#ifndef AUTOBOOST_MPL_FOR_EACH_HPP_INCLUDED #define AUTOBOOST_MPL_FOR_EACH_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2008 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <autoboost/mpl/is_sequence.hpp> #include <autoboost/mpl/begin_end.hpp> #include <autoboost/mpl/apply.hpp> #include <autoboost/mpl/bool.hpp> #include <autoboost/mpl/next_prior.hpp> #include <autoboost/mpl/deref.hpp> #include <autoboost/mpl/identity.hpp> #include <autoboost/mpl/assert.hpp> #include <autoboost/mpl/aux_/config/gpu.hpp> #include <autoboost/mpl/aux_/unwrap.hpp> #include <autoboost/type_traits/is_same.hpp> #include <autoboost/utility/value_init.hpp> namespace autoboost { namespace mpl { namespace aux { template< bool done = true > struct for_each_impl { template< typename Iterator , typename LastIterator , typename TransformFunc , typename F > AUTOBOOST_MPL_CFG_GPU_ENABLED static void execute( Iterator* , LastIterator* , TransformFunc* , F ) { } }; template<> struct for_each_impl<false> { template< typename Iterator , typename LastIterator , typename TransformFunc , typename F > AUTOBOOST_MPL_CFG_GPU_ENABLED static void execute( Iterator* , LastIterator* , TransformFunc* , F f ) { typedef typename deref<Iterator>::type item; typedef typename apply1<TransformFunc,item>::type arg; // dwa 2002/9/10 -- make sure not to invoke undefined behavior // when we pass arg. value_initialized<arg> x; aux::unwrap(f, 0)(autoboost::get(x)); typedef typename mpl::next<Iterator>::type iter; for_each_impl<autoboost::is_same<iter,LastIterator>::value> ::execute( static_cast<iter*>(0), static_cast<LastIterator*>(0), static_cast<TransformFunc*>(0), f); } }; } // namespace aux // agurt, 17/mar/02: pointer default parameters are necessary to workaround // MSVC 6.5 function template signature's mangling bug template< typename Sequence , typename TransformOp , typename F > AUTOBOOST_MPL_CFG_GPU_ENABLED inline void for_each(F f, Sequence* = 0, TransformOp* = 0) { AUTOBOOST_MPL_ASSERT(( is_sequence<Sequence> )); typedef typename begin<Sequence>::type first; typedef typename end<Sequence>::type last; aux::for_each_impl< autoboost::is_same<first,last>::value > ::execute(static_cast<first*>(0), static_cast<last*>(0), static_cast<TransformOp*>(0), f); } template< typename Sequence , typename F > AUTOBOOST_MPL_CFG_GPU_ENABLED inline void for_each(F f, Sequence* = 0) { // jfalcou: fully qualifying this call so it doesnt clash with autoboostphoenix::for_each // ons ome compilers -- done on 02/28/2011 autoboost::mpl::for_each<Sequence, identity<> >(f); } }} #endif // AUTOBOOST_MPL_FOR_EACH_HPP_INCLUDED
codemercenary/autowiring
contrib/autoboost/autoboost/mpl/for_each.hpp
C++
apache-2.0
3,170
(function() { function timecode() { return function(seconds) { var seconds = Number.parseFloat(seconds); if (Number.isNaN(seconds)) { return '-:--' }; var wholeSeconds = Math.floor(seconds); var minutes = Math.floor(wholeSeconds / 60); var remainingSeconds = wholeSeconds % 60; var output = minutes + ':'; if (remainingSeconds < 10) { output += '0'; } output += remainingSeconds; return output; }; } angular .module('blocJams') .filter('timecode', timecode); })();
sjcliu/bloc-jams-angular
dist/scripts/filters/timecode.js
JavaScript
apache-2.0
692
module RSpec module Matchers module BuiltIn class OperatorMatcher class << self def registry @registry ||= {} end def register(klass, operator, matcher) registry[klass] ||= {} registry[klass][operator] = matcher end def unregister(klass, operator) registry[klass] && registry[klass].delete(operator) end def get(klass, operator) klass.ancestors.each { |ancestor| matcher = registry[ancestor] && registry[ancestor][operator] return matcher if matcher } nil end end def initialize(actual) @actual = actual end def self.use_custom_matcher_or_delegate(operator) define_method(operator) do |expected| if !has_non_generic_implementation_of?(operator) && matcher = OperatorMatcher.get(@actual.class, operator) @actual.__send__(::RSpec::Matchers.last_should, matcher.new(expected)) else eval_match(@actual, operator, expected) end end negative_operator = operator.sub(/^=/, '!') if negative_operator != operator && respond_to?(negative_operator) define_method(negative_operator) do |expected| opposite_should = ::RSpec::Matchers.last_should == :should ? :should_not : :should raise "RSpec does not support `#{::RSpec::Matchers.last_should} #{negative_operator} expected`. " + "Use `#{opposite_should} #{operator} expected` instead." end end end ['==', '===', '=~', '>', '>=', '<', '<='].each do |operator| use_custom_matcher_or_delegate operator end def fail_with_message(message) RSpec::Expectations.fail_with(message, @expected, @actual) end def description "#{@operator} #{@expected.inspect}" end private if Method.method_defined?(:owner) # 1.8.6 lacks Method#owner :-( def has_non_generic_implementation_of?(op) Expectations.method_handle_for(@actual, op).owner != ::Kernel rescue NameError false end else def has_non_generic_implementation_of?(op) # This is a bit of a hack, but: # # {}.method(:=~).to_s # => "#<Method: Hash(Kernel)#=~>" # # In the absence of Method#owner, this is the best we # can do to see if the method comes from Kernel. !Expectations.method_handle_for(@actual, op).to_s.include?('(Kernel)') rescue NameError false end end def eval_match(actual, operator, expected) ::RSpec::Matchers.last_matcher = self @operator, @expected = operator, expected __delegate_operator(actual, operator, expected) end end class PositiveOperatorMatcher < OperatorMatcher def __delegate_operator(actual, operator, expected) if actual.__send__(operator, expected) true elsif ['==','===', '=~'].include?(operator) fail_with_message("expected: #{expected.inspect}\n got: #{actual.inspect} (using #{operator})") else fail_with_message("expected: #{operator} #{expected.inspect}\n got: #{operator.gsub(/./, ' ')} #{actual.inspect}") end end end class NegativeOperatorMatcher < OperatorMatcher def __delegate_operator(actual, operator, expected) return false unless actual.__send__(operator, expected) return fail_with_message("expected not: #{operator} #{expected.inspect}\n got: #{operator.gsub(/./, ' ')} #{actual.inspect}") end end end end end
sghill/gocd
server/webapp/WEB-INF/rails.new/vendor/bundle/jruby/1.9/gems/rspec-expectations-2.99.2/lib/rspec/matchers/operator_matcher.rb
Ruby
apache-2.0
3,913
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.sql.operator; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition; /** * OR operator. * * @author Luca Garulli * */ public class OQueryOperatorOr extends OQueryOperator { public OQueryOperatorOr() { super("OR", 3, false); } @Override public Object evaluateRecord(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext) { if (iLeft == null) return false; return (Boolean) iLeft || (Boolean) iRight; } @Override public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) { if (iLeft == null || iRight == null) return OIndexReuseType.NO_INDEX; return OIndexReuseType.INDEX_UNION; } @Override public ORID getBeginRidRange(final Object iLeft,final Object iRight) { final ORID leftRange; final ORID rightRange; if(iLeft instanceof OSQLFilterCondition) leftRange = ((OSQLFilterCondition) iLeft).getBeginRidRange(); else leftRange = null; if(iRight instanceof OSQLFilterCondition) rightRange = ((OSQLFilterCondition) iRight).getBeginRidRange(); else rightRange = null; if(leftRange == null || rightRange == null) return null; else return leftRange.compareTo(rightRange) <= 0 ? leftRange : rightRange; } @Override public ORID getEndRidRange(final Object iLeft,final Object iRight) { final ORID leftRange; final ORID rightRange; if(iLeft instanceof OSQLFilterCondition) leftRange = ((OSQLFilterCondition) iLeft).getEndRidRange(); else leftRange = null; if(iRight instanceof OSQLFilterCondition) rightRange = ((OSQLFilterCondition) iRight).getEndRidRange(); else rightRange = null; if(leftRange == null || rightRange == null) return null; else return leftRange.compareTo(rightRange) >= 0 ? leftRange : rightRange; } }
redox/OrientDB
core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorOr.java
Java
apache-2.0
2,880
/* * 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.activemq.artemis.tests.integration.management; import org.apache.activemq.artemis.api.core.management.ActiveMQServerControl; import org.apache.activemq.artemis.api.core.management.Parameter; import org.apache.activemq.artemis.api.core.management.ResourceNames; import java.util.Map; public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTest { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- private static String[] toStringArray(final Object[] res) { String[] names = new String[res.length]; for (int i = 0; i < res.length; i++) { names[i] = res[i].toString(); } return names; } // Constructors -------------------------------------------------- // Public -------------------------------------------------------- // ActiveMQServerControlTest overrides -------------------------- // the core messaging proxy doesn't work when the server is stopped so we cant run these 2 tests @Override public void testScaleDownWithOutConnector() throws Exception { } @Override public void testScaleDownWithConnector() throws Exception { } @Override protected ActiveMQServerControl createManagementControl() throws Exception { return new ActiveMQServerControl() { @Override public void updateDuplicateIdCache(String address, Object[] ids) { } @Override public void scaleDown(String connector) throws Exception { throw new UnsupportedOperationException(); } private final CoreMessagingProxy proxy = new CoreMessagingProxy(addServerLocator(createInVMNonHALocator()), ResourceNames.CORE_SERVER); @Override public boolean isSharedStore() { return (Boolean) proxy.retrieveAttributeValue("sharedStore"); } @Override public boolean closeConnectionsForAddress(final String ipAddress) throws Exception { return (Boolean) proxy.invokeOperation("closeConnectionsForAddress", ipAddress); } @Override public boolean closeConsumerConnectionsForAddress(final String address) throws Exception { return (Boolean) proxy.invokeOperation("closeConsumerConnectionsForAddress", address); } @Override public boolean closeConnectionsForUser(final String userName) throws Exception { return (Boolean) proxy.invokeOperation("closeConnectionsForUser", userName); } @Override public boolean commitPreparedTransaction(final String transactionAsBase64) throws Exception { return (Boolean) proxy.invokeOperation("commitPreparedTransaction", transactionAsBase64); } @Override public void createQueue(final String address, final String name) throws Exception { proxy.invokeOperation("createQueue", address, name); } @Override public void createQueue(final String address, final String name, final String filter, final boolean durable) throws Exception { proxy.invokeOperation("createQueue", address, name, filter, durable); } @Override public void createQueue(final String address, final String name, final boolean durable) throws Exception { proxy.invokeOperation("createQueue", address, name, durable); } @Override public void deployQueue(final String address, final String name, final String filter, final boolean durable) throws Exception { proxy.invokeOperation("deployQueue", address, name, filter, durable); } @Override public void deployQueue(final String address, final String name, final String filterString) throws Exception { proxy.invokeOperation("deployQueue", address, name); } @Override public void destroyQueue(final String name) throws Exception { proxy.invokeOperation("destroyQueue", name); } @Override public void destroyQueue(final String name, final boolean removeConsumers) throws Exception { proxy.invokeOperation("destroyQueue", name, removeConsumers); } @Override public void disableMessageCounters() throws Exception { proxy.invokeOperation("disableMessageCounters"); } @Override public void enableMessageCounters() throws Exception { proxy.invokeOperation("enableMessageCounters"); } @Override public String getBindingsDirectory() { return (String) proxy.retrieveAttributeValue("bindingsDirectory"); } @Override public int getConnectionCount() { return (Integer) proxy.retrieveAttributeValue("connectionCount", Integer.class); } @Override public long getTotalConnectionCount() { return (Long) proxy.retrieveAttributeValue("totalConnectionCount", Long.class); } @Override public long getTotalMessageCount() { return (Long) proxy.retrieveAttributeValue("totalMessageCount", Long.class); } @Override public long getTotalMessagesAdded() { return (Long) proxy.retrieveAttributeValue("totalMessagesAdded", Long.class); } @Override public long getTotalMessagesAcknowledged() { return (Long) proxy.retrieveAttributeValue("totalMessagesAcknowledged", Long.class); } @Override public long getTotalConsumerCount() { return (Long) proxy.retrieveAttributeValue("totalConsumerCount", Long.class); } @Override public long getConnectionTTLOverride() { return (Long) proxy.retrieveAttributeValue("connectionTTLOverride", Long.class); } @Override public Object[] getConnectors() throws Exception { return (Object[]) proxy.retrieveAttributeValue("connectors"); } @Override public String getConnectorsAsJSON() throws Exception { return (String) proxy.retrieveAttributeValue("connectorsAsJSON"); } @Override public String[] getAddressNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("addressNames")); } @Override public String[] getQueueNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("queueNames", String.class)); } @Override public String getUptime() { return null; } @Override public long getUptimeMillis() { return 0; } @Override public boolean isReplicaSync() { return false; } @Override public int getIDCacheSize() { return (Integer) proxy.retrieveAttributeValue("IDCacheSize", Integer.class); } public String[] getInterceptorClassNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("incomingInterceptorClassNames")); } @Override public String[] getIncomingInterceptorClassNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("incomingInterceptorClassNames")); } @Override public String[] getOutgoingInterceptorClassNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("outgoingInterceptorClassNames")); } @Override public String getJournalDirectory() { return (String) proxy.retrieveAttributeValue("journalDirectory"); } @Override public int getJournalFileSize() { return (Integer) proxy.retrieveAttributeValue("journalFileSize", Integer.class); } @Override public int getJournalMaxIO() { return (Integer) proxy.retrieveAttributeValue("journalMaxIO", Integer.class); } @Override public int getJournalMinFiles() { return (Integer) proxy.retrieveAttributeValue("journalMinFiles", Integer.class); } @Override public String getJournalType() { return (String) proxy.retrieveAttributeValue("journalType"); } @Override public String getLargeMessagesDirectory() { return (String) proxy.retrieveAttributeValue("largeMessagesDirectory"); } @Override public String getManagementAddress() { return (String) proxy.retrieveAttributeValue("managementAddress"); } @Override public String getManagementNotificationAddress() { return (String) proxy.retrieveAttributeValue("managementNotificationAddress"); } @Override public int getMessageCounterMaxDayCount() { return (Integer) proxy.retrieveAttributeValue("messageCounterMaxDayCount", Integer.class); } @Override public long getMessageCounterSamplePeriod() { return (Long) proxy.retrieveAttributeValue("messageCounterSamplePeriod", Long.class); } @Override public long getMessageExpiryScanPeriod() { return (Long) proxy.retrieveAttributeValue("messageExpiryScanPeriod", Long.class); } @Override public long getMessageExpiryThreadPriority() { return (Long) proxy.retrieveAttributeValue("messageExpiryThreadPriority", Long.class); } @Override public String getPagingDirectory() { return (String) proxy.retrieveAttributeValue("pagingDirectory"); } @Override public int getScheduledThreadPoolMaxSize() { return (Integer) proxy.retrieveAttributeValue("scheduledThreadPoolMaxSize", Integer.class); } @Override public int getThreadPoolMaxSize() { return (Integer) proxy.retrieveAttributeValue("threadPoolMaxSize", Integer.class); } @Override public long getSecurityInvalidationInterval() { return (Long) proxy.retrieveAttributeValue("securityInvalidationInterval", Long.class); } @Override public long getTransactionTimeout() { return (Long) proxy.retrieveAttributeValue("transactionTimeout", Long.class); } @Override public long getTransactionTimeoutScanPeriod() { return (Long) proxy.retrieveAttributeValue("transactionTimeoutScanPeriod", Long.class); } @Override public String getVersion() { return proxy.retrieveAttributeValue("version").toString(); } @Override public boolean isBackup() { return (Boolean) proxy.retrieveAttributeValue("backup"); } @Override public boolean isClustered() { return (Boolean) proxy.retrieveAttributeValue("clustered"); } @Override public boolean isCreateBindingsDir() { return (Boolean) proxy.retrieveAttributeValue("createBindingsDir"); } @Override public boolean isCreateJournalDir() { return (Boolean) proxy.retrieveAttributeValue("createJournalDir"); } @Override public boolean isJournalSyncNonTransactional() { return (Boolean) proxy.retrieveAttributeValue("journalSyncNonTransactional"); } @Override public boolean isJournalSyncTransactional() { return (Boolean) proxy.retrieveAttributeValue("journalSyncTransactional"); } @Override public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) throws Exception { proxy.invokeOperation("setFailoverOnServerShutdown", failoverOnServerShutdown); } @Override public boolean isFailoverOnServerShutdown() { return (Boolean) proxy.retrieveAttributeValue("failoverOnServerShutdown"); } public void setScaleDown(boolean scaleDown) throws Exception { proxy.invokeOperation("setEnabled", scaleDown); } public boolean isScaleDown() { return (Boolean) proxy.retrieveAttributeValue("scaleDown"); } @Override public boolean isMessageCounterEnabled() { return (Boolean) proxy.retrieveAttributeValue("messageCounterEnabled"); } @Override public boolean isPersistDeliveryCountBeforeDelivery() { return (Boolean) proxy.retrieveAttributeValue("persistDeliveryCountBeforeDelivery"); } @Override public boolean isAsyncConnectionExecutionEnabled() { return (Boolean) proxy.retrieveAttributeValue("asyncConnectionExecutionEnabled"); } @Override public boolean isPersistIDCache() { return (Boolean) proxy.retrieveAttributeValue("persistIDCache"); } @Override public boolean isSecurityEnabled() { return (Boolean) proxy.retrieveAttributeValue("securityEnabled"); } @Override public boolean isStarted() { return (Boolean) proxy.retrieveAttributeValue("started"); } @Override public boolean isWildcardRoutingEnabled() { return (Boolean) proxy.retrieveAttributeValue("wildcardRoutingEnabled"); } @Override public String[] listConnectionIDs() throws Exception { return (String[]) proxy.invokeOperation("listConnectionIDs"); } @Override public String[] listPreparedTransactions() throws Exception { return (String[]) proxy.invokeOperation("listPreparedTransactions"); } @Override public String listPreparedTransactionDetailsAsJSON() throws Exception { return (String) proxy.invokeOperation("listPreparedTransactionDetailsAsJSON"); } @Override public String listPreparedTransactionDetailsAsHTML() throws Exception { return (String) proxy.invokeOperation("listPreparedTransactionDetailsAsHTML"); } @Override public String[] listHeuristicCommittedTransactions() throws Exception { return (String[]) proxy.invokeOperation("listHeuristicCommittedTransactions"); } @Override public String[] listHeuristicRolledBackTransactions() throws Exception { return (String[]) proxy.invokeOperation("listHeuristicRolledBackTransactions"); } @Override public String[] listRemoteAddresses() throws Exception { return (String[]) proxy.invokeOperation("listRemoteAddresses"); } @Override public String[] listRemoteAddresses(final String ipAddress) throws Exception { return (String[]) proxy.invokeOperation("listRemoteAddresses", ipAddress); } @Override public String[] listSessions(final String connectionID) throws Exception { return (String[]) proxy.invokeOperation("listSessions", connectionID); } @Override public void resetAllMessageCounterHistories() throws Exception { proxy.invokeOperation("resetAllMessageCounterHistories"); } @Override public void resetAllMessageCounters() throws Exception { proxy.invokeOperation("resetAllMessageCounters"); } @Override public boolean rollbackPreparedTransaction(final String transactionAsBase64) throws Exception { return (Boolean) proxy.invokeOperation("rollbackPreparedTransaction", transactionAsBase64); } @Override public void sendQueueInfoToQueue(final String queueName, final String address) throws Exception { proxy.invokeOperation("sendQueueInfoToQueue", queueName, address); } @Override public void setMessageCounterMaxDayCount(final int count) throws Exception { proxy.invokeOperation("setMessageCounterMaxDayCount", count); } @Override public void setMessageCounterSamplePeriod(final long newPeriod) throws Exception { proxy.invokeOperation("setMessageCounterSamplePeriod", newPeriod); } @Override public int getJournalBufferSize() { return (Integer) proxy.retrieveAttributeValue("JournalBufferSize", Integer.class); } @Override public int getJournalBufferTimeout() { return (Integer) proxy.retrieveAttributeValue("JournalBufferTimeout", Integer.class); } @Override public int getJournalCompactMinFiles() { return (Integer) proxy.retrieveAttributeValue("JournalCompactMinFiles", Integer.class); } @Override public int getJournalCompactPercentage() { return (Integer) proxy.retrieveAttributeValue("JournalCompactPercentage", Integer.class); } @Override public boolean isPersistenceEnabled() { return (Boolean) proxy.retrieveAttributeValue("PersistenceEnabled"); } @Override public int getDiskScanPeriod() { return (Integer) proxy.retrieveAttributeValue("DiskScanPeriod", Integer.class); } @Override public int getMaxDiskUsage() { return (Integer) proxy.retrieveAttributeValue("MaxDiskUsage", Integer.class); } @Override public long getGlobalMaxSize() { return (Long) proxy.retrieveAttributeValue("GlobalMaxSize", Long.class); } @Override public void addSecuritySettings(String addressMatch, String sendRoles, String consumeRoles, String createDurableQueueRoles, String deleteDurableQueueRoles, String createNonDurableQueueRoles, String deleteNonDurableQueueRoles, String manageRoles) throws Exception { proxy.invokeOperation("addSecuritySettings", addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles); } @Override public void addSecuritySettings(String addressMatch, String sendRoles, String consumeRoles, String createDurableQueueRoles, String deleteDurableQueueRoles, String createNonDurableQueueRoles, String deleteNonDurableQueueRoles, String manageRoles, String browseRoles) throws Exception { proxy.invokeOperation("addSecuritySettings", addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles, browseRoles); } @Override public void removeSecuritySettings(String addressMatch) throws Exception { proxy.invokeOperation("removeSecuritySettings", addressMatch); } @Override public Object[] getRoles(String addressMatch) throws Exception { return (Object[]) proxy.invokeOperation("getRoles", addressMatch); } @Override public String getRolesAsJSON(String addressMatch) throws Exception { return (String) proxy.invokeOperation("getRolesAsJSON", addressMatch); } @Override public void addAddressSettings(@Parameter(desc = "an address match", name = "addressMatch") String addressMatch, @Parameter(desc = "the dead letter address setting", name = "DLA") String DLA, @Parameter(desc = "the expiry address setting", name = "expiryAddress") String expiryAddress, @Parameter(desc = "the expiry delay setting", name = "expiryDelay") long expiryDelay, @Parameter(desc = "are any queues created for this address a last value queue", name = "lastValueQueue") boolean lastValueQueue, @Parameter(desc = "the delivery attempts", name = "deliveryAttempts") int deliveryAttempts, @Parameter(desc = "the max size in bytes", name = "maxSizeBytes") long maxSizeBytes, @Parameter(desc = "the page size in bytes", name = "pageSizeBytes") int pageSizeBytes, @Parameter(desc = "the max number of pages in the soft memory cache", name = "pageMaxCacheSize") int pageMaxCacheSize, @Parameter(desc = "the redelivery delay", name = "redeliveryDelay") long redeliveryDelay, @Parameter(desc = "the redelivery delay multiplier", name = "redeliveryMultiplier") double redeliveryMultiplier, @Parameter(desc = "the maximum redelivery delay", name = "maxRedeliveryDelay") long maxRedeliveryDelay, @Parameter(desc = "the redistribution delay", name = "redistributionDelay") long redistributionDelay, @Parameter(desc = "do we send to the DLA when there is no where to route the message", name = "sendToDLAOnNoRoute") boolean sendToDLAOnNoRoute, @Parameter(desc = "the policy to use when the address is full", name = "addressFullMessagePolicy") String addressFullMessagePolicy, @Parameter(desc = "when a consumer falls below this threshold in terms of messages consumed per second it will be considered 'slow'", name = "slowConsumerThreshold") long slowConsumerThreshold, @Parameter(desc = "how often (in seconds) to check for slow consumers", name = "slowConsumerCheckPeriod") long slowConsumerCheckPeriod, @Parameter(desc = "the policy to use when a slow consumer is detected", name = "slowConsumerPolicy") String slowConsumerPolicy, @Parameter(desc = "allow queues to be created automatically", name = "autoCreateJmsQueues") boolean autoCreateJmsQueues, @Parameter(desc = "allow auto-created queues to be deleted automatically", name = "autoDeleteJmsQueues") boolean autoDeleteJmsQueues, @Parameter(desc = "allow topics to be created automatically", name = "autoCreateJmsTopics") boolean autoCreateJmsTopics, @Parameter(desc = "allow auto-created topics to be deleted automatically", name = "autoDeleteJmsTopics") boolean autoDeleteJmsTopics) throws Exception { proxy.invokeOperation("addAddressSettings", addressMatch, DLA, expiryAddress, expiryDelay, lastValueQueue, deliveryAttempts, maxSizeBytes, pageSizeBytes, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues, autoCreateJmsTopics, autoDeleteJmsTopics); } @Override public void removeAddressSettings(String addressMatch) throws Exception { proxy.invokeOperation("removeAddressSettings", addressMatch); } @Override public void createDivert(String name, String routingName, String address, String forwardingAddress, boolean exclusive, String filterString, String transformerClassName) throws Exception { proxy.invokeOperation("createDivert", name, routingName, address, forwardingAddress, exclusive, filterString, transformerClassName); } @Override public void destroyDivert(String name) throws Exception { proxy.invokeOperation("destroyDivert", name); } @Override public String[] getBridgeNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("bridgeNames")); } @Override public void destroyBridge(String name) throws Exception { proxy.invokeOperation("destroyBridge", name); } @Override public void createConnectorService(String name, String factoryClass, Map<String, Object> parameters) throws Exception { proxy.invokeOperation("createConnectorService", name, factoryClass, parameters); } @Override public void destroyConnectorService(String name) throws Exception { proxy.invokeOperation("destroyConnectorService", name); } @Override public String[] getConnectorServices() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("connectorServices")); } @Override public void forceFailover() throws Exception { proxy.invokeOperation("forceFailover"); } public String getLiveConnectorName() throws Exception { return (String) proxy.retrieveAttributeValue("liveConnectorName"); } @Override public String getAddressSettingsAsJSON(String addressMatch) throws Exception { return (String) proxy.invokeOperation("getAddressSettingsAsJSON", addressMatch); } @Override public String[] getDivertNames() { return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("divertNames")); } @Override public void createBridge(String name, String queueName, String forwardingAddress, String filterString, String transformerClassName, long retryInterval, double retryIntervalMultiplier, int initialConnectAttempts, int reconnectAttempts, boolean useDuplicateDetection, int confirmationWindowSize, int producerWindowSize, long clientFailureCheckPeriod, String connectorNames, boolean useDiscovery, boolean ha, String user, String password) throws Exception { proxy.invokeOperation("createBridge", name, queueName, forwardingAddress, filterString, transformerClassName, retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, producerWindowSize, clientFailureCheckPeriod, connectorNames, useDiscovery, ha, user, password); } @Override public void createBridge(String name, String queueName, String forwardingAddress, String filterString, String transformerClassName, long retryInterval, double retryIntervalMultiplier, int initialConnectAttempts, int reconnectAttempts, boolean useDuplicateDetection, int confirmationWindowSize, long clientFailureCheckPeriod, String connectorNames, boolean useDiscovery, boolean ha, String user, String password) throws Exception { proxy.invokeOperation("createBridge", name, queueName, forwardingAddress, filterString, transformerClassName, retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, clientFailureCheckPeriod, connectorNames, useDiscovery, ha, user, password); } @Override public String listProducersInfoAsJSON() throws Exception { return (String) proxy.invokeOperation("listProducersInfoAsJSON"); } @Override public String listConsumersAsJSON(String connectionID) throws Exception { return (String) proxy.invokeOperation("listConsumersAsJSON", connectionID); } @Override public String listAllConsumersAsJSON() throws Exception { return (String) proxy.invokeOperation("listAllConsumersAsJSON"); } @Override public String listConnectionsAsJSON() throws Exception { return (String) proxy.invokeOperation("listConnectionsAsJSON"); } @Override public String listSessionsAsJSON(@Parameter(desc = "a connection ID", name = "connectionID") String connectionID) throws Exception { return (String) proxy.invokeOperation("listSessionsAsJSON", connectionID); } }; } @Override public boolean usingCore() { return true; } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- }
paulgallagher75/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlUsingCoreTest.java
Java
apache-2.0
32,136
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the directconnect-2012-10-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DirectConnect.Model { /// <summary> /// Container for the parameters to the DeleteInterconnect operation. /// Deletes the specified interconnect. /// </summary> public partial class DeleteInterconnectRequest : AmazonDirectConnectRequest { private string _interconnectId; /// <summary> /// Gets and sets the property InterconnectId. /// </summary> public string InterconnectId { get { return this._interconnectId; } set { this._interconnectId = value; } } // Check to see if InterconnectId property is set internal bool IsSetInterconnectId() { return this._interconnectId != null; } } }
rafd123/aws-sdk-net
sdk/src/Services/DirectConnect/Generated/Model/DeleteInterconnectRequest.cs
C#
apache-2.0
1,636
package org.apache.pdfbox.pdmodel.graphics; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.common.PDStream; /** * A PostScript XObject. * Conforming readers may not be able to interpret the PostScript fragments. * * @author John Hewson */ public class PDPostScriptXObject extends PDXObject { /** * Creates a PostScript XObject. * @param stream The XObject stream */ public PDPostScriptXObject(PDStream stream) { super(stream, COSName.PS); } }
mdamt/PdfBox-Android
library/src/main/java/org/apache/pdfbox/pdmodel/graphics/PDPostScriptXObject.java
Java
apache-2.0
535
# Copyright 2021 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. PYTHON_VERSION_COMPATIBILITY = 'PY2+3' DEPS = [ 'cq', 'properties', 'step', ] def RunSteps(api): api.step('show properties', []) api.step.active_result.presentation.logs['result'] = [ 'mode: %s' % (api.cq.run_mode,), ] def GenTests(api): yield api.test('dry') + api.cq(run_mode=api.cq.DRY_RUN) yield api.test('quick-dry') + api.cq(run_mode=api.cq.QUICK_DRY_RUN) yield api.test('full') + api.cq(run_mode=api.cq.FULL_RUN) yield api.test('legacy-full') + api.properties(**{ '$recipe_engine/cq': {'dry_run': False}, }) yield api.test('legacy-dry') + api.properties(**{ '$recipe_engine/cq': {'dry_run': True}, })
luci/recipes-py
recipe_modules/cq/tests/mode_of_run.py
Python
apache-2.0
825
// Copyright 2016-2017 Authors of Cilium // // 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 addressing import ( "encoding/json" "fmt" "net" ) type CiliumIP interface { IPNet(ones int) *net.IPNet EndpointPrefix() *net.IPNet IP() net.IP String() string IsIPv6() bool GetFamilyString() string IsSet() bool } type CiliumIPv6 []byte // NewCiliumIPv6 returns a IPv6 if the given `address` is an IPv6 address. func NewCiliumIPv6(address string) (CiliumIPv6, error) { ip, _, err := net.ParseCIDR(address) if err != nil { ip = net.ParseIP(address) if ip == nil { return nil, fmt.Errorf("Invalid IPv6 address: %s", address) } } // As result of ParseIP, ip is either a valid IPv6 or IPv4 address. net.IP // represents both versions on 16 bytes, so a more reliable way to tell // IPv4 and IPv6 apart is to see if it fits 4 bytes ip4 := ip.To4() if ip4 != nil { return nil, fmt.Errorf("Not an IPv6 address: %s", address) } return DeriveCiliumIPv6(ip.To16()), nil } func DeriveCiliumIPv6(src net.IP) CiliumIPv6 { ip := make(CiliumIPv6, 16) copy(ip, src.To16()) return ip } // IsSet returns true if the IP is set func (ip CiliumIPv6) IsSet() bool { return ip.String() != "" } func (ip CiliumIPv6) IsIPv6() bool { return true } func (ip CiliumIPv6) IPNet(ones int) *net.IPNet { return &net.IPNet{ IP: ip.IP(), Mask: net.CIDRMask(ones, 128), } } func (ip CiliumIPv6) EndpointPrefix() *net.IPNet { return ip.IPNet(128) } func (ip CiliumIPv6) IP() net.IP { return net.IP(ip) } func (ip CiliumIPv6) String() string { if ip == nil { return "" } return net.IP(ip).String() } func (ip CiliumIPv6) MarshalJSON() ([]byte, error) { return json.Marshal(net.IP(ip)) } func (ip *CiliumIPv6) UnmarshalJSON(b []byte) error { if len(b) < len(`""`) { return fmt.Errorf("Invalid CiliumIPv6 '%s'", string(b)) } str := string(b[1 : len(b)-1]) if str == "" { return nil } c, err := NewCiliumIPv6(str) if err != nil { return fmt.Errorf("Invalid CiliumIPv6 '%s': %s", str, err) } *ip = c return nil } type CiliumIPv4 []byte func NewCiliumIPv4(address string) (CiliumIPv4, error) { ip, _, err := net.ParseCIDR(address) if err != nil { ip = net.ParseIP(address) if ip == nil { return nil, fmt.Errorf("Invalid IPv4 address: %s", address) } } ip4 := ip.To4() if ip4 == nil { return nil, fmt.Errorf("Not an IPv4 address") } return DeriveCiliumIPv4(ip4), nil } func DeriveCiliumIPv4(src net.IP) CiliumIPv4 { ip := make(CiliumIPv4, 4) copy(ip, src.To4()) return ip } // IsSet returns true if the IP is set func (ip CiliumIPv4) IsSet() bool { return ip.String() != "" } func (ip CiliumIPv4) IsIPv6() bool { return false } func (ip CiliumIPv4) IPNet(ones int) *net.IPNet { return &net.IPNet{ IP: net.IP(ip), Mask: net.CIDRMask(ones, 32), } } func (ip CiliumIPv4) EndpointPrefix() *net.IPNet { return ip.IPNet(32) } func (ip CiliumIPv4) IP() net.IP { return net.IP(ip) } func (ip CiliumIPv4) String() string { if ip == nil { return "" } return net.IP(ip).String() } func (ip CiliumIPv4) MarshalJSON() ([]byte, error) { return json.Marshal(net.IP(ip)) } func (ip *CiliumIPv4) UnmarshalJSON(b []byte) error { if len(b) < len(`""`) { return fmt.Errorf("Invalid CiliumIPv4 '%s'", string(b)) } str := string(b[1 : len(b)-1]) if str == "" { return nil } c, err := NewCiliumIPv4(str) if err != nil { return fmt.Errorf("Invalid CiliumIPv4 '%s': %s", str, err) } *ip = c return nil } // GetFamilyString returns the address family of ip as a string. func (ip CiliumIPv4) GetFamilyString() string { return "IPv4" } // GetFamilyString returns the address family of ip as a string. func (ip CiliumIPv6) GetFamilyString() string { return "IPv6" }
tgraf/cilium
pkg/addressing/ip.go
GO
apache-2.0
4,261
/* * Copyright 2008 biaoping.yin * * 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.frameworkset.spi.assemble; import org.frameworkset.spi.assemble.BeanAccembleHelper.LoopObject; /** * * * <p>Title: Context.java</p> * * <p>Description: * This context is used to defend loopioc. * 依赖注入的上下文信息, * 如果注入类与被注入类之间存在循环注入的情况,则系统自动报错,是否存在循环注入 * 是通过上下文信息来判断的 * * * * * </p> * * <p>Copyright: Copyright (c) 2007</p> * * <p>bboss workgroup</p> * @Date Aug 14, 2008 4:37:33 PM * @author biaoping.yin,尹标平 * @version 1.0 */ public class Context { Context parent; String refid; /** * 保存应用的 */ private Object currentObj; boolean isroot = false; public Context(String refid) { isroot = true; this.refid = refid; } public Context(Context parent,String refid) { this.parent = parent; this.refid = refid; } public boolean isLoopIOC(String refid_,LoopObject lo) { if(refid_.equals(this.refid)) { lo.setObj(currentObj); return true; } if(this.isroot) { return false; } else if(parent != null) { return parent.isLoopIOC(refid_,lo); } return false; } public String toString() { StringBuilder ret = new StringBuilder(); if(this.isroot) { ret.append(refid); } else { ret.append(parent) .append(">") .append(refid); } return ret.toString(); } public Object getCurrentObj() { return currentObj; } public Object setCurrentObj(Object currentObj) { this.currentObj = currentObj; return currentObj; } }
bbossgroups/bbossgroups-3.5
bboss-core/src/org/frameworkset/spi/assemble/Context.java
Java
apache-2.0
2,300
// Copyright 2017 Monax Industries Limited // // 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 vm import ( "fmt" "github.com/hyperledger/burrow/common/math/integral" "github.com/hyperledger/burrow/common/sanity" . "github.com/hyperledger/burrow/word256" ) // Not goroutine safe type Stack struct { data []Word256 ptr int gas *int64 err *error } func NewStack(capacity int, gas *int64, err *error) *Stack { return &Stack{ data: make([]Word256, capacity), ptr: 0, gas: gas, err: err, } } func (st *Stack) useGas(gasToUse int64) { if *st.gas > gasToUse { *st.gas -= gasToUse } else { st.setErr(ErrInsufficientGas) } } func (st *Stack) setErr(err error) { if *st.err == nil { *st.err = err } } func (st *Stack) Push(d Word256) { st.useGas(GasStackOp) if st.ptr == cap(st.data) { st.setErr(ErrDataStackOverflow) return } st.data[st.ptr] = d st.ptr++ } // currently only called after Sha3 func (st *Stack) PushBytes(bz []byte) { if len(bz) != 32 { sanity.PanicSanity("Invalid bytes size: expected 32") } st.Push(LeftPadWord256(bz)) } func (st *Stack) Push64(i int64) { st.Push(Int64ToWord256(i)) } func (st *Stack) Pop() Word256 { st.useGas(GasStackOp) if st.ptr == 0 { st.setErr(ErrDataStackUnderflow) return Zero256 } st.ptr-- return st.data[st.ptr] } func (st *Stack) PopBytes() []byte { return st.Pop().Bytes() } func (st *Stack) Pop64() int64 { d := st.Pop() return Int64FromWord256(d) } func (st *Stack) Len() int { return st.ptr } func (st *Stack) Swap(n int) { st.useGas(GasStackOp) if st.ptr < n { st.setErr(ErrDataStackUnderflow) return } st.data[st.ptr-n], st.data[st.ptr-1] = st.data[st.ptr-1], st.data[st.ptr-n] return } func (st *Stack) Dup(n int) { st.useGas(GasStackOp) if st.ptr < n { st.setErr(ErrDataStackUnderflow) return } st.Push(st.data[st.ptr-n]) return } // Not an opcode, costs no gas. func (st *Stack) Peek() Word256 { if st.ptr == 0 { st.setErr(ErrDataStackUnderflow) return Zero256 } return st.data[st.ptr-1] } func (st *Stack) Print(n int) { fmt.Println("### stack ###") if st.ptr > 0 { nn := integral.MinInt(n, st.ptr) for j, i := 0, st.ptr-1; i > st.ptr-1-nn; i-- { fmt.Printf("%-3d %X\n", j, st.data[i]) j += 1 } } else { fmt.Println("-- empty --") } fmt.Println("#############") }
benjaminbollen/eris-db
manager/burrow-mint/evm/stack.go
GO
apache-2.0
2,847
/* * 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.isis.viewer.wicket.ui.errors; import java.util.Iterator; import java.util.List; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.apache.isis.applib.NonRecoverableException; import org.apache.isis.applib.services.error.ErrorReportingService; import org.apache.isis.applib.services.error.Ticket; import org.apache.isis.core.metamodel.spec.feature.ObjectMember; import org.apache.isis.viewer.wicket.model.models.ModelAbstract; public class ExceptionModel extends ModelAbstract<List<StackTraceDetail>> { private static final long serialVersionUID = 1L; private static final String MAIN_MESSAGE_IF_NOT_RECOGNIZED = "Sorry, an unexpected error occurred."; private List<StackTraceDetail> stackTraceDetailList; private List<List<StackTraceDetail>> stackTraceDetailLists; private boolean recognized; private boolean authorizationCause; private final String mainMessage; public static ExceptionModel create(String recognizedMessageIfAny, Exception ex) { return new ExceptionModel(recognizedMessageIfAny, ex); } /** * Three cases: authorization exception, else recognized, else or not recognized. * @param recognizedMessageIfAny * @param ex */ private ExceptionModel(String recognizedMessageIfAny, Exception ex) { final ObjectMember.AuthorizationException authorizationException = causalChainOf(ex, ObjectMember.AuthorizationException.class); if(authorizationException != null) { this.authorizationCause = true; this.mainMessage = authorizationException.getMessage(); } else { this.authorizationCause = false; if(recognizedMessageIfAny != null) { this.recognized = true; this.mainMessage = recognizedMessageIfAny; } else { this.recognized =false; // see if we can find a NonRecoverableException in the stack trace Iterable<NonRecoverableException> appEx = Iterables.filter(Throwables.getCausalChain(ex), NonRecoverableException.class); Iterator<NonRecoverableException> iterator = appEx.iterator(); NonRecoverableException nonRecoverableException = iterator.hasNext() ? iterator.next() : null; this.mainMessage = nonRecoverableException != null? nonRecoverableException.getMessage() : MAIN_MESSAGE_IF_NOT_RECOGNIZED; } } stackTraceDetailList = asStackTrace(ex); stackTraceDetailLists = asStackTraces(ex); } @Override protected List<StackTraceDetail> load() { return stackTraceDetailList; } private static <T extends Exception> T causalChainOf(Exception ex, Class<T> exType) { final List<Throwable> causalChain = Throwables.getCausalChain(ex); for (Throwable cause : causalChain) { if(exType.isAssignableFrom(cause.getClass())) { return (T)cause; } } return null; } @Override public void setObject(List<StackTraceDetail> stackTraceDetail) { if(stackTraceDetail == null) { return; } this.stackTraceDetailList = stackTraceDetail; } private Ticket ticket; public Ticket getTicket() { return ticket; } /** * Optionally called if an {@link ErrorReportingService} has been configured and returns a <tt>non-null</tt> ticket * to represent the fact that the error has been recorded. */ public void setTicket(final Ticket ticket) { this.ticket = ticket; } public boolean isRecognized() { return recognized; } public String getMainMessage() { return mainMessage; } /** * Whether this was an authorization exception (so UI can suppress information, eg stack trace). */ public boolean isAuthorizationException() { return authorizationCause; } public List<StackTraceDetail> getStackTrace() { return stackTraceDetailList; } public List<List<StackTraceDetail>> getStackTraces() { return stackTraceDetailLists; } private static List<StackTraceDetail> asStackTrace(Throwable ex) { List<StackTraceDetail> stackTrace = Lists.newArrayList(); List<Throwable> causalChain = Throwables.getCausalChain(ex); boolean firstTime = true; for(Throwable cause: causalChain) { if(!firstTime) { stackTrace.add(StackTraceDetail.spacer()); stackTrace.add(StackTraceDetail.causedBy()); stackTrace.add(StackTraceDetail.spacer()); } else { firstTime = false; } append(cause, stackTrace); } return stackTrace; } private static List<List<StackTraceDetail>> asStackTraces(Throwable ex) { List<List<StackTraceDetail>> stackTraces = Lists.newArrayList(); List<Throwable> causalChain = Throwables.getCausalChain(ex); boolean firstTime = true; for(Throwable cause: causalChain) { List<StackTraceDetail> stackTrace = Lists.newArrayList(); append(cause, stackTrace); stackTraces.add(stackTrace); } return stackTraces; } private static void append(final Throwable cause, final List<StackTraceDetail> stackTrace) { stackTrace.add(StackTraceDetail.exceptionClassName(cause)); stackTrace.add(StackTraceDetail.exceptionMessage(cause)); for (StackTraceElement el : cause.getStackTrace()) { stackTrace.add(StackTraceDetail.element(el)); } } }
incodehq/isis
core/viewer-wicket-ui/src/main/java/org/apache/isis/viewer/wicket/ui/errors/ExceptionModel.java
Java
apache-2.0
6,578
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet(VerbsData.Update, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "Snapshot", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSSnapshot))] public partial class UpdateAzureRmSnapshot : ComputeAutomationBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { if (ShouldProcess(this.SnapshotName, VerbsData.Update)) { string resourceGroupName = this.ResourceGroupName; string snapshotName = this.SnapshotName; SnapshotUpdate snapshotupdate = new SnapshotUpdate(); ComputeAutomationAutoMapperProfile.Mapper.Map<PSSnapshotUpdate, SnapshotUpdate>(this.SnapshotUpdate, snapshotupdate); Snapshot snapshot = new Snapshot(); ComputeAutomationAutoMapperProfile.Mapper.Map<PSSnapshot, Snapshot>(this.Snapshot, snapshot); var result = (this.SnapshotUpdate == null) ? SnapshotsClient.CreateOrUpdate(resourceGroupName, snapshotName, snapshot) : SnapshotsClient.Update(resourceGroupName, snapshotName, snapshotupdate); var psObject = new PSSnapshot(); ComputeAutomationAutoMapperProfile.Mapper.Map<Snapshot, PSSnapshot>(result, psObject); WriteObject(psObject); } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] [Parameter( ParameterSetName = "FriendMethod", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] [ResourceGroupCompleter] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true)] [Parameter( ParameterSetName = "FriendMethod", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true)] [ResourceNameCompleter("Microsoft.Compute/snapshots", "ResourceGroupName")] [Alias("Name")] public string SnapshotName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 3, Mandatory = true, ValueFromPipeline = true)] public PSSnapshotUpdate SnapshotUpdate { get; set; } [Parameter( ParameterSetName = "FriendMethod", Position = 4, Mandatory = true, ValueFromPipelineByPropertyName = false, ValueFromPipeline = true)] [AllowNull] public PSSnapshot Snapshot { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } } }
AzureAutomationTeam/azure-powershell
src/ResourceManager/Compute/Commands.Compute/Generated/Snapshot/SnapshotUpdateMethod.cs
C#
apache-2.0
4,375
import { get } from 'lodash'; class WizardHelper { constructor() {} isScheduleModeEvery(scheduleString) { return !!scheduleString.match(/every\s(\d+)\s(seconds|minutes|hours|days|months|years)/); } isWizardWatcher(watcher) { return get(watcher, 'wizard.chart_query_params'); } getUniqueTagId(name, uuid) { return name + '_' + uuid.replace(/-/g, ''); } } export default WizardHelper;
elasticfence/kaae
public/pages/watcher_wizard/services/wizard_helper/wizard_helper.js
JavaScript
apache-2.0
414
from django.conf import settings from django.utils.module_loading import import_string from .tracing import DjangoTracing from .tracing import initialize_global_tracer try: # Django >= 1.10 from django.utils.deprecation import MiddlewareMixin except ImportError: # Not required for Django <= 1.9, see: # https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware MiddlewareMixin = object class OpenTracingMiddleware(MiddlewareMixin): ''' __init__() is only called once, no arguments, when the Web server responds to the first request ''' def __init__(self, get_response=None): ''' TODO: ANSWER Qs - Is it better to place all tracing info in the settings file, or to require a tracing.py file with configurations? - Also, better to have try/catch with empty tracer or just fail fast if there's no tracer specified ''' self._init_tracing() self._tracing = settings.OPENTRACING_TRACING self.get_response = get_response def _init_tracing(self): if getattr(settings, 'OPENTRACING_TRACER', None) is not None: # Backwards compatibility. tracing = settings.OPENTRACING_TRACER elif getattr(settings, 'OPENTRACING_TRACING', None) is not None: tracing = settings.OPENTRACING_TRACING elif getattr(settings, 'OPENTRACING_TRACER_CALLABLE', None) is not None: tracer_callable = settings.OPENTRACING_TRACER_CALLABLE tracer_parameters = getattr(settings, 'OPENTRACING_TRACER_PARAMETERS', {}) if not callable(tracer_callable): tracer_callable = import_string(tracer_callable) tracer = tracer_callable(**tracer_parameters) tracing = DjangoTracing(tracer) else: # Rely on the global Tracer. tracing = DjangoTracing() # trace_all defaults to True when used as middleware. tracing._trace_all = getattr(settings, 'OPENTRACING_TRACE_ALL', True) # set the start_span_cb hook, if any. tracing._start_span_cb = getattr(settings, 'OPENTRACING_START_SPAN_CB', None) # Normalize the tracing field in settings, including the old field. settings.OPENTRACING_TRACING = tracing settings.OPENTRACING_TRACER = tracing # Potentially set the global Tracer (unless we rely on it already). if getattr(settings, 'OPENTRACING_SET_GLOBAL_TRACER', False): initialize_global_tracer(tracing) def process_view(self, request, view_func, view_args, view_kwargs): # determine whether this middleware should be applied # NOTE: if tracing is on but not tracing all requests, then the tracing # occurs through decorator functions rather than middleware if not self._tracing._trace_all: return None if hasattr(settings, 'OPENTRACING_TRACED_ATTRIBUTES'): traced_attributes = getattr(settings, 'OPENTRACING_TRACED_ATTRIBUTES') else: traced_attributes = [] self._tracing._apply_tracing(request, view_func, traced_attributes) def process_exception(self, request, exception): self._tracing._finish_tracing(request, error=exception) def process_response(self, request, response): self._tracing._finish_tracing(request, response=response) return response
kawamon/hue
desktop/core/ext-py/django_opentracing-1.1.0/django_opentracing/middleware.py
Python
apache-2.0
3,646
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/appstream/model/CreateFleetRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::AppStream::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateFleetRequest::CreateFleetRequest() : m_nameHasBeenSet(false), m_imageNameHasBeenSet(false), m_imageArnHasBeenSet(false), m_instanceTypeHasBeenSet(false), m_fleetType(FleetType::NOT_SET), m_fleetTypeHasBeenSet(false), m_computeCapacityHasBeenSet(false), m_vpcConfigHasBeenSet(false), m_maxUserDurationInSeconds(0), m_maxUserDurationInSecondsHasBeenSet(false), m_disconnectTimeoutInSeconds(0), m_disconnectTimeoutInSecondsHasBeenSet(false), m_descriptionHasBeenSet(false), m_displayNameHasBeenSet(false), m_enableDefaultInternetAccess(false), m_enableDefaultInternetAccessHasBeenSet(false), m_domainJoinInfoHasBeenSet(false), m_tagsHasBeenSet(false), m_idleDisconnectTimeoutInSeconds(0), m_idleDisconnectTimeoutInSecondsHasBeenSet(false), m_iamRoleArnHasBeenSet(false), m_streamView(StreamView::NOT_SET), m_streamViewHasBeenSet(false) { } Aws::String CreateFleetRequest::SerializePayload() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_imageNameHasBeenSet) { payload.WithString("ImageName", m_imageName); } if(m_imageArnHasBeenSet) { payload.WithString("ImageArn", m_imageArn); } if(m_instanceTypeHasBeenSet) { payload.WithString("InstanceType", m_instanceType); } if(m_fleetTypeHasBeenSet) { payload.WithString("FleetType", FleetTypeMapper::GetNameForFleetType(m_fleetType)); } if(m_computeCapacityHasBeenSet) { payload.WithObject("ComputeCapacity", m_computeCapacity.Jsonize()); } if(m_vpcConfigHasBeenSet) { payload.WithObject("VpcConfig", m_vpcConfig.Jsonize()); } if(m_maxUserDurationInSecondsHasBeenSet) { payload.WithInteger("MaxUserDurationInSeconds", m_maxUserDurationInSeconds); } if(m_disconnectTimeoutInSecondsHasBeenSet) { payload.WithInteger("DisconnectTimeoutInSeconds", m_disconnectTimeoutInSeconds); } if(m_descriptionHasBeenSet) { payload.WithString("Description", m_description); } if(m_displayNameHasBeenSet) { payload.WithString("DisplayName", m_displayName); } if(m_enableDefaultInternetAccessHasBeenSet) { payload.WithBool("EnableDefaultInternetAccess", m_enableDefaultInternetAccess); } if(m_domainJoinInfoHasBeenSet) { payload.WithObject("DomainJoinInfo", m_domainJoinInfo.Jsonize()); } if(m_tagsHasBeenSet) { JsonValue tagsJsonMap; for(auto& tagsItem : m_tags) { tagsJsonMap.WithString(tagsItem.first, tagsItem.second); } payload.WithObject("Tags", std::move(tagsJsonMap)); } if(m_idleDisconnectTimeoutInSecondsHasBeenSet) { payload.WithInteger("IdleDisconnectTimeoutInSeconds", m_idleDisconnectTimeoutInSeconds); } if(m_iamRoleArnHasBeenSet) { payload.WithString("IamRoleArn", m_iamRoleArn); } if(m_streamViewHasBeenSet) { payload.WithString("StreamView", StreamViewMapper::GetNameForStreamView(m_streamView)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection CreateFleetRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "PhotonAdminProxyService.CreateFleet")); return headers; }
jt70471/aws-sdk-cpp
aws-cpp-sdk-appstream/source/model/CreateFleetRequest.cpp
C++
apache-2.0
3,638
/** * Get more info at : www.jrebirth.org . * Copyright JRebirth.org © 2011-2013 * Contact : sebastien.bordes@jrebirth.org * * 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.jrebirth.af.core.resource.font; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import org.jrebirth.af.api.resource.builder.VariantResourceBuilder; import org.jrebirth.af.api.resource.font.FontExtension; import org.jrebirth.af.api.resource.font.FontItem; import org.jrebirth.af.api.resource.font.FontName; import org.jrebirth.af.api.resource.font.FontParams; import org.jrebirth.af.core.resource.ResourceBuilders; /** * The interface <strong>FontItemReal</strong> used to provided convenient shortcuts for initializing a {@link Font}. * * @author Sébastien Bordes */ public interface FontItemBase extends FontItem { /** * {@inheritDoc} */ @Override default VariantResourceBuilder<FontItem, FontParams, Font, Double> builder() { return ResourceBuilders.FONT_BUILDER; } /** * The interface <strong>Real</strong> provides shortcuts method used to build and register a {@link RealFont}. */ interface Real extends FontItemBase { /** * Build and register a {@link RealFont} {@link FontParams}. * * @param name the name of the font * @param size the size of the font * @param extension the font extension */ default void real(final FontName name, final double size, final FontExtension extension) { set(new RealFont(name, size, extension)); } /** * Build and register a {@link RealFont} {@link FontParams}. * * @param name the name of the font * @param size the size of the font */ default void real(final FontName name, final double size) { set(new RealFont(name, size)); } } /** * The interface <strong>Family</strong> provides shortcuts method used to build and register a {@link FamilyFont}. */ interface Family extends FontItemBase { /** * Build and register a {@link FamilyFont} {@link FontParams}. * * @param family the font family * @param size the font size * @param extension the font extension */ default void family(final String family, final double size, final FontExtension extension) { set(new FamilyFont(family, size, extension)); } /** * Build and register a {@link FamilyFont} {@link FontParams}. * * @param family the font family * @param size the font size * @param weight the font weight {@link FontWeight} * @param extension the font extension */ default void family(final String family, final double size, final FontWeight weight, final FontExtension extension) { set(new FamilyFont(family, size, extension, weight)); } /** * Build and register a {@link FamilyFont} {@link FontParams}. * * @param family the font family * @param size the font size * @param extension the font extension * @param posture the font posture {@link FontPosture} */ default void family(final String family, final double size, final FontExtension extension, final FontPosture posture) { set(new FamilyFont(family, size, extension, posture)); } /** * Build and register a {@link FamilyFont} {@link FontParams}. * * @param family the font family * @param size the font size * @param extension the font extension * @param weight the font weight {@link FontWeight} * @param posture the font posture {@link FontPosture} */ default void family(final String family, final double size, final FontExtension extension, final FontWeight weight, final FontPosture posture) { set(new FamilyFont(family, size, extension, weight, posture)); } /** * Build and register a {@link FamilyFont} {@link FontParams}. * * @param family the font family * @param size the font size */ default void family(final String family, final double size) { set(new FamilyFont(family, size)); } /** * Build and register a {@link FamilyFont} {@link FontParams}. * * @param family the font family * @param size the font size * @param weight the font weight {@link FontWeight} */ default void family(final String family, final double size, final FontWeight weight) { set(new FamilyFont(family, size, weight)); } /** * Build and register a {@link FamilyFont} {@link FontParams}. * * @param family the font family * @param size the font size * @param posture the font posture {@link FontPosture} */ default void family(final String family, final double size, final FontPosture posture) { set(new FamilyFont(family, size, posture)); } /** * Build and register a {@link FamilyFont} {@link FontParams}. * * @param family the font family * @param size the font size * @param weight the font weight {@link FontWeight} * @param posture the font posture {@link FontPosture} */ default void family(final String family, final double size, final FontWeight weight, final FontPosture posture) { set(new FamilyFont(family, size, weight, posture)); } } }
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/resource/font/FontItemBase.java
Java
apache-2.0
6,279
/* * Copyright 2012 Martin Winandy * * 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.pmw.tinylog; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import org.pmw.tinylog.writers.LogEntryValue; /** * Converts a format pattern for log entries to a list of tokens. * * @see Logger#setLoggingFormat(String) */ final class Tokenizer { private static final String DEFAULT_DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss"; private static final String NEW_LINE = EnvironmentHelper.getNewLine(); private static final Pattern NEW_LINE_REPLACER = Pattern.compile("\r\n|\\\\r\\\\n|\n|\\\\n|\r|\\\\r"); private static final String TAB = "\t"; private static final Pattern TAB_REPLACER = Pattern.compile("\t|\\\\t"); private final Locale locale; private final int maxStackTraceElements; private int index; /** * @param locale * Locale for formatting * @param maxStackTraceElements * Limit of stack traces for exceptions */ Tokenizer(final Locale locale, final int maxStackTraceElements) { this.locale = locale; this.maxStackTraceElements = maxStackTraceElements; } /** * Parse a format pattern. * * @param formatPattern * Format pattern for log entries * * @return List of tokens */ List<Token> parse(final String formatPattern) { List<Token> tokens = new ArrayList<>(); index = 0; while (index < formatPattern.length()) { char c = formatPattern.charAt(index); int start = index; while (c != '{' && c != '}') { ++index; if (index >= formatPattern.length()) { tokens.add(getPlainTextToken(formatPattern.substring(start, index))); return tokens; } c = formatPattern.charAt(index); } if (index > start) { tokens.add(getPlainTextToken(formatPattern.substring(start, index))); } if (c == '{') { Token token = parsePartly(formatPattern); if (token != null) { tokens.add(token); } } else if (c == '}') { InternalLogger.warn("Opening curly brace is missing for: \"{}\"", formatPattern.substring(0, index + 1)); ++index; } } return tokens; } private Token parsePartly(final String formatPattern) { List<Token> tokens = new ArrayList<>(); int[] options = new int[] { 0 /* minimum size */, 0 /* indent */}; int offset = index; ++index; while (index < formatPattern.length()) { char c = formatPattern.charAt(index); int start = index; while (c != '{' && c != '|' && c != '}') { ++index; if (index >= formatPattern.length()) { InternalLogger.warn("Closing curly brace is missing for: \"{}\"", formatPattern.substring(offset, index)); tokens.add(getToken(formatPattern.substring(start, index))); return combine(tokens, options); } c = formatPattern.charAt(index); } if (index > start) { if (c == '{') { tokens.add(getPlainTextToken(formatPattern.substring(start, index))); } else { tokens.add(getToken(formatPattern.substring(start, index))); } } if (c == '{') { Token token = parsePartly(formatPattern); if (token != null) { tokens.add(token); } } else if (c == '|') { ++index; start = index; while (c != '{' && c != '}') { ++index; if (index >= formatPattern.length()) { InternalLogger.warn("Closing curly brace is missing for: \"{}\"", formatPattern.substring(offset, index)); options = parseOptions(formatPattern.substring(start)); return combine(tokens, options); } c = formatPattern.charAt(index); } if (index > start) { options = parseOptions(formatPattern.substring(start, index)); } } else if (c == '}') { ++index; return combine(tokens, options); } } InternalLogger.warn("Closing curly brace is missing for: \"{}\"", formatPattern.substring(offset, index)); return combine(tokens, options); } private Token getToken(final String text) { if (text.equals("date")) { return new DateToken(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT_PATTERN, locale)); } else if (text.startsWith("date:")) { String dateFormatPattern = text.substring(5, text.length()); try { return new DateToken(DateTimeFormatter.ofPattern(dateFormatPattern, locale)); } catch (IllegalArgumentException ex) { InternalLogger.error(ex, "\"{}\" is an invalid date format pattern", dateFormatPattern); return new DateToken(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT_PATTERN, locale)); } } else if ("pid".equals(text)) { return new PlainTextToken(EnvironmentHelper.getProcessId()); } else if (text.startsWith("pid:")) { InternalLogger.warn("\"{pid}\" does not support parameters"); return new PlainTextToken(EnvironmentHelper.getProcessId().toString()); } else if ("thread".equals(text)) { return new ThreadNameToken(); } else if (text.startsWith("thread:")) { InternalLogger.warn("\"{thread}\" does not support parameters"); return new ThreadNameToken(); } else if ("thread_id".equals(text)) { return new ThreadIdToken(); } else if (text.startsWith("thread_id:")) { InternalLogger.warn("\"{thread_id}\" does not support parameters"); return new ThreadIdToken(); } else if ("class".equals(text)) { return new ClassToken(); } else if (text.startsWith("class:")) { InternalLogger.warn("\"{class}\" does not support parameters"); return new ClassToken(); } else if ("class_name".equals(text)) { return new ClassNameToken(); } else if (text.startsWith("class_name:")) { InternalLogger.warn("\"{class_name}\" does not support parameters"); return new ClassNameToken(); } else if ("package".equals(text)) { return new PackageToken(); } else if (text.startsWith("package:")) { InternalLogger.warn("\"{package}\" does not support parameters"); return new PackageToken(); } else if ("method".equals(text)) { return new MethodToken(); } else if (text.startsWith("method:")) { InternalLogger.warn("\"{method}\" does not support parameters"); return new MethodToken(); } else if ("file".equals(text)) { return new FileToken(); } else if (text.startsWith("file:")) { InternalLogger.warn("\"{file}\" does not support parameters"); return new FileToken(); } else if ("line".equals(text)) { return new LineToken(); } else if (text.startsWith("line:")) { InternalLogger.warn("\"{line}\" does not support parameters"); return new LineToken(); } else if ("level".equals(text)) { return new LevelToken(); } else if (text.startsWith("level:")) { InternalLogger.warn("\"{level}\" does not support parameters"); return new LevelToken(); } else if ("message".equals(text)) { return new MessageToken(maxStackTraceElements); } else if (text.startsWith("message:")) { InternalLogger.warn("\"{message}\" does not support parameters"); return new MessageToken(maxStackTraceElements); } else { return getPlainTextToken(text); } } private static Token getPlainTextToken(final String text) { String plainText = NEW_LINE_REPLACER.matcher(text).replaceAll(NEW_LINE); plainText = TAB_REPLACER.matcher(plainText).replaceAll(TAB); return new PlainTextToken(plainText); } private static int[] parseOptions(final String text) { int minSize = 0; int indent = 0; int index = 0; while (index < text.length()) { char c = text.charAt(index); while (c == ',') { ++index; if (index >= text.length()) { return new int[] { minSize, indent }; } c = text.charAt(index); } int start = index; while (c != ',') { ++index; if (index >= text.length()) { break; } c = text.charAt(index); } if (index > start) { String parameter = text.substring(start, index); int splitter = parameter.indexOf('='); if (splitter == -1) { parameter = parameter.trim(); if ("min-size".equals(parameter)) { InternalLogger.warn("No value set for \"min-size\""); } else if ("indent".equals(parameter)) { InternalLogger.warn("No value set for \"indent\""); } else { InternalLogger.warn("Unknown option \"{}\"", parameter); } } else { String key = parameter.substring(0, splitter).trim(); String value = parameter.substring(splitter + 1).trim(); if ("min-size".equals(key)) { if (value.length() == 0) { InternalLogger.warn("No value set for \"min-size\""); } else { try { minSize = parsePositiveInt(value); } catch (NumberFormatException ex) { InternalLogger.warn("\"{}\" is an invalid number for \"min-size\"", value); } } } else if ("indent".equals(key)) { if (value.length() == 0) { InternalLogger.warn("No value set for \"indent\""); } else { try { indent = parsePositiveInt(value); } catch (NumberFormatException ex) { InternalLogger.warn("\"{}\" is an invalid number for \"indent\"", value); } } } else { InternalLogger.warn("Unknown option \"{}\"", key); } } } } return new int[] { minSize, indent }; } private static int parsePositiveInt(final String value) throws NumberFormatException { int number = Integer.parseInt(value); if (number >= 0) { return number; } else { throw new NumberFormatException(); } } private static Token combine(final List<Token> tokens, final int[] options) { int minSize = options[0]; int indent = options[1]; if (tokens.isEmpty()) { return null; } else if (tokens.size() == 1) { if (indent > 0) { return new IndentToken(tokens.get(0), indent); } else if (minSize > 0) { return new MinSizeToken(tokens.get(0), minSize); } else { return tokens.get(0); } } else { if (indent > 0) { return new IndentToken(new BundlerToken(tokens), indent); } else if (minSize > 0) { return new MinSizeToken(new BundlerToken(tokens), minSize); } else { return new BundlerToken(tokens); } } } private static final class BundlerToken implements Token { private final List<Token> tokens; private BundlerToken(final List<Token> tokens) { this.tokens = tokens; } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { Collection<LogEntryValue> values = EnumSet.noneOf(LogEntryValue.class); for (Token token : tokens) { values.addAll(token.getRequiredLogEntryValues()); } return values; } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { for (Token token : tokens) { token.render(logEntry, builder); } } } private static final class MinSizeToken implements Token { private final Token token; private final int minSize; private MinSizeToken(final Token token, final int minSize) { this.token = token; this.minSize = minSize; } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return token.getRequiredLogEntryValues(); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { int offset = builder.length(); token.render(logEntry, builder); int size = builder.length() - offset; if (size < minSize) { char[] spaces = new char[minSize - size]; Arrays.fill(spaces, ' '); builder.append(spaces); } } } private static final class IndentToken implements Token { private final Token token; private final char[] spaces; private IndentToken(final Token token, final int indent) { this.token = token; this.spaces = new char[indent]; Arrays.fill(spaces, ' '); } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return token.getRequiredLogEntryValues(); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { if (builder.length() == 0 || builder.charAt(builder.length() - 1) == '\n' || builder.charAt(builder.length() - 1) == '\r') { builder.append(spaces); } StringBuilder subBuilder = new StringBuilder(1024); token.render(logEntry, subBuilder); int head = 0; for (int i = head; i < subBuilder.length(); ++i) { char c = subBuilder.charAt(i); if (c == '\n') { builder.append(subBuilder, head, i + 1); builder.append(spaces); head = i + 1; } else if (c == '\r') { if (i + 1 < subBuilder.length() && subBuilder.charAt(i + 1) == '\n') { ++i; } builder.append(subBuilder, head, i + 1); builder.append(spaces); head = i + 1; } else if (head == i && (c == ' ' || c == '\t')) { ++head; } } if (head < subBuilder.length()) { builder.append(subBuilder, head, subBuilder.length()); } } } private static final class DateToken implements Token { private final DateTimeFormatter formatter; private DateToken(final DateTimeFormatter formatter) { this.formatter = formatter; } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.DATE); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(formatter.format(logEntry.getDate())); } } private static final class ThreadNameToken implements Token { private ThreadNameToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.THREAD); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(logEntry.getThread().getName()); } }; private static final class ThreadIdToken implements Token { public ThreadIdToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.THREAD); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(logEntry.getThread().getId()); } } private static final class ClassToken implements Token { public ClassToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.CLASS); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(logEntry.getClassName()); } } private static final class ClassNameToken implements Token { public ClassNameToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.CLASS); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { String fullyQualifiedClassName = logEntry.getClassName(); int dotIndex = fullyQualifiedClassName.lastIndexOf('.'); if (dotIndex < 0) { builder.append(fullyQualifiedClassName); } else { builder.append(fullyQualifiedClassName.substring(dotIndex + 1)); } } } private static final class PackageToken implements Token { private PackageToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.CLASS); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { String fullyQualifiedClassName = logEntry.getClassName(); int dotIndex = fullyQualifiedClassName.lastIndexOf('.'); if (dotIndex != -1) { builder.append(fullyQualifiedClassName.substring(0, dotIndex)); } } } private static final class MethodToken implements Token { private MethodToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.METHOD); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(logEntry.getMethodName()); } } private static final class FileToken implements Token { private FileToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.FILE); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(logEntry.getFilename()); } } private static final class LineToken implements Token { private LineToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.LINE); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(logEntry.getLineNumber()); } } private static final class LevelToken implements Token { private LevelToken() { } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.LEVEL); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(logEntry.getLevel()); } } private static final class MessageToken implements Token { private static final String NEW_LINE = EnvironmentHelper.getNewLine(); private final int maxStackTraceElements; private MessageToken(final int maxStackTraceElements) { this.maxStackTraceElements = maxStackTraceElements; } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.singletonList(LogEntryValue.MESSAGE); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { String message = logEntry.getMessage(); if (message != null) { builder.append(message); } Throwable exception = logEntry.getException(); if (exception != null) { if (message != null) { builder.append(": "); } formatException(builder, exception, maxStackTraceElements); } } private static void formatException(final StringBuilder builder, final Throwable exception, final int maxStackTraceElements) { if (maxStackTraceElements == 0) { builder.append(exception.getClass().getName()); String exceptionMessage = exception.getMessage(); if (exceptionMessage != null) { builder.append(": "); builder.append(exceptionMessage); } } else { formatExceptionWithStackTrace(builder, exception, maxStackTraceElements); } } private static void formatExceptionWithStackTrace(final StringBuilder builder, final Throwable exception, final int countStackTraceElements) { builder.append(exception.getClass().getName()); String message = exception.getMessage(); if (message != null) { builder.append(": "); builder.append(message); } StackTraceElement[] stackTrace = exception.getStackTrace(); int length = Math.min(stackTrace.length, Math.max(1, countStackTraceElements)); for (int i = 0; i < length; ++i) { builder.append(NEW_LINE); builder.append('\t'); builder.append("at "); builder.append(stackTrace[i]); } if (stackTrace.length > length) { builder.append(NEW_LINE); builder.append('\t'); builder.append("..."); } else { Throwable cause = exception.getCause(); if (cause != null) { builder.append(NEW_LINE); builder.append("Caused by: "); formatExceptionWithStackTrace(builder, cause, countStackTraceElements - length); } } } } private static final class PlainTextToken implements Token { private final String text; private PlainTextToken(final String text) { this.text = text; } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return Collections.emptyList(); } @Override public void render(final LogEntry logEntry, final StringBuilder builder) { builder.append(text); } } }
yarish/tinylog
tinylog/src/main/java/org/pmw/tinylog/Tokenizer.java
Java
apache-2.0
21,096
// // Copyright 2015 Blu Age Corporation - Plano, Texas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using Summer.Batch.Extra.Copybook; namespace Summer.Batch.Extra.Ebcdic { /// <summary> /// An EbcdicReaderMapper maps a list of fields, corresponding to an EBCDIC /// record, to a business object. /// </summary> /// <typeparam name="TT">&nbsp;</typeparam> public interface IEbcdicReaderMapper<out TT> { /// <summary> /// Converts the content of a list of values into a business object. /// </summary> /// <param name="values">the list of values to map</param> /// <param name="itemCount">the record line number, starting at 0.</param> /// <returns>The mapped object</returns> TT Map(IList<object> values, int itemCount); /// <summary> /// Sets the record format map to use for mapping /// </summary> RecordFormatMap RecordFormatMap { set; } /// <summary> /// Sets the date parser /// </summary> IDateParser DateParser { set; } /// <summary> /// The getter for the distinguished pattern. /// </summary> string DistinguishedPattern { get; } } }
SummerBatch/SummerBatch
Summer.Batch.Extra/Ebcdic/IEbcdicReaderMapper.cs
C#
apache-2.0
1,853
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/es/model/AutoTune.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ElasticsearchService { namespace Model { AutoTune::AutoTune() : m_autoTuneType(AutoTuneType::NOT_SET), m_autoTuneTypeHasBeenSet(false), m_autoTuneDetailsHasBeenSet(false) { } AutoTune::AutoTune(JsonView jsonValue) : m_autoTuneType(AutoTuneType::NOT_SET), m_autoTuneTypeHasBeenSet(false), m_autoTuneDetailsHasBeenSet(false) { *this = jsonValue; } AutoTune& AutoTune::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("AutoTuneType")) { m_autoTuneType = AutoTuneTypeMapper::GetAutoTuneTypeForName(jsonValue.GetString("AutoTuneType")); m_autoTuneTypeHasBeenSet = true; } if(jsonValue.ValueExists("AutoTuneDetails")) { m_autoTuneDetails = jsonValue.GetObject("AutoTuneDetails"); m_autoTuneDetailsHasBeenSet = true; } return *this; } JsonValue AutoTune::Jsonize() const { JsonValue payload; if(m_autoTuneTypeHasBeenSet) { payload.WithString("AutoTuneType", AutoTuneTypeMapper::GetNameForAutoTuneType(m_autoTuneType)); } if(m_autoTuneDetailsHasBeenSet) { payload.WithObject("AutoTuneDetails", m_autoTuneDetails.Jsonize()); } return payload; } } // namespace Model } // namespace ElasticsearchService } // namespace Aws
aws/aws-sdk-cpp
aws-cpp-sdk-es/source/model/AutoTune.cpp
C++
apache-2.0
1,529
<?php /************************************************************************/ /* PHP-NUKE: Advanced Content Management System */ /* ============================================ */ /* */ /* Copyright (c) 2006 by Francisco Burzi */ /* http://phpnuke.org */ /* */ /* 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. */ /************************************************************************/ if (stristr(htmlentities($_SERVER['PHP_SELF']), "header.php")) { Header("Location: index.php"); die(); } $preloader = 1; //Preloader define('NUKE_HEADER', true); @require_once("mainfile.php"); global $db ,$prefix ,$gtset ,$admin ,$adminmail; if ($gtset == "1") { nextGenTap(1,0,0); } if(!$row = $db->sql_fetchrow($db->sql_query("SELECT * from ".$prefix."_nukesql"))){ die(header("location: upgrade.php")); } ################################################## # Include some common header for HTML generation # ################################################## global $pagetitle; if(defined("ADMIN_FILE")){ adminheader($pagetitle); }else{ global $name, $nukeurl, $xdemailset,$xtouch,$sitecookies; //// in this code we save current page that user is in it. if($name != "Your_Account"){ $currentpagelink = $_SERVER['REQUEST_URI']; $arr_nukeurl = explode("/",$nukeurl); $arr_nukeurl = array_filter($arr_nukeurl); foreach($arr_nukeurl as $key => $values){ if($key > 2){ unset($arr_nukeurl[$key]); } } $arr_nukeurl = array_filter($arr_nukeurl); $new_nukeurl = $arr_nukeurl[0]."//".$arr_nukeurl[2]; $currentpage = $new_nukeurl.$currentpagelink; nuke_set_cookie("currentpage",$currentpage,time()+1800); } if(!function_exists('head')){ function head() { global $slogan, $name, $sitename, $banners, $nukeurl, $Version_Num, $ab_config, $artpage, $topic, $hlpfile, $user, $hr, $theme, $cookie, $bgcolor1, $bgcolor2, $bgcolor3, $bgcolor4, $textcolor1, $textcolor2, $forumpage, $adminpage, $userpage, $pagetitle, $pagetags, $align, $preloader, $anonymous; $ThemeSel = get_theme(); theme_lang(); echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"; echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"; echo "<head>\n"; echo"<title>$sitename $pagetitle</title>"; @include("includes/meta.php"); @include("includes/javascript.php"); if (file_exists("themes/$ThemeSel/images/favicon.ico")) { echo "<link rel=\"shortcut icon\" href=\"themes/$ThemeSel/images/favicon.ico\" type=\"image/x-icon\" />\n"; } echo "</head>\n"; if($preloader == 1){ echo "<div id=\"waitDiv\" onclick=\"this.style.visibility='hidden'\" style=\" direction:rtl; text-align:center; line-height:17px; position:fixed; z-index:1000; width:100%; height:100%; background-color:#000; color:#fff; font-size:11px; margin:0px auto;\"><div style=\"position:fixed; top:100px; left:100px \" id=\"loadingimage\" ><img src=\"images/loader.gif\" /></div></div>"; echo "<script>showWaitm('waitDiv', 1);</script>\n"; echo "</div>\n"; } $u_agent = $_SERVER['HTTP_USER_AGENT']; themeheader(); } } online(); if(isset($admin) && $admin == $_COOKIE['admin']){}else{ function xdvs($nuim){ global $prefix, $db, $dbname; $nuim=intval($nuim); $result = $db->sql_query("SELECT * FROM `" . $prefix . "_xdisable` WHERE `xdid` =$nuim LIMIT 0 , 1"); while ($row = $db->sql_fetchrow($result)) { mb_internal_encoding('UTF-8'); $xdid = intval($row['xdid']); $xdname = $row['xdname']; $xdvalue = $row['xdvalue']; } return $xdvalue; } function xduemails($nuim){ global $prefix, $db, $dbname; $db->sql_query("INSERT INTO `$dbname`.`" . $prefix . "_xdisable` (`xdid`, `xdname`, `xdvalue`) VALUES (NULL, 'xduemail', '$nuim');"); } if(xdvs(1)==1){ if(isset($xdemailset)){ if (filter_var($xdemailset, FILTER_VALIDATE_EMAIL)) { xduemails($xdemailset); }else{ $xdemailset=0; } } $xdtheme=xdvs(2); if($xdtheme=="default"){ xdisable_theme(); }else{ @include("includes/xdisable/$xdtheme/xdtheme.php"); xdisable_theme(); } } } function xtscookie($name, $cookiedata, $cookietime){ global $sitecookies; if($cookiedata == false){ $cookietime = time()-3600; } $name_data = rawurlencode($name) . '=' . rawurlencode($cookiedata); $expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime); @header('Set-Cookie: '.$name_data.(($cookietime) ? '; expires='.$expire : '').'; path='.$sitecookies.'; HttpOnly', false); } if(isset($xtouch)){ $expire = time()+60*60*24*7; xtscookie("xtouch-set", $xtouch, $expire); if($_SERVER['HTTP_REFERER']==""){ Header("Location: index.php"); } else { header('Location:' . $_SERVER['HTTP_REFERER']); } } $mobile_browser = '0'; if(@preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone)/i', strtolower($_SERVER['HTTP_USER_AGENT']))){ $mobile_browser++; } if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))){ $mobile_browser++; } $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4)); $mobile_agents = array( 'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac', 'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno', 'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-', 'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-', 'newt','noki','oper','palm','pana','pant','phil','play','port','prox', 'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar', 'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-', 'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp', 'wapr','webc','winw','winw','xda','xda-'); if(in_array($mobile_ua,$mobile_agents)){ $mobile_browser++; } if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) { $mobile_browser++; } if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) { $mobile_browser=0; } if($mobile_browser>0 OR $_COOKIE['xtouch-set']==1){ require_once("XMSConfig.lib.php"); $xcall1=xsitemapitemcall("radius","حالت فعال بودن ماژول تاچ"); $xcallt=xsitemapitemcall("select","پوسته ماژول تاچ"); $xcallsm=xsitemapitemcall("select","منو در Xtouch"); $xcallst=xsitemapitemcall("text","عنوان سایت در حالت موبایل"); $xcallss=xsitemapitemcall("radius","نمایش لینک دسکتاپ"); $xcallsmm=xsitemapitemcall("checkbox","فعال بودن ماژول های تاچ"); if($xcall1[1]=="radius" AND $xcall1[2]=="حالت فعال بودن ماژول تاچ" AND $xcall1[3]!==""){ if($xcall1[3]==0 OR $xcall1[3]==1){ if($xcallsmm[1]=="checkbox" AND $xcallsmm[2]=="فعال بودن ماژول های تاچ"){$xtmodules=$xcallsmm[3];} if($xcallt[1]=="select" AND $xcallt[2]=="پوسته ماژول تاچ"){$xttheme=$xcallt[3];} if($xcallt[3]==""){$xttheme="default";} if($xcallsm[1]=="select" AND $xcallsm[2]=="منو در Xtouch" AND $xcallsm[3]!==""){$xtxmmenu=$xcallsm[3];} if($xcallst[1]=="text" AND $xcallst[2]=="عنوان سایت در حالت موبایل" AND $xcallst[3]!==""){$xtstitle=$xcallst[3];} if($xcallss[1]=="radius" AND $xcallss[2]=="نمایش لینک دسکتاپ" AND $xcallss[3]!==""){$swichers=$xcallss[3];} if($xcallst[3]==""){$xtstitle=$sitename;} if($xcall1[3]==1 AND is_admin($admin)){ if($xttheme=="default"){}else{include("modules/Xtouch/themes/$xttheme/xttheme.php");} xttheme($xtstitle,$xtxmmenu,$swichers,$xtmodules); }elseif($xcall1[3]==0){ if($xttheme=="default"){}else{include("modules/Xtouch/themes/$xttheme/xttheme.php");} xttheme($xtstitle,$xtxmmenu,$swichers,$xtmodules); } } } } head(); @include("includes/counter.php"); if(defined('HOME_FILE')) { message_box(); blocks("Center"); } } ?>
xtoolkit/XMPN
Xtouch/header2.php
PHP
apache-2.0
8,225
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2020 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.client.wizards; import static com.google.appinventor.client.Ode.MESSAGES; import com.allen_sauer.gwt.dnd.client.util.StringUtil; import com.google.appinventor.client.Ode; import com.google.appinventor.client.OdeAsyncCallback; import com.google.appinventor.client.editor.simple.SimpleComponentDatabase; import com.google.appinventor.client.editor.youngandroid.YaProjectEditor; import com.google.appinventor.client.explorer.project.Project; import com.google.appinventor.client.output.OdeLog; import com.google.appinventor.common.utils.StringUtils; import com.google.appinventor.client.utils.Uploader; import com.google.appinventor.shared.rpc.ServerLayout; import com.google.appinventor.shared.rpc.UploadResponse; import com.google.appinventor.shared.rpc.component.Component; import com.google.appinventor.shared.rpc.component.ComponentImportResponse; import com.google.appinventor.shared.rpc.project.ProjectNode; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidAssetsFolder; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidComponentsFolder; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidProjectNode; import com.google.gwt.core.client.GWT; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.client.Command; import com.google.gwt.cell.client.CheckboxCell; import com.google.gwt.cell.client.NumberCell; import com.google.gwt.cell.client.TextCell; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TabPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.view.client.ListDataProvider; import com.google.gwt.view.client.SingleSelectionModel; import java.util.List; public class ComponentImportWizard extends Wizard { final static String external_components = "assets/external_comps/"; public static class ImportComponentCallback extends OdeAsyncCallback<ComponentImportResponse> { @Override public void onSuccess(ComponentImportResponse response) { if (response.getStatus() == ComponentImportResponse.Status.FAILED){ Window.alert(MESSAGES.componentImportError() + "\n" + response.getMessage()); return; } else if (response.getStatus() != ComponentImportResponse.Status.IMPORTED && response.getStatus() != ComponentImportResponse.Status.UPGRADED) { Window.alert(MESSAGES.componentImportError()); return; } else if (response.getStatus() == ComponentImportResponse.Status.UNKNOWN_URL) { Window.alert(MESSAGES.componentImportUnknownURLError()); } else if (response.getStatus() == ComponentImportResponse.Status.UPGRADED) { StringBuilder sb = new StringBuilder(MESSAGES.componentUpgradedAlert()); for (String name : response.getComponentTypes().values()) { sb.append("\n"); sb.append(name); } Window.alert(sb.toString()); } List<ProjectNode> compNodes = response.getNodes(); long destinationProjectId = response.getProjectId(); long currentProjectId = ode.getCurrentYoungAndroidProjectId(); if (currentProjectId != destinationProjectId) { return; // User switched project early! } Project project = ode.getProjectManager().getProject(destinationProjectId); if (project == null) { return; // Project does not exist! } if (response.getStatus() == ComponentImportResponse.Status.UPGRADED || response.getStatus() == ComponentImportResponse.Status.IMPORTED) { YoungAndroidComponentsFolder componentsFolder = ((YoungAndroidProjectNode) project.getRootNode()).getComponentsFolder(); YaProjectEditor projectEditor = (YaProjectEditor) ode.getEditorManager().getOpenProjectEditor(destinationProjectId); if (projectEditor == null) { return; // Project is not open! } for (ProjectNode node : compNodes) { project.addNode(componentsFolder, node); if ((node.getName().equals("component.json") || node.getName().equals("components.json")) && StringUtils.countMatches(node.getFileId(), "/") == 3) { projectEditor.addComponent(node, null); } } } } } private static int FROM_MY_COMPUTER_TAB = 0; private static int URL_TAB = 1; private static final String COMPONENT_ARCHIVE_EXTENSION = ".aix"; private static final Ode ode = Ode.getInstance(); public ComponentImportWizard() { super(MESSAGES.componentImportWizardCaption(), true, false); final CellTable compTable = createCompTable(); final FileUpload fileUpload = createFileUpload(); final Grid urlGrid = createUrlGrid(); final TabPanel tabPanel = new TabPanel(); tabPanel.add(fileUpload, MESSAGES.componentImportFromComputer()); tabPanel.add(urlGrid, MESSAGES.componentImportFromURL()); tabPanel.selectTab(FROM_MY_COMPUTER_TAB); tabPanel.addStyleName("ode-Tabpanel"); VerticalPanel panel = new VerticalPanel(); panel.add(tabPanel); addPage(panel); getConfirmButton().setText("Import"); setPagePanelHeight(150); setPixelSize(200, 150); setStylePrimaryName("ode-DialogBox"); initFinishCommand(new Command() { @Override public void execute() { final long projectId = ode.getCurrentYoungAndroidProjectId(); final Project project = ode.getProjectManager().getProject(projectId); final YoungAndroidAssetsFolder assetsFolderNode = ((YoungAndroidProjectNode) project.getRootNode()).getAssetsFolder(); if (tabPanel.getTabBar().getSelectedTab() == URL_TAB) { TextBox urlTextBox = (TextBox) urlGrid.getWidget(1, 0); String url = urlTextBox.getText(); if (url.trim().isEmpty()) { Window.alert(MESSAGES.noUrlError()); return; } ode.getComponentService().importComponentToProject(url, projectId, assetsFolderNode.getFileId(), new ImportComponentCallback()); } else if (tabPanel.getTabBar().getSelectedTab() == FROM_MY_COMPUTER_TAB) { if (!fileUpload.getFilename().endsWith(COMPONENT_ARCHIVE_EXTENSION)) { Window.alert(MESSAGES.notComponentArchiveError()); return; } String url = GWT.getModuleBaseURL() + ServerLayout.UPLOAD_SERVLET + "/" + ServerLayout.UPLOAD_COMPONENT + "/" + trimLeadingPath(fileUpload.getFilename()); Uploader.getInstance().upload(fileUpload, url, new OdeAsyncCallback<UploadResponse>() { @Override public void onSuccess(UploadResponse uploadResponse) { String toImport = uploadResponse.getInfo(); ode.getComponentService().importComponentToProject(toImport, projectId, assetsFolderNode.getFileId(), new ImportComponentCallback()); } }); return; } } private String trimLeadingPath(String filename) { // Strip leading path off filename. // We need to support both Unix ('/') and Windows ('\\') separators. return filename.substring(Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\')) + 1); } }); } private CellTable createCompTable() { final SingleSelectionModel<Component> selectionModel = new SingleSelectionModel<Component>(); CellTable<Component> compTable = new CellTable<Component>(); compTable.setSelectionModel(selectionModel); Column<Component, Boolean> checkColumn = new Column<Component, Boolean>(new CheckboxCell(true, false)) { @Override public Boolean getValue(Component comp) { return selectionModel.isSelected(comp); } }; Column<Component, String> nameColumn = new Column<Component, String>(new TextCell()) { @Override public String getValue(Component comp) { return comp.getName(); } }; Column<Component, Number> versionColumn = new Column<Component, Number>(new NumberCell()) { @Override public Number getValue(Component comp) { return comp.getVersion(); } }; compTable.addColumn(checkColumn); compTable.addColumn(nameColumn, "Component"); compTable.addColumn(versionColumn, "Version"); return compTable; } private Grid createUrlGrid() { TextBox urlTextBox = new TextBox(); urlTextBox.setWidth("100%"); Grid grid = new Grid(2, 1); grid.setWidget(0, 0, new Label("Url:")); grid.setWidget(1, 0, urlTextBox); return grid; } private FileUpload createFileUpload() { FileUpload upload = new FileUpload(); upload.setName(ServerLayout.UPLOAD_COMPONENT_ARCHIVE_FORM_ELEMENT); upload.getElement().setAttribute("accept", COMPONENT_ARCHIVE_EXTENSION); return upload; } }
halatmit/appinventor-sources
appinventor/appengine/src/com/google/appinventor/client/wizards/ComponentImportWizard.java
Java
apache-2.0
9,473
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, 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. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.domain.materials; import com.thoughtworks.go.config.materials.SubprocessExecutionContext; import com.thoughtworks.go.remote.AgentIdentifier; import com.thoughtworks.go.util.CachedDigestUtils; import java.util.HashMap; import java.util.Map; class AgentSubprocessExecutionContext implements SubprocessExecutionContext { private AgentIdentifier agentIdentifier; private final String workingDirectory; AgentSubprocessExecutionContext(final AgentIdentifier agentIdentifier, String workingDirectory) { this.agentIdentifier = agentIdentifier; this.workingDirectory = workingDirectory; } public String getProcessNamespace(String fingerprint) { return CachedDigestUtils.sha256Hex(fingerprint + agentIdentifier.getUuid() + workingDirectory); } @Override public Map<String, String> getDefaultEnvironmentVariables() { return new HashMap<>(); } }
xli/gocd
common/src/com/thoughtworks/go/domain/materials/AgentSubprocessExecutionContext.java
Java
apache-2.0
1,684
package com.wangjie.rapidrouter; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
wangjiegulu/RapidRouter
library/src/test/java/com/wangjie/rapidrouter/ExampleUnitTest.java
Java
apache-2.0
401
/* * 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.beam.sdk.coders; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.beam.sdk.testing.CoderProperties; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.util.CoderUtils; import org.apache.beam.sdk.values.TypeDescriptor; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link ListCoder}. */ @RunWith(JUnit4.class) public class ListCoderTest { private static final Coder<List<Integer>> TEST_CODER = ListCoder.of(VarIntCoder.of()); private static final List<List<Integer>> TEST_VALUES = Arrays.asList( Collections.emptyList(), Collections.singletonList(43), Arrays.asList(1, 2, 3, 4), new ArrayList<>(Arrays.asList(7, 6, 5))); @Test public void testCoderIsSerializableWithWellKnownCoderType() throws Exception { CoderProperties.coderSerializable(ListCoder.of(GlobalWindow.Coder.INSTANCE)); } @Test public void testDecodeEncodeContentsInSameOrder() throws Exception { for (List<Integer> value : TEST_VALUES) { CoderProperties.coderDecodeEncodeContentsInSameOrder(TEST_CODER, value); } } @Test public void testEmptyList() throws Exception { List<Integer> list = Collections.emptyList(); Coder<List<Integer>> coder = ListCoder.of(VarIntCoder.of()); CoderProperties.coderDecodeEncodeEqual(coder, list); } @Test public void testCoderSerializable() throws Exception { CoderProperties.coderSerializable(TEST_CODER); } /** * Generated data to check that the wire format has not changed. To regenerate, see * {@link org.apache.beam.sdk.coders.PrintBase64Encodings}. */ private static final List<String> TEST_ENCODINGS = Arrays.asList( "AAAAAA", "AAAAASs", "AAAABAECAwQ", "AAAAAwcGBQ"); @Test public void testWireFormatEncode() throws Exception { CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void encodeNullThrowsCoderException() throws Exception { thrown.expect(CoderException.class); thrown.expectMessage("cannot encode a null List"); CoderUtils.encodeToBase64(TEST_CODER, null); } @Test public void testListWithNullsAndVarIntCoderThrowsException() throws Exception { thrown.expect(CoderException.class); thrown.expectMessage("cannot encode a null Integer"); List<Integer> list = Arrays.asList(1, 2, 3, null, 4); Coder<List<Integer>> coder = ListCoder.of(VarIntCoder.of()); CoderProperties.coderDecodeEncodeEqual(coder, list); } @Test public void testListWithNullsAndSerializableCoder() throws Exception { List<Integer> list = Arrays.asList(1, 2, 3, null, 4); Coder<List<Integer>> coder = ListCoder.of(SerializableCoder.of(Integer.class)); CoderProperties.coderDecodeEncodeEqual(coder, list); } @Test public void testEncodedTypeDescriptor() throws Exception { TypeDescriptor<List<Integer>> typeDescriptor = new TypeDescriptor<List<Integer>>() {}; assertThat(TEST_CODER.getEncodedTypeDescriptor(), equalTo(typeDescriptor)); } }
tgroh/incubator-beam
sdks/java/core/src/test/java/org/apache/beam/sdk/coders/ListCoderTest.java
Java
apache-2.0
4,233
config = { "interfaces": { "google.bigtable.v2.Bigtable": { "retry_codes": { "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], "non_idempotent": [], }, "retry_params": { "default": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 20000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 20000, "total_timeout_millis": 600000, }, "streaming": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 20000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 20000, "total_timeout_millis": 3600000, }, }, "methods": { "ReadRows": { "timeout_millis": 3600000, "retry_codes_name": "idempotent", "retry_params_name": "streaming", }, "SampleRowKeys": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "MutateRow": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "MutateRows": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "CheckAndMutateRow": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "ReadModifyWriteRow": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, }, } } }
dhermes/google-cloud-python
bigtable/google/cloud/bigtable_v2/gapic/bigtable_client_config.py
Python
apache-2.0
2,407
/******************************************************************************* * Copyright 2013 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * 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. ******************************************************************************/ /** * Contains components which are fundamental for all similarity measures. */ package dkpro.similarity.algorithms;
TitasNandi/Summer_Project
dkpro-similarity-master/dkpro-similarity-algorithms-core-asl/src/main/java/dkpro/similarity/algorithms/package-info.java
Java
apache-2.0
937
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2012, ITU/ISO/IEC * 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 name of the ITU/ISO/IEC 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. */ #include <vector> #include <algorithm> #include <ostream> #include "NALread.h" #include "TLibCommon/NAL.h" #include "TLibCommon/TComBitStream.h" using namespace std; //! \ingroup TLibDecoder //! \{ static void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, TComInputBitstream *pcBitstream) { unsigned zeroCount = 0; vector<uint8_t>::iterator it_read, it_write; UInt *auiStoredTileMarkerLocation = new UInt[MAX_MARKER_PER_NALU]; // Remove tile markers and note the bitstream location for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++ ) { Bool bTileMarkerFound = false; if ( ( it_read - nalUnitBuf.begin() ) < ( nalUnitBuf.size() - 2 ) ) { if ( (*(it_read) == 0x00) && (*(it_read+1) == 0x00) && (*(it_read+2) == 0x02) ) // tile marker detected { it_read += 2; UInt uiDistance = (UInt) (it_write - nalUnitBuf.begin()); UInt uiCount = pcBitstream->getTileMarkerLocationCount(); bTileMarkerFound = true; pcBitstream->setTileMarkerLocation( uiCount, uiDistance ); auiStoredTileMarkerLocation[uiCount] = uiDistance; pcBitstream->setTileMarkerLocationCount( uiCount + 1 ); } } if (!bTileMarkerFound) { *it_write = *it_read; it_write++; } } nalUnitBuf.resize(it_write - nalUnitBuf.begin()); for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++, it_write++) { if (zeroCount == 2 && *it_read == 0x03) { // update tile marker location UInt uiDistance = (UInt) (it_read - nalUnitBuf.begin()); for (UInt uiIdx=0; uiIdx<pcBitstream->getTileMarkerLocationCount(); uiIdx++) { if (auiStoredTileMarkerLocation[ uiIdx ] >= uiDistance) { pcBitstream->setTileMarkerLocation( uiIdx, pcBitstream->getTileMarkerLocation( uiIdx )-1 ); } } it_read++; zeroCount = 0; } zeroCount = (*it_read == 0x00) ? zeroCount+1 : 0; *it_write = *it_read; } nalUnitBuf.resize(it_write - nalUnitBuf.begin()); delete [] auiStoredTileMarkerLocation; } /** * create a NALunit structure with given header values and storage for * a bitstream */ void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf) { /* perform anti-emulation prevention */ TComInputBitstream *pcBitstream = new TComInputBitstream(NULL); convertPayloadToRBSP(nalUnitBuf, pcBitstream); nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf); // copy the tile marker location information nalu.m_Bitstream->setTileMarkerLocationCount( pcBitstream->getTileMarkerLocationCount() ); for (UInt uiIdx=0; uiIdx < nalu.m_Bitstream->getTileMarkerLocationCount(); uiIdx++) { nalu.m_Bitstream->setTileMarkerLocation( uiIdx, pcBitstream->getTileMarkerLocation(uiIdx) ); } delete pcBitstream; TComInputBitstream& bs = *nalu.m_Bitstream; bool forbidden_zero_bit = bs.read(1); assert(forbidden_zero_bit == 0); nalu.m_RefIDC = (NalRefIdc) bs.read(2); nalu.m_UnitType = (NalUnitType) bs.read(5); switch (nalu.m_UnitType) { case NAL_UNIT_CODED_SLICE: case NAL_UNIT_CODED_SLICE_IDR: case NAL_UNIT_CODED_SLICE_CDR: { nalu.m_TemporalID = bs.read(3); nalu.m_OutputFlag = bs.read(1); unsigned reserved_one_4bits = bs.read(4); assert(reserved_one_4bits == 1); } break; default: nalu.m_TemporalID = 0; nalu.m_OutputFlag = true; break; } } //! \}
lheric/GitlHEVCAnalyzer
appgitlhevcdecoder/HM-5.2/source/Lib/TLibDecoder/NALread.cpp
C++
apache-2.0
5,455
/* * Copyright 2017-present Open Networking Foundation * * 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.onosproject.openstacknetworking.impl; import com.google.common.collect.ImmutableSet; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.packet.IpAddress; import org.onlab.packet.MacAddress; import org.onlab.util.Tools; import org.onosproject.event.ListenerRegistry; import org.onosproject.net.Host; import org.onosproject.net.HostId; import org.onosproject.net.host.HostEvent; import org.onosproject.net.host.HostListener; import org.onosproject.net.host.HostService; import org.onosproject.openstacknetworking.api.InstancePort; import org.onosproject.openstacknetworking.api.InstancePortEvent; import org.onosproject.openstacknetworking.api.InstancePortListener; import org.onosproject.openstacknetworking.api.InstancePortService; import org.slf4j.Logger; import java.util.Set; import java.util.stream.Collectors; import static org.onosproject.openstacknetworking.api.InstancePortEvent.Type.OPENSTACK_INSTANCE_PORT_DETECTED; import static org.onosproject.openstacknetworking.api.InstancePortEvent.Type.OPENSTACK_INSTANCE_PORT_UPDATED; import static org.onosproject.openstacknetworking.api.InstancePortEvent.Type.OPENSTACK_INSTANCE_PORT_VANISHED; import static org.onosproject.openstacknetworking.impl.HostBasedInstancePort.ANNOTATION_NETWORK_ID; import static org.onosproject.openstacknetworking.impl.HostBasedInstancePort.ANNOTATION_PORT_ID; import static org.slf4j.LoggerFactory.getLogger; /** * Provides implementation of administering and interfacing host based instance ports. * It also provides instance port events for the hosts mapped to OpenStack VM interface. */ @Service @Component(immediate = true) public class HostBasedInstancePortManager extends ListenerRegistry<InstancePortEvent, InstancePortListener> implements InstancePortService { protected final Logger log = getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected HostService hostService; private final HostListener hostListener = new InternalHostListener(); @Activate protected void activate() { hostService.addListener(hostListener); log.info("Started"); } @Deactivate protected void deactivate() { hostService.removeListener(hostListener); log.info("Stopped"); } @Override public InstancePort instancePort(MacAddress macAddress) { Host host = hostService.getHost(HostId.hostId(macAddress)); if (host == null || !isValidHost(host)) { return null; } return HostBasedInstancePort.of(host); } @Override public InstancePort instancePort(IpAddress ipAddress, String osNetId) { return Tools.stream(hostService.getHosts()).filter(this::isValidHost) .map(HostBasedInstancePort::of) .filter(instPort -> instPort.networkId().equals(osNetId)) .filter(instPort -> instPort.ipAddress().equals(ipAddress)) .findAny().orElse(null); } @Override public InstancePort instancePort(String osPortId) { return Tools.stream(hostService.getHosts()).filter(this::isValidHost) .map(HostBasedInstancePort::of) .filter(instPort -> instPort.portId().equals(osPortId)) .findAny().orElse(null); } @Override public Set<InstancePort> instancePorts() { Set<InstancePort> instPors = Tools.stream(hostService.getHosts()) .filter(this::isValidHost) .map(HostBasedInstancePort::of) .collect(Collectors.toSet()); return ImmutableSet.copyOf(instPors); } @Override public Set<InstancePort> instancePorts(String osNetId) { Set<InstancePort> instPors = Tools.stream(hostService.getHosts()) .filter(this::isValidHost) .map(HostBasedInstancePort::of) .filter(instPort -> instPort.networkId().equals(osNetId)) .collect(Collectors.toSet()); return ImmutableSet.copyOf(instPors); } private boolean isValidHost(Host host) { return !host.ipAddresses().isEmpty() && host.annotations().value(ANNOTATION_NETWORK_ID) != null && host.annotations().value(ANNOTATION_PORT_ID) != null; } private class InternalHostListener implements HostListener { @Override public boolean isRelevant(HostEvent event) { Host host = event.subject(); if (!isValidHost(host)) { log.debug("Invalid host detected, ignore it {}", host); return false; } return true; } @Override public void event(HostEvent event) { InstancePort instPort = HostBasedInstancePort.of(event.subject()); InstancePortEvent instPortEvent; switch (event.type()) { case HOST_UPDATED: instPortEvent = new InstancePortEvent( OPENSTACK_INSTANCE_PORT_UPDATED, instPort); log.debug("Instance port is updated: {}", instPort); process(instPortEvent); break; case HOST_ADDED: instPortEvent = new InstancePortEvent( OPENSTACK_INSTANCE_PORT_DETECTED, instPort); log.debug("Instance port is detected: {}", instPort); process(instPortEvent); break; case HOST_REMOVED: instPortEvent = new InstancePortEvent( OPENSTACK_INSTANCE_PORT_VANISHED, instPort); log.debug("Instance port is disabled: {}", instPort); process(instPortEvent); break; default: break; } } } }
sdnwiselab/onos
apps/openstacknetworking/src/main/java/org/onosproject/openstacknetworking/impl/HostBasedInstancePortManager.java
Java
apache-2.0
6,879
package com.deliveredtechnologies.rulebook.runner.test.rulebooks; /** * Sample POJO rule with no annotations whatsoever. */ public class SampleRuleWithoutRuleAnnotation { }
Clayton7510/RuleBook
rulebook-core/src/test/java/com/deliveredtechnologies/rulebook/runner/test/rulebooks/SampleRuleWithoutRuleAnnotation.java
Java
apache-2.0
176
package play.curator.lock; import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessLock; import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex; import org.apache.curator.retry.ExponentialBackoffRetry; public class LockClient { public static final String NAMESPACE = "test/locks"; public static final String LOCK_NODE = "lockClient1"; /** * Starts a process to test locking across Zookeeper using Curator * @param args hostport waitTime processTime * @throws Exception */ public static void main(String[] args) throws Exception { new LockClient(args[0], Long.parseLong(args[1]), Long.parseLong(args[2])).run(); } private String connectionString; private long waitTime; private long processTime; public LockClient(String connectionString, long waitTime, long processTime) { this.connectionString = connectionString; this.waitTime = waitTime; this.processTime = processTime; } public void run() throws Exception { CuratorFramework framework = null; try { framework = CuratorFrameworkFactory.builder() .connectString(connectionString) .connectionTimeoutMs(3000) .namespace(NAMESPACE) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build(); framework.start(); InterProcessLock lock = new InterProcessSemaphoreMutex(framework, LOCK_NODE); System.out.println("Locking..."); if(lock.acquire(waitTime, TimeUnit.MILLISECONDS)) { try { System.out.println("Aquired Lock!"); System.out.println("Beginning 'Processing' ..."); Thread.sleep(processTime); System.out.println("'Processing' finished..."); } finally { lock.release(); System.out.println("Lock Released"); } } else { System.out.println("Could not aquire lock. Exiting..."); } } finally { if(framework != null) { framework.close(); } } } }
jbaiera/zookeeper-play
src/main/java/play/curator/lock/LockClient.java
Java
apache-2.0
2,027
/* * 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.shardingsphere.sql.parser.mysql.parser; import org.apache.shardingsphere.sql.parser.api.parser.SQLLexer; import org.apache.shardingsphere.sql.parser.api.parser.SQLParser; import org.apache.shardingsphere.sql.parser.spi.DatabaseTypedSQLParserFacade; /** * SQL parser facade for MySQL. */ public final class MySQLParserFacade implements DatabaseTypedSQLParserFacade { @Override public Class<? extends SQLLexer> getLexerClass() { return MySQLLexer.class; } @Override public Class<? extends SQLParser> getParserClass() { return MySQLParser.class; } @Override public String getDatabaseType() { return "MySQL"; } }
apache/incubator-shardingsphere
shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-mysql/src/main/java/org/apache/shardingsphere/sql/parser/mysql/parser/MySQLParserFacade.java
Java
apache-2.0
1,510
# # # 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. # # module Puppet::Parser::Functions newfunction(:hdp_host, :type => :rvalue) do |args| args = function_hdp_args_as_array(args) var = args[0] val = lookupvar("::"+var) function_hdp_is_empty(val) ? "" : val end end
telefonicaid/fiware-cosmos-ambari
ambari-agent/src/main/puppet/modules/hdp/lib/puppet/parser/functions/hdp_host.rb
Ruby
apache-2.0
1,024
/* * Copyright 2015-2025 the original author or authors. * * 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 sockslib.common; import java.security.Principal; /** * The class <code>Credentials</code> represents a credentials. * * @author Youchao Feng * @version 1.0 * @date May 14, 2015 2:35:26 PM */ public interface Credentials { /** * Returns principal. * * @return principal. */ Principal getUserPrincipal(); /** * Returns password. * * @return password. */ String getPassword(); }
fengyouchao/fucksocks
src/main/java/sockslib/common/Credentials.java
Java
apache-2.0
1,041
#include <3rdparty/yaml-cpp/node/node.h> #include "nodebuilder.h" #include "nodeevents.h" namespace YAML { Node Clone(const Node& node) { NodeEvents events(node); NodeBuilder builder; events.Emit(builder); return builder.Root(); } }
izenecloud/izenelib
source/3rdparty/yaml-cpp/node.cpp
C++
apache-2.0
272
package com.miaotu.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper; import com.miaotu.R; import com.miaotu.activity.PersonCenterActivity; import com.miaotu.model.GroupUserInfo; import com.miaotu.util.Util; import com.miaotu.view.CircleImageView; import java.util.List; /** * Created by Jayden on 2015/5/29. */ public class GroupUserAdapter extends BaseAdapter{ private List<GroupUserInfo> groupInfos; private LayoutInflater mLayoutInflater = null; private Context mContext; public GroupUserAdapter(Context context, List<GroupUserInfo> groupInfos){ this.groupInfos = groupInfos; mLayoutInflater = LayoutInflater.from(context); this.mContext = context; } @Override public int getCount() { return groupInfos == null?0:groupInfos.size(); } @Override public Object getItem(int i) { return groupInfos.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(final int i, View view, ViewGroup viewGroup) { ViewHolder holder = null; if(view == null){ view = mLayoutInflater.inflate(R.layout.item_group_user, null); holder = new ViewHolder(); holder.ivPhoto = (CircleImageView) view.findViewById(R.id.iv_head_photo); holder.tvName = (TextView) view.findViewById(R.id.tv_name); view.setTag(holder); }else { holder = (ViewHolder) view.getTag(); } UrlImageViewHelper.setUrlDrawable(holder.ivPhoto, groupInfos.get(i).getHeadurl(), R.drawable.icon_default_head_photo); holder.tvName.setText(groupInfos.get(i).getNickname()); holder.ivPhoto.setTag(i); holder.ivPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!Util.isNetworkConnected(mContext)) { return; } int pos = (int) view.getTag(); Intent intent = new Intent(mContext, PersonCenterActivity.class); intent.putExtra("uid", groupInfos.get(pos).getUid()); mContext.startActivity(intent); } }); return view; } public class ViewHolder{ CircleImageView ivPhoto; TextView tvName; } }
miaotu3/Mitotu
MiaoTu/src/main/java/com/miaotu/adapter/GroupUserAdapter.java
Java
apache-2.0
2,624
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #nullable enable using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class IAssemblySymbolExtensions { private const string AttributeSuffix = "Attribute"; public static bool ContainsNamespaceName( this List<IAssemblySymbol> assemblies, string namespaceName) { // PERF: Expansion of "assemblies.Any(a => a.NamespaceNames.Contains(namespaceName))" // to avoid allocating a lambda. foreach (var a in assemblies) { if (a.NamespaceNames.Contains(namespaceName)) { return true; } } return false; } public static bool ContainsTypeName(this List<IAssemblySymbol> assemblies, string typeName, bool tryWithAttributeSuffix = false) { if (!tryWithAttributeSuffix) { // PERF: Expansion of "assemblies.Any(a => a.TypeNames.Contains(typeName))" // to avoid allocating a lambda. foreach (var a in assemblies) { if (a.TypeNames.Contains(typeName)) { return true; } } } else { var attributeName = typeName + AttributeSuffix; foreach (var a in assemblies) { var typeNames = a.TypeNames; if (typeNames.Contains(typeName) || typeNames.Contains(attributeName)) { return true; } } } return false; } public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly) { return Equals(assembly, toAssembly) || (assembly.IsInteractive && toAssembly.IsInteractive) || toAssembly.GivesAccessTo(assembly); } } }
nguerrera/roslyn
src/Workspaces/Core/Portable/Shared/Extensions/IAssemblySymbolExtensions.cs
C#
apache-2.0
2,282
package com.custardsource.parfait.spring; import java.util.Random; @Profiled public class DelayingBean { private final int delay; public DelayingBean() { this.delay = new Random().nextInt(100); } @Profiled public void doThing() { try { Thread.sleep(delay); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
akshayahn/parfait
parfait-spring/src/test/java/com/custardsource/parfait/spring/DelayingBean.java
Java
apache-2.0
355
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-09-06 01:35 from __future__ import unicode_literals from django.db import migrations, models def load_settings(apps, schema_editor): Setting = apps.get_model("climate_data", "Setting") Setting( name="receiving_data", value="0" ).save() class Migration(migrations.Migration): dependencies = [ ('climate_data', '0013_setting'), ] operations = [ migrations.RunPython(load_settings) ]
qubs/data-centre
climate_data/migrations/0014_auto_20160906_0135.py
Python
apache-2.0
506
/* Copyright 2012, Strategic Gains, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.strategicgains.restexpress.response; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author toddf * @since May 14, 2012 */ public class ResponseProcessorResolver { private Map<String, ResponseProcessor> processors = new HashMap<String, ResponseProcessor>(); private String defaultFormat; public ResponseProcessorResolver() { super(); } public ResponseProcessorResolver(Map<String, ResponseProcessor> processors, String defaultFormat) { super(); this.processors.putAll(processors); this.defaultFormat = defaultFormat; } public ResponseProcessor put(String format, ResponseProcessor processor) { return processors.put(format, processor); } public void setDefaultFormat(String format) { this.defaultFormat = format; } public ResponseProcessor resolve(String requestFormat) { if (requestFormat == null || requestFormat.trim().isEmpty()) { return getDefault(); } return resolveViaSpecifiedFormat(requestFormat); } public ResponseProcessor getDefault() { return resolveViaSpecifiedFormat(defaultFormat); } private ResponseProcessor resolveViaSpecifiedFormat(String format) { if (format == null || format.trim().isEmpty()) { return null; } return processors.get(format); } /** * @return */ public Collection<String> getSupportedFormats() { return processors.keySet(); } }
kushalagrawal/RestExpress
src/java/com/strategicgains/restexpress/response/ResponseProcessorResolver.java
Java
apache-2.0
2,010
/** * 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.camel.example.fhir.osgi; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import javax.inject.Inject; import org.apache.camel.CamelContext; import org.apache.camel.ServiceStatus; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.tinybundles.core.TinyBundles; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.streamBundle; import static org.ops4j.pax.exam.CoreOptions.when; import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.debugConfiguration; import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class FhirOsgiIT { @Inject private CamelContext context; @Configuration public Option[] config() throws IOException { return options( PaxExamOptions.KARAF.option(), PaxExamOptions.CAMEL_FHIR.option(), streamBundle( TinyBundles.bundle() .read( Files.newInputStream( Paths.get("target") .resolve("camel-example-fhir-osgi.jar"))) .build()), when(false) .useOptions( debugConfiguration("5005", true)), CoreOptions.composite(editConfigurationFilePut( "etc/org.apache.camel.example.fhir.osgi.configuration.cfg", new File("org.apache.camel.example.fhir.osgi.configuration.cfg"))) ); } @Test public void testRouteStatus() { assertNotNull(context); assertEquals("Route status is incorrect!", ServiceStatus.Started, context.getRouteController().getRouteStatus("fhir-example-osgi")); } }
kevinearls/camel
examples/camel-example-fhir-osgi/src/test/java/org/apache/camel/example/fhir/osgi/FhirOsgiIT.java
Java
apache-2.0
3,055
/* * 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 myservice.mynamespace.web; import java.io.IOException; import java.lang.Override;import java.lang.RuntimeException;import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import myservice.mynamespace.data.Storage; import myservice.mynamespace.service.DemoBatchProcessor; import myservice.mynamespace.service.DemoEdmProvider; import myservice.mynamespace.service.DemoEntityCollectionProcessor; import myservice.mynamespace.service.DemoEntityProcessor; import myservice.mynamespace.service.DemoPrimitiveProcessor; import org.apache.olingo.server.api.OData; import org.apache.olingo.server.api.ODataHttpHandler; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.commons.api.edmx.EdmxReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DemoServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(DemoServlet.class); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { HttpSession session = req.getSession(true); Storage storage = (Storage) session.getAttribute(Storage.class.getName()); if (storage == null) { storage = new Storage(); session.setAttribute(Storage.class.getName(), storage); } // create odata handler and configure it with EdmProvider and Processor OData odata = OData.newInstance(); ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(), new ArrayList<EdmxReference>()); ODataHttpHandler handler = odata.createHandler(edm); handler.register(new DemoEntityCollectionProcessor(storage)); handler.register(new DemoEntityProcessor(storage)); handler.register(new DemoPrimitiveProcessor(storage)); handler.register(new DemoBatchProcessor(storage)); // let the handler do the work handler.process(req, resp); } catch (RuntimeException e) { LOG.error("Server Error occurred in ExampleServlet", e); throw new ServletException(e); } } }
apache/olingo-odata4
samples/tutorials/p11_batch/src/main/java/myservice/mynamespace/web/DemoServlet.java
Java
apache-2.0
3,114
package ingvar.android.processor.service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import ingvar.android.processor.exception.ProcessorException; import ingvar.android.processor.observation.IObserver; import ingvar.android.processor.observation.ScheduledObserver; import ingvar.android.processor.persistence.Time; import ingvar.android.processor.task.AbstractTask; import ingvar.android.processor.task.Execution; import ingvar.android.processor.task.ITask; import ingvar.android.processor.task.ScheduledExecution; import ingvar.android.processor.util.LW; /** * Wrapper for processing service. * Just provide helper methods. * Logged under DEBUG level. * * <br/><br/>Created by Igor Zubenko on 2015.03.19. */ public class Processor<S extends ProcessorService> { public static final String TAG = Processor.class.getSimpleName(); private Class<? extends ProcessorService> serviceClass; private Map<AbstractTask, IObserver[]> plannedTasks; private ServiceConnection connection; private S service; public Processor(Class<? extends ProcessorService> serviceClass) { this.serviceClass = serviceClass; this.service = null; this.connection = new Connection(); this.plannedTasks = new ConcurrentHashMap<>(); } /** * Send task for execution. * * @param task task * @param observers task observers * @return {@link Future} of task execution */ public Execution execute(AbstractTask task, IObserver... observers) { if(service == null) { throw new ProcessorException("Service is not bound yet!"); } return service.execute(task, observers); } /** * If service is bound execute task, otherwise add to queue. * * @param task task * @param observers task observers */ public void planExecute(AbstractTask task, IObserver... observers) { if(isBound()) { execute(task, observers); } else { plannedTasks.put(task, observers); LW.d(TAG, "Queued task %s", task); } } /** * Schedule task for single execution. * If task with same key & cache class already exists it will be cancelled and their observers will be removed. * * @param task task * @param delay the time from now to delay execution (millis) * @param observers task observers * @return {@link ScheduledFuture} of task execution */ public ScheduledExecution schedule(AbstractTask task, long delay, ScheduledObserver... observers) { if(!isBound()) { throw new ProcessorException("Service is not bound yet!"); } return service.schedule(task, delay, observers); } /** * Schedule task for multiple executions. * If task with same key & cache class already exists it will be cancelled and their observers will be removed. * * @param task task * @param initialDelay the time to delay first execution * @param delay the delay between the termination of one execution and the commencement of the next. * @param observers task observers * @return {@link ScheduledFuture} of task execution */ public ScheduledExecution schedule(AbstractTask task, long initialDelay, long delay, ScheduledObserver... observers) { if(!isBound()) { throw new ProcessorException("Service is not bound yet!"); } return service.schedule(task, initialDelay, delay, observers); } public void cancel(AbstractTask task) { if(!isBound()) { throw new ProcessorException("Service is not bound yet!"); } service.cancel(task); } public ScheduledExecution getScheduled(AbstractTask task) { if(!isBound()) { throw new ProcessorException("Service is not bound yet!"); } return service.getScheduled(task); } /** * Remove registered observers from task. * * @param task task */ public void removeObservers(ITask task) { service.getObserverManager().remove(task); } /** * Obtain task result from cache. * * @param key result identifier * @param dataClass single result item class * @param expiryTime how much time data consider valid in the repository * @param <R> returned result class * @return cached result if exists and did not expired, null otherwise */ public <R> R obtainFromCache(Object key, Class dataClass, long expiryTime) { return service.getCacheManager().obtain(key, dataClass, expiryTime); } /** * Obtain task result from cache if exists. * * @param key result identifier * @param dataClass single result item class * @param <R> returned result class * @return cached result if exists, null otherwise */ public <R> R obtainFromCache(Object key, Class dataClass) { return obtainFromCache(key, dataClass, Time.ALWAYS_RETURNED); } public void removeFromCache(Object key, Class dataClass) { service.getCacheManager().remove(key, dataClass); } /** * Remove all data by class. * * @param dataClass data class */ public void clearCache(Class dataClass) { service.getCacheManager().remove(dataClass); } /** * Remove all data from cache. */ public void clearCache() { service.clearCache(); } /** * Bind service to context. * * @param context context */ public void bind(Context context) { LW.d(TAG, "Bind service '%s' to context '%s'", serviceClass.getSimpleName(), context.getClass().getSimpleName()); Intent intent = new Intent(context, serviceClass); context.startService(intent); //keep service alive after context unbound. if(!context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) { throw new ProcessorException("Connection is not made. Maybe you forgot add your service to AndroidManifest.xml?"); } } /** * Unbind service from context. * Remove all planned tasks if exist. * * @param context */ public void unbind(Context context) { LW.d(TAG, "Unbind service '%s' from context '%s'", serviceClass.getSimpleName(), context.getClass().getSimpleName()); if(service != null) { service.removeObservers(context); } context.unbindService(connection); plannedTasks.clear(); service = null; } /** * Check bound service or not. * * @return true if bound, false otherwise */ public boolean isBound() { return service != null; } /** * Get service. * * @return service or null if not bound */ public S getService() { return service; } private class Connection implements ServiceConnection { @Override @SuppressWarnings("unchecked") public void onServiceConnected(ComponentName name, IBinder service) { LW.d(TAG, "Service '%s' connected.", name); Processor.this.service = (S) ((ProcessorService.ProcessorBinder) service).getService(); if(plannedTasks.size() > 0) { LW.d(TAG, "Execute planned %d tasks.", plannedTasks.size()); for (Map.Entry<AbstractTask, IObserver[]> entry : plannedTasks.entrySet()) { Processor.this.service.execute(entry.getKey(), entry.getValue()); } plannedTasks.clear(); } } @Override public void onServiceDisconnected(ComponentName name) { LW.d(TAG, "Service '%s' disconnected.", name); plannedTasks.clear(); Processor.this.service = null; } } }
orwir/processor
core/src/main/java/ingvar/android/processor/service/Processor.java
Java
apache-2.0
8,123
/******************************************************************************* * Copyright (c) quickfixengine.org All rights reserved. * * This file is part of the QuickFIX FIX Engine * * This file may be distributed under the terms of the quickfixengine.org * license as defined by quickfixengine.org and appearing in the file * LICENSE included in the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.quickfixengine.org/LICENSE for licensing information. * * Contact ask@quickfixengine.org if any conditions of this licensing * are not clear to you. ******************************************************************************/ package quickfix.field; import quickfix.DecimalField; public class OfferSwapPoints extends DecimalField { static final long serialVersionUID = 20050617; public static final int FIELD = 1066; public OfferSwapPoints() { super(1066); } public OfferSwapPoints(java.math.BigDecimal data) { super(1066, data); } public OfferSwapPoints(double data) { super(1066, new java.math.BigDecimal(data)); } }
Forexware/quickfixj
src/main/java/quickfix/field/OfferSwapPoints.java
Java
apache-2.0
1,279
// Copyright 2017 The Prometheus Authors // 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 index import ( "container/heap" "encoding/binary" "runtime" "sort" "strings" "sync" "github.com/prometheus/prometheus/pkg/labels" ) var allPostingsKey = labels.Label{} // AllPostingsKey returns the label key that is used to store the postings list of all existing IDs. func AllPostingsKey() (name, value string) { return allPostingsKey.Name, allPostingsKey.Value } // MemPostings holds postings list for series ID per label pair. They may be written // to out of order. // ensureOrder() must be called once before any reads are done. This allows for quick // unordered batch fills on startup. type MemPostings struct { mtx sync.RWMutex m map[string]map[string][]uint64 ordered bool } // NewMemPostings returns a memPostings that's ready for reads and writes. func NewMemPostings() *MemPostings { return &MemPostings{ m: make(map[string]map[string][]uint64, 512), ordered: true, } } // NewUnorderedMemPostings returns a memPostings that is not safe to be read from // until ensureOrder was called once. func NewUnorderedMemPostings() *MemPostings { return &MemPostings{ m: make(map[string]map[string][]uint64, 512), ordered: false, } } // SortedKeys returns a list of sorted label keys of the postings. func (p *MemPostings) SortedKeys() []labels.Label { p.mtx.RLock() keys := make([]labels.Label, 0, len(p.m)) for n, e := range p.m { for v := range e { keys = append(keys, labels.Label{Name: n, Value: v}) } } p.mtx.RUnlock() sort.Slice(keys, func(i, j int) bool { if d := strings.Compare(keys[i].Name, keys[j].Name); d != 0 { return d < 0 } return keys[i].Value < keys[j].Value }) return keys } // LabelNames returns all the unique label names. func (p *MemPostings) LabelNames() []string { p.mtx.RLock() defer p.mtx.RUnlock() n := len(p.m) if n == 0 { return nil } names := make([]string, 0, n-1) for name := range p.m { if name != allPostingsKey.Name { names = append(names, name) } } return names } // LabelValues returns label values for the given name. func (p *MemPostings) LabelValues(name string) []string { p.mtx.RLock() defer p.mtx.RUnlock() values := make([]string, 0, len(p.m[name])) for v := range p.m[name] { values = append(values, v) } return values } // PostingsStats contains cardinality based statistics for postings. type PostingsStats struct { CardinalityMetricsStats []Stat CardinalityLabelStats []Stat LabelValueStats []Stat LabelValuePairsStats []Stat NumLabelPairs int } // Stats calculates the cardinality statistics from postings. func (p *MemPostings) Stats(label string) *PostingsStats { const maxNumOfRecords = 10 var size uint64 p.mtx.RLock() metrics := &maxHeap{} labels := &maxHeap{} labelValueLength := &maxHeap{} labelValuePairs := &maxHeap{} numLabelPairs := 0 metrics.init(maxNumOfRecords) labels.init(maxNumOfRecords) labelValueLength.init(maxNumOfRecords) labelValuePairs.init(maxNumOfRecords) for n, e := range p.m { if n == "" { continue } labels.push(Stat{Name: n, Count: uint64(len(e))}) numLabelPairs += len(e) size = 0 for name, values := range e { if n == label { metrics.push(Stat{Name: name, Count: uint64(len(values))}) } labelValuePairs.push(Stat{Name: n + "=" + name, Count: uint64(len(values))}) size += uint64(len(name)) } labelValueLength.push(Stat{Name: n, Count: size}) } p.mtx.RUnlock() return &PostingsStats{ CardinalityMetricsStats: metrics.get(), CardinalityLabelStats: labels.get(), LabelValueStats: labelValueLength.get(), LabelValuePairsStats: labelValuePairs.get(), NumLabelPairs: numLabelPairs, } } // Get returns a postings list for the given label pair. func (p *MemPostings) Get(name, value string) Postings { var lp []uint64 p.mtx.RLock() l := p.m[name] if l != nil { lp = l[value] } p.mtx.RUnlock() if lp == nil { return EmptyPostings() } return newListPostings(lp...) } // All returns a postings list over all documents ever added. func (p *MemPostings) All() Postings { return p.Get(AllPostingsKey()) } // EnsureOrder ensures that all postings lists are sorted. After it returns all further // calls to add and addFor will insert new IDs in a sorted manner. func (p *MemPostings) EnsureOrder() { p.mtx.Lock() defer p.mtx.Unlock() if p.ordered { return } n := runtime.GOMAXPROCS(0) workc := make(chan []uint64) var wg sync.WaitGroup wg.Add(n) for i := 0; i < n; i++ { go func() { for l := range workc { sort.Slice(l, func(a, b int) bool { return l[a] < l[b] }) } wg.Done() }() } for _, e := range p.m { for _, l := range e { workc <- l } } close(workc) wg.Wait() p.ordered = true } // Delete removes all ids in the given map from the postings lists. func (p *MemPostings) Delete(deleted map[uint64]struct{}) { var keys, vals []string // Collect all keys relevant for deletion once. New keys added afterwards // can by definition not be affected by any of the given deletes. p.mtx.RLock() for n := range p.m { keys = append(keys, n) } p.mtx.RUnlock() for _, n := range keys { p.mtx.RLock() vals = vals[:0] for v := range p.m[n] { vals = append(vals, v) } p.mtx.RUnlock() // For each posting we first analyse whether the postings list is affected by the deletes. // If yes, we actually reallocate a new postings list. for _, l := range vals { // Only lock for processing one postings list so we don't block reads for too long. p.mtx.Lock() found := false for _, id := range p.m[n][l] { if _, ok := deleted[id]; ok { found = true break } } if !found { p.mtx.Unlock() continue } repl := make([]uint64, 0, len(p.m[n][l])) for _, id := range p.m[n][l] { if _, ok := deleted[id]; !ok { repl = append(repl, id) } } if len(repl) > 0 { p.m[n][l] = repl } else { delete(p.m[n], l) } p.mtx.Unlock() } p.mtx.Lock() if len(p.m[n]) == 0 { delete(p.m, n) } p.mtx.Unlock() } } // Iter calls f for each postings list. It aborts if f returns an error and returns it. func (p *MemPostings) Iter(f func(labels.Label, Postings) error) error { p.mtx.RLock() defer p.mtx.RUnlock() for n, e := range p.m { for v, p := range e { if err := f(labels.Label{Name: n, Value: v}, newListPostings(p...)); err != nil { return err } } } return nil } // Add a label set to the postings index. func (p *MemPostings) Add(id uint64, lset labels.Labels) { p.mtx.Lock() for _, l := range lset { p.addFor(id, l) } p.addFor(id, allPostingsKey) p.mtx.Unlock() } func (p *MemPostings) addFor(id uint64, l labels.Label) { nm, ok := p.m[l.Name] if !ok { nm = map[string][]uint64{} p.m[l.Name] = nm } list := append(nm[l.Value], id) nm[l.Value] = list if !p.ordered { return } // There is no guarantee that no higher ID was inserted before as they may // be generated independently before adding them to postings. // We repair order violations on insert. The invariant is that the first n-1 // items in the list are already sorted. for i := len(list) - 1; i >= 1; i-- { if list[i] >= list[i-1] { break } list[i], list[i-1] = list[i-1], list[i] } } // ExpandPostings returns the postings expanded as a slice. func ExpandPostings(p Postings) (res []uint64, err error) { for p.Next() { res = append(res, p.At()) } return res, p.Err() } // Postings provides iterative access over a postings list. type Postings interface { // Next advances the iterator and returns true if another value was found. Next() bool // Seek advances the iterator to value v or greater and returns // true if a value was found. Seek(v uint64) bool // At returns the value at the current iterator position. At() uint64 // Err returns the last error of the iterator. Err() error } // errPostings is an empty iterator that always errors. type errPostings struct { err error } func (e errPostings) Next() bool { return false } func (e errPostings) Seek(uint64) bool { return false } func (e errPostings) At() uint64 { return 0 } func (e errPostings) Err() error { return e.err } var emptyPostings = errPostings{} // EmptyPostings returns a postings list that's always empty. // NOTE: Returning EmptyPostings sentinel when index.Postings struct has no postings is recommended. // It triggers optimized flow in other functions like Intersect, Without etc. func EmptyPostings() Postings { return emptyPostings } // ErrPostings returns new postings that immediately error. func ErrPostings(err error) Postings { return errPostings{err} } // Intersect returns a new postings list over the intersection of the // input postings. func Intersect(its ...Postings) Postings { if len(its) == 0 { return EmptyPostings() } if len(its) == 1 { return its[0] } for _, p := range its { if p == EmptyPostings() { return EmptyPostings() } } return newIntersectPostings(its...) } type intersectPostings struct { arr []Postings cur uint64 } func newIntersectPostings(its ...Postings) *intersectPostings { return &intersectPostings{arr: its} } func (it *intersectPostings) At() uint64 { return it.cur } func (it *intersectPostings) doNext() bool { Loop: for { for _, p := range it.arr { if !p.Seek(it.cur) { return false } if p.At() > it.cur { it.cur = p.At() continue Loop } } return true } } func (it *intersectPostings) Next() bool { for _, p := range it.arr { if !p.Next() { return false } if p.At() > it.cur { it.cur = p.At() } } return it.doNext() } func (it *intersectPostings) Seek(id uint64) bool { it.cur = id return it.doNext() } func (it *intersectPostings) Err() error { for _, p := range it.arr { if p.Err() != nil { return p.Err() } } return nil } // Merge returns a new iterator over the union of the input iterators. func Merge(its ...Postings) Postings { if len(its) == 0 { return EmptyPostings() } if len(its) == 1 { return its[0] } p, ok := newMergedPostings(its) if !ok { return EmptyPostings() } return p } type postingsHeap []Postings func (h postingsHeap) Len() int { return len(h) } func (h postingsHeap) Less(i, j int) bool { return h[i].At() < h[j].At() } func (h *postingsHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } func (h *postingsHeap) Push(x interface{}) { *h = append(*h, x.(Postings)) } func (h *postingsHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } type mergedPostings struct { h postingsHeap initialized bool cur uint64 err error } func newMergedPostings(p []Postings) (m *mergedPostings, nonEmpty bool) { ph := make(postingsHeap, 0, len(p)) for _, it := range p { // NOTE: mergedPostings struct requires the user to issue an initial Next. if it.Next() { ph = append(ph, it) } else { if it.Err() != nil { return &mergedPostings{err: it.Err()}, true } } } if len(ph) == 0 { return nil, false } return &mergedPostings{h: ph}, true } func (it *mergedPostings) Next() bool { if it.h.Len() == 0 || it.err != nil { return false } // The user must issue an initial Next. if !it.initialized { heap.Init(&it.h) it.cur = it.h[0].At() it.initialized = true return true } for { cur := it.h[0] if !cur.Next() { heap.Pop(&it.h) if cur.Err() != nil { it.err = cur.Err() return false } if it.h.Len() == 0 { return false } } else { // Value of top of heap has changed, re-heapify. heap.Fix(&it.h, 0) } if it.h[0].At() != it.cur { it.cur = it.h[0].At() return true } } } func (it *mergedPostings) Seek(id uint64) bool { if it.h.Len() == 0 || it.err != nil { return false } if !it.initialized { if !it.Next() { return false } } for it.cur < id { cur := it.h[0] if !cur.Seek(id) { heap.Pop(&it.h) if cur.Err() != nil { it.err = cur.Err() return false } if it.h.Len() == 0 { return false } } else { // Value of top of heap has changed, re-heapify. heap.Fix(&it.h, 0) } it.cur = it.h[0].At() } return true } func (it mergedPostings) At() uint64 { return it.cur } func (it mergedPostings) Err() error { return it.err } // Without returns a new postings list that contains all elements from the full list that // are not in the drop list. func Without(full, drop Postings) Postings { if full == EmptyPostings() { return EmptyPostings() } if drop == EmptyPostings() { return full } return newRemovedPostings(full, drop) } type removedPostings struct { full, remove Postings cur uint64 initialized bool fok, rok bool } func newRemovedPostings(full, remove Postings) *removedPostings { return &removedPostings{ full: full, remove: remove, } } func (rp *removedPostings) At() uint64 { return rp.cur } func (rp *removedPostings) Next() bool { if !rp.initialized { rp.fok = rp.full.Next() rp.rok = rp.remove.Next() rp.initialized = true } for { if !rp.fok { return false } if !rp.rok { rp.cur = rp.full.At() rp.fok = rp.full.Next() return true } fcur, rcur := rp.full.At(), rp.remove.At() if fcur < rcur { rp.cur = fcur rp.fok = rp.full.Next() return true } else if rcur < fcur { // Forward the remove postings to the right position. rp.rok = rp.remove.Seek(fcur) } else { // Skip the current posting. rp.fok = rp.full.Next() } } } func (rp *removedPostings) Seek(id uint64) bool { if rp.cur >= id { return true } rp.fok = rp.full.Seek(id) rp.rok = rp.remove.Seek(id) rp.initialized = true return rp.Next() } func (rp *removedPostings) Err() error { if rp.full.Err() != nil { return rp.full.Err() } return rp.remove.Err() } // ListPostings implements the Postings interface over a plain list. type ListPostings struct { list []uint64 cur uint64 } func NewListPostings(list []uint64) Postings { return newListPostings(list...) } func newListPostings(list ...uint64) *ListPostings { return &ListPostings{list: list} } func (it *ListPostings) At() uint64 { return it.cur } func (it *ListPostings) Next() bool { if len(it.list) > 0 { it.cur = it.list[0] it.list = it.list[1:] return true } it.cur = 0 return false } func (it *ListPostings) Seek(x uint64) bool { // If the current value satisfies, then return. if it.cur >= x { return true } if len(it.list) == 0 { return false } // Do binary search between current position and end. i := sort.Search(len(it.list), func(i int) bool { return it.list[i] >= x }) if i < len(it.list) { it.cur = it.list[i] it.list = it.list[i+1:] return true } it.list = nil return false } func (it *ListPostings) Err() error { return nil } // bigEndianPostings implements the Postings interface over a byte stream of // big endian numbers. type bigEndianPostings struct { list []byte cur uint32 } func newBigEndianPostings(list []byte) *bigEndianPostings { return &bigEndianPostings{list: list} } func (it *bigEndianPostings) At() uint64 { return uint64(it.cur) } func (it *bigEndianPostings) Next() bool { if len(it.list) >= 4 { it.cur = binary.BigEndian.Uint32(it.list) it.list = it.list[4:] return true } return false } func (it *bigEndianPostings) Seek(x uint64) bool { if uint64(it.cur) >= x { return true } num := len(it.list) / 4 // Do binary search between current position and end. i := sort.Search(num, func(i int) bool { return binary.BigEndian.Uint32(it.list[i*4:]) >= uint32(x) }) if i < num { j := i * 4 it.cur = binary.BigEndian.Uint32(it.list[j:]) it.list = it.list[j+4:] return true } it.list = nil return false } func (it *bigEndianPostings) Err() error { return nil }
GoogleCloudPlatform/prometheus-engine
vendor/github.com/prometheus/prometheus/tsdb/index/postings.go
GO
apache-2.0
16,432
using System; using System.Collections; using System.Collections.Generic; using System.Threading; namespace Restful.Collections.Generic { /// <summary> /// 表示键值对的线程安全泛型集合 /// </summary> /// <typeparam name="TKey">键类型</typeparam> /// <typeparam name="TValue">值类型</typeparam> [Serializable] public class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private object syncRoot; private readonly IDictionary<TKey, TValue> dictionary; public ThreadSafeDictionary() { this.dictionary = new Dictionary<TKey, TValue>(); } public ThreadSafeDictionary( IDictionary<TKey, TValue> dictionary ) { this.dictionary = dictionary; } public object SyncRoot { get { if( syncRoot == null ) { Interlocked.CompareExchange( ref syncRoot, new object(), null ); } return syncRoot; } } #region IDictionary<TKey,TValue> Members public bool ContainsKey( TKey key ) { return dictionary.ContainsKey( key ); } public void Add( TKey key, TValue value ) { lock( SyncRoot ) { dictionary.Add( key, value ); } } public bool Remove( TKey key ) { lock( SyncRoot ) { return dictionary.Remove( key ); } } public bool TryGetValue( TKey key, out TValue value ) { return dictionary.TryGetValue( key, out value ); } public TValue this[TKey key] { get { return dictionary[key]; } set { lock( SyncRoot ) { dictionary[key] = value; } } } public ICollection<TKey> Keys { get { lock( SyncRoot ) { return dictionary.Keys; } } } public ICollection<TValue> Values { get { lock( SyncRoot ) { return dictionary.Values; } } } #endregion #region ICollection<KeyValuePair<TKey,TValue>> Members public void Add( KeyValuePair<TKey, TValue> item ) { lock( SyncRoot ) { dictionary.Add( item ); } } public void Clear() { lock( SyncRoot ) { dictionary.Clear(); } } public bool Contains( KeyValuePair<TKey, TValue> item ) { return dictionary.Contains( item ); } public void CopyTo( KeyValuePair<TKey, TValue>[] array, int arrayIndex ) { lock( SyncRoot ) { dictionary.CopyTo( array, arrayIndex ); } } public bool Remove( KeyValuePair<TKey, TValue> item ) { lock( SyncRoot ) { return dictionary.Remove( item ); } } public int Count { get { return dictionary.Count; } } public bool IsReadOnly { get { return false; } } #endregion #region IEnumerable<KeyValuePair<TKey,TValue>> Members IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { lock( SyncRoot ) { KeyValuePair<TKey, TValue>[] pairArray = new KeyValuePair<TKey, TValue>[dictionary.Count]; this.dictionary.CopyTo( pairArray, 0 ); return Array.AsReadOnly( pairArray ).GetEnumerator(); } } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return ( (IEnumerable<KeyValuePair<TKey, TValue>>)this ).GetEnumerator(); } #endregion } }
chinadev/Restful
src/Restful/Restful/Collections/Generic/ThreadSafeDictionary.cs
C#
apache-2.0
4,347
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pedrogomez.renderers.sample.ui.renderers; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import com.pedrogomez.renderers.sample.R; import com.pedrogomez.renderers.sample.model.Video; import java.util.Date; /** * VideoRenderer created to contains the live video presentation logic. This VideoRenderer subtype * change the inflated layout and override the renderer algorithm to add a new phase to render the * date. * * @author Pedro Vicente Gómez Sánchez. */ public class LiveVideoRenderer extends VideoRenderer { @Bind(R.id.date) TextView date; @Override protected View inflate(LayoutInflater inflater, ViewGroup parent) { View inflatedView = inflater.inflate(R.layout.live_video_renderer, parent, false); ButterKnife.bind(this, inflatedView); return inflatedView; } @Override protected void setUpView(View rootView) { /* * Empty implementation substituted with the usage of ButterKnife library by Jake Wharton. */ } @Override protected void renderLabel() { getLabel().setText(getContext().getString(R.string.live_label)); } @Override protected void renderMarker(Video video) { getMarker().setVisibility(View.GONE); } @Override public void render() { super.render(); renderDate(); } private void renderDate() { String now = new Date().toLocaleString(); date.setText(now); } }
manolovn/Renderers
sample/src/main/java/com/pedrogomez/renderers/sample/ui/renderers/LiveVideoRenderer.java
Java
apache-2.0
2,132
/* * 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.geode.internal.cache.execute; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.logging.log4j.Logger; import org.apache.geode.InternalGemFireException; import org.apache.geode.SystemFailure; import org.apache.geode.cache.LowMemoryException; import org.apache.geode.cache.TransactionException; import org.apache.geode.cache.client.internal.ProxyCache; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionContext; import org.apache.geode.cache.execute.FunctionException; import org.apache.geode.cache.execute.FunctionInvocationTargetException; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.execute.ResultCollector; import org.apache.geode.cache.execute.ResultSender; import org.apache.geode.cache.query.QueryInvalidException; import org.apache.geode.distributed.internal.DM; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.cache.tier.sockets.ServerConnection; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LocalizedMessage; /** * Abstract implementation of InternalExecution interface. * * @since GemFire 5.8LA * */ public abstract class AbstractExecution implements InternalExecution { private static final Logger logger = LogService.getLogger(); protected boolean isMemberMappedArgument; protected MemberMappedArgument memberMappedArg; protected Object args; protected ResultCollector rc; protected Set filter = new HashSet(); protected boolean hasRoutingObjects; protected volatile boolean isReExecute = false; protected volatile boolean isClientServerMode = false; protected Set<String> failedNodes = new HashSet<String>(); protected boolean isFnSerializationReqd; /*** * yjing The following code is added to get a set of function executing nodes by the data aware * procedure */ protected Collection<InternalDistributedMember> executionNodes = null; public static interface ExecutionNodesListener { public void afterExecutionNodesSet(AbstractExecution execution); public void reset(); } protected ExecutionNodesListener executionNodesListener = null; protected boolean waitOnException = false; protected boolean forwardExceptions = false; protected boolean ignoreDepartedMembers = false; protected ProxyCache proxyCache; private final static ConcurrentHashMap<String, byte[]> idToFunctionAttributes = new ConcurrentHashMap<String, byte[]>(); public static final byte NO_HA_NO_HASRESULT_NO_OPTIMIZEFORWRITE = 0; public static final byte NO_HA_HASRESULT_NO_OPTIMIZEFORWRITE = 2; public static final byte HA_HASRESULT_NO_OPTIMIZEFORWRITE = 3; public static final byte NO_HA_NO_HASRESULT_OPTIMIZEFORWRITE = 4; public static final byte NO_HA_HASRESULT_OPTIMIZEFORWRITE = 6; public static final byte HA_HASRESULT_OPTIMIZEFORWRITE = 7; public static final byte HA_HASRESULT_NO_OPTIMIZEFORWRITE_REEXECUTE = 11; public static final byte HA_HASRESULT_OPTIMIZEFORWRITE_REEXECUTE = 15; public static byte getFunctionState(boolean isHA, boolean hasResult, boolean optimizeForWrite) { if (isHA) { if (hasResult) { if (optimizeForWrite) { return HA_HASRESULT_OPTIMIZEFORWRITE; } else { return HA_HASRESULT_NO_OPTIMIZEFORWRITE; } } return (byte) 1; // ERROR scenario } else { if (hasResult) { if (optimizeForWrite) { return NO_HA_HASRESULT_OPTIMIZEFORWRITE; } else { return NO_HA_HASRESULT_NO_OPTIMIZEFORWRITE; } } else { if (optimizeForWrite) { return NO_HA_NO_HASRESULT_OPTIMIZEFORWRITE; } else { return NO_HA_NO_HASRESULT_NO_OPTIMIZEFORWRITE; } } } } public static byte getReexecuteFunctionState(byte fnState) { if (fnState == HA_HASRESULT_NO_OPTIMIZEFORWRITE) { return HA_HASRESULT_NO_OPTIMIZEFORWRITE_REEXECUTE; } else if (fnState == HA_HASRESULT_OPTIMIZEFORWRITE) { return HA_HASRESULT_OPTIMIZEFORWRITE_REEXECUTE; } throw new InternalGemFireException("Wrong fnState provided."); } protected AbstractExecution() {} protected AbstractExecution(AbstractExecution ae) { if (ae.args != null) { this.args = ae.args; } if (ae.rc != null) { this.rc = ae.rc; } if (ae.memberMappedArg != null) { this.memberMappedArg = ae.memberMappedArg; } this.isMemberMappedArgument = ae.isMemberMappedArgument; this.isClientServerMode = ae.isClientServerMode; if (ae.proxyCache != null) { this.proxyCache = ae.proxyCache; } this.isFnSerializationReqd = ae.isFnSerializationReqd; } protected AbstractExecution(AbstractExecution ae, boolean isReExecute) { this(ae); this.isReExecute = isReExecute; } public boolean isMemberMappedArgument() { return this.isMemberMappedArgument; } public Object getArgumentsForMember(String memberId) { if (!isMemberMappedArgument) { return this.args; } else { return this.memberMappedArg.getArgumentsForMember(memberId); } } public MemberMappedArgument getMemberMappedArgument() { return this.memberMappedArg; } public Object getArguments() { return this.args; } public ResultCollector getResultCollector() { return this.rc; } public Set getFilter() { return this.filter; } public AbstractExecution setIsReExecute() { this.isReExecute = true; if (this.executionNodesListener != null) { this.executionNodesListener.reset(); } return this; } public boolean isReExecute() { return isReExecute; } public Set<String> getFailedNodes() { return this.failedNodes; } public void addFailedNode(String failedNode) { this.failedNodes.add(failedNode); } public void clearFailedNodes() { this.failedNodes.clear(); } public boolean isClientServerMode() { return isClientServerMode; } public boolean isFnSerializationReqd() { return isFnSerializationReqd; } public Collection<InternalDistributedMember> getExecutionNodes() { return this.executionNodes; } public void setRequireExecutionNodes(ExecutionNodesListener listener) { this.executionNodes = Collections.emptySet(); this.executionNodesListener = listener; } public void setExecutionNodes(Set<InternalDistributedMember> nodes) { if (this.executionNodes != null) { this.executionNodes = nodes; if (this.executionNodesListener != null) { this.executionNodesListener.afterExecutionNodesSet(this); } } } public void executeFunctionOnLocalPRNode(final Function fn, final FunctionContext cx, final PartitionedRegionFunctionResultSender sender, DM dm, boolean isTx) { if (dm instanceof DistributionManager && !isTx) { if (ServerConnection.isExecuteFunctionOnLocalNodeOnly().byteValue() == 1) { ServerConnection.executeFunctionOnLocalNodeOnly((byte) 3);// executed locally executeFunctionLocally(fn, cx, sender, dm); if (!sender.isLastResultReceived() && fn.hasResult()) { ((InternalResultSender) sender).setException(new FunctionException( LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT .toString(fn.getId()))); } } else { final DistributionManager newDM = (DistributionManager) dm; newDM.getFunctionExcecutor().execute(new Runnable() { public void run() { executeFunctionLocally(fn, cx, sender, newDM); if (!sender.isLastResultReceived() && fn.hasResult()) { ((InternalResultSender) sender).setException(new FunctionException( LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT .toString(fn.getId()))); } } }); } } else { executeFunctionLocally(fn, cx, sender, dm); if (!sender.isLastResultReceived() && fn.hasResult()) { ((InternalResultSender) sender).setException(new FunctionException( LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT .toString(fn.getId()))); } } } // Bug41118 : in case of lonerDistribuedSystem do local execution through // main thread otherwise give execution to FunctionExecutor from // DistributionManager public void executeFunctionOnLocalNode(final Function<?> fn, final FunctionContext cx, final ResultSender sender, DM dm, final boolean isTx) { if (dm instanceof DistributionManager && !isTx) { final DistributionManager newDM = (DistributionManager) dm; newDM.getFunctionExcecutor().execute(new Runnable() { public void run() { executeFunctionLocally(fn, cx, sender, newDM); if (!((InternalResultSender) sender).isLastResultReceived() && fn.hasResult()) { ((InternalResultSender) sender).setException(new FunctionException( LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT .toString(fn.getId()))); } } }); } else { executeFunctionLocally(fn, cx, sender, dm); if (!((InternalResultSender) sender).isLastResultReceived() && fn.hasResult()) { ((InternalResultSender) sender).setException(new FunctionException( LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT .toString(fn.getId()))); } } } public void executeFunctionLocally(final Function<?> fn, final FunctionContext cx, final ResultSender sender, DM dm) { FunctionStats stats = FunctionStats.getFunctionStats(fn.getId(), dm.getSystem()); try { long start = stats.startTime(); stats.startFunctionExecution(fn.hasResult()); if (logger.isDebugEnabled()) { logger.debug("Executing Function: {} on local node with context: {}", fn.getId(), cx.toString()); } fn.execute(cx); stats.endFunctionExecution(start, fn.hasResult()); } catch (FunctionInvocationTargetException fite) { FunctionException functionException = null; if (fn.isHA()) { functionException = new FunctionException(new InternalFunctionInvocationTargetException(fite.getMessage())); } else { functionException = new FunctionException(fite); } handleException(functionException, fn, cx, sender, dm); } catch (BucketMovedException bme) { FunctionException functionException = null; if (fn.isHA()) { functionException = new FunctionException(new InternalFunctionInvocationTargetException(bme)); } else { functionException = new FunctionException(bme); } handleException(functionException, fn, cx, sender, dm); } catch (VirtualMachineError e) { SystemFailure.initiateFailure(e); throw e; } catch (Throwable t) { SystemFailure.checkFailure(); handleException(t, fn, cx, sender, dm); } } public ResultCollector execute(final String functionName) { if (functionName == null) { throw new FunctionException( LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL .toLocalizedString()); } this.isFnSerializationReqd = false; Function functionObject = FunctionService.getFunction(functionName); if (functionObject == null) { throw new FunctionException( LocalizedStrings.ExecuteFunction_FUNCTION_NAMED_0_IS_NOT_REGISTERED .toLocalizedString(functionName)); } return executeFunction(functionObject); } public ResultCollector execute(Function function) throws FunctionException { if (function == null) { throw new FunctionException( LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL .toLocalizedString()); } if (function.isHA() && !function.hasResult()) { throw new FunctionException( LocalizedStrings.FunctionService_FUNCTION_ATTRIBUTE_MISMATCH.toLocalizedString()); } String id = function.getId(); if (id == null) { throw new IllegalArgumentException( LocalizedStrings.ExecuteFunction_THE_FUNCTION_GET_ID_RETURNED_NULL.toLocalizedString()); } this.isFnSerializationReqd = true; return executeFunction(function); } public void setWaitOnExceptionFlag(boolean waitOnException) { this.setForwardExceptions(waitOnException); this.waitOnException = waitOnException; } public boolean getWaitOnExceptionFlag() { return this.waitOnException; } public void setForwardExceptions(boolean forward) { this.forwardExceptions = forward; } public boolean isForwardExceptions() { return forwardExceptions; } @Override public void setIgnoreDepartedMembers(boolean ignore) { this.ignoreDepartedMembers = ignore; if (ignore) { setWaitOnExceptionFlag(true); } } public boolean isIgnoreDepartedMembers() { return this.ignoreDepartedMembers; } protected abstract ResultCollector executeFunction(Function fn); /** * validates whether a function should execute in presence of transaction and HeapCritical * members. If the function is the first operation in a transaction, bootstraps the function. * * @param function the function * @param targetMembers the set of members the function will be executed on * @throws TransactionException if more than one nodes are targeted within a transaction * @throws LowMemoryException if the set contains a heap critical member */ public abstract void validateExecution(Function function, Set targetMembers); public LocalResultCollector<?, ?> getLocalResultCollector(Function function, final ResultCollector<?, ?> rc) { if (rc instanceof LocalResultCollector) { return (LocalResultCollector) rc; } else { return new LocalResultCollectorImpl(function, rc, this); } } /** * Returns the function attributes defined by the functionId, returns null if no function is found * for the specified functionId * * @param functionId * @return byte[] * @throws FunctionException if functionID passed is null * @since GemFire 6.6 */ public byte[] getFunctionAttributes(String functionId) { if (functionId == null) { throw new FunctionException(LocalizedStrings.FunctionService_0_PASSED_IS_NULL .toLocalizedString("functionId instance ")); } return idToFunctionAttributes.get(functionId); } public void removeFunctionAttributes(String functionId) { idToFunctionAttributes.remove(functionId); } public void addFunctionAttributes(String functionId, byte[] functionAttributes) { idToFunctionAttributes.put(functionId, functionAttributes); } private void handleException(Throwable functionException, final Function fn, final FunctionContext cx, final ResultSender sender, DM dm) { FunctionStats stats = FunctionStats.getFunctionStats(fn.getId(), dm.getSystem()); if (logger.isDebugEnabled()) { logger.debug("Exception occurred on local node while executing Function: {}", fn.getId(), functionException); } stats.endFunctionExecutionWithException(fn.hasResult()); if (fn.hasResult()) { if (waitOnException || forwardExceptions) { if (functionException instanceof FunctionException && functionException.getCause() instanceof QueryInvalidException) { // Handle this exception differently since it can contain // non-serializable objects. // java.io.NotSerializableException: antlr.CommonToken // create a new FunctionException on the original one's message (not cause). functionException = new FunctionException(functionException.getLocalizedMessage()); } sender.lastResult(functionException); } else { ((InternalResultSender) sender).setException(functionException); } } else { logger.warn(LocalizedMessage.create(LocalizedStrings.FunctionService_EXCEPTION_ON_LOCAL_NODE), functionException); } } }
pivotal-amurmann/geode
geode-core/src/main/java/org/apache/geode/internal/cache/execute/AbstractExecution.java
Java
apache-2.0
17,394
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # Copyright 2013 Red Hat, 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. import abc import logging import uuid import six from stevedore import named from oslo.config import cfg from oslo.messaging import serializer as msg_serializer from oslo.utils import timeutils _notifier_opts = [ cfg.MultiStrOpt('notification_driver', default=[], help='Driver or drivers to handle sending notifications.'), cfg.ListOpt('notification_topics', default=['notifications', ], deprecated_name='topics', deprecated_group='rpc_notifier2', help='AMQP topic used for OpenStack notifications.'), ] _LOG = logging.getLogger(__name__) @six.add_metaclass(abc.ABCMeta) class _Driver(object): def __init__(self, conf, topics, transport): self.conf = conf self.topics = topics self.transport = transport @abc.abstractmethod def notify(self, ctxt, msg, priority, retry): pass class Notifier(object): """Send notification messages. The Notifier class is used for sending notification messages over a messaging transport or other means. Notification messages follow the following format:: {'message_id': six.text_type(uuid.uuid4()), 'publisher_id': 'compute.host1', 'timestamp': timeutils.utcnow(), 'priority': 'WARN', 'event_type': 'compute.create_instance', 'payload': {'instance_id': 12, ... }} A Notifier object can be instantiated with a transport object and a publisher ID: notifier = messaging.Notifier(get_transport(CONF), 'compute') and notifications are sent via drivers chosen with the notification_driver config option and on the topics chosen with the notification_topics config option. Alternatively, a Notifier object can be instantiated with a specific driver or topic:: notifier = notifier.Notifier(RPC_TRANSPORT, 'compute.host', driver='messaging', topic='notifications') Notifier objects are relatively expensive to instantiate (mostly the cost of loading notification drivers), so it is possible to specialize a given Notifier object with a different publisher id using the prepare() method:: notifier = notifier.prepare(publisher_id='compute') notifier.info(ctxt, event_type, payload) """ def __init__(self, transport, publisher_id=None, driver=None, topic=None, serializer=None, retry=None): """Construct a Notifier object. :param transport: the transport to use for sending messages :type transport: oslo.messaging.Transport :param publisher_id: field in notifications sent, for example 'compute.host1' :type publisher_id: str :param driver: a driver to lookup from oslo.messaging.notify.drivers :type driver: str :param topic: the topic which to send messages on :type topic: str :param serializer: an optional entity serializer :type serializer: Serializer :param retry: an connection retries configuration None or -1 means to retry forever 0 means no retry N means N retries :type retry: int """ transport.conf.register_opts(_notifier_opts) self.transport = transport self.publisher_id = publisher_id self.retry = retry self._driver_names = ([driver] if driver is not None else transport.conf.notification_driver) self._topics = ([topic] if topic is not None else transport.conf.notification_topics) self._serializer = serializer or msg_serializer.NoOpSerializer() self._driver_mgr = named.NamedExtensionManager( 'oslo.messaging.notify.drivers', names=self._driver_names, invoke_on_load=True, invoke_args=[transport.conf], invoke_kwds={ 'topics': self._topics, 'transport': self.transport, } ) _marker = object() def prepare(self, publisher_id=_marker, retry=_marker): """Return a specialized Notifier instance. Returns a new Notifier instance with the supplied publisher_id. Allows sending notifications from multiple publisher_ids without the overhead of notification driver loading. :param publisher_id: field in notifications sent, for example 'compute.host1' :type publisher_id: str :param retry: an connection retries configuration None or -1 means to retry forever 0 means no retry N means N retries :type retry: int """ return _SubNotifier._prepare(self, publisher_id, retry=retry) def _notify(self, ctxt, event_type, payload, priority, publisher_id=None, retry=None): payload = self._serializer.serialize_entity(ctxt, payload) ctxt = self._serializer.serialize_context(ctxt) msg = dict(message_id=six.text_type(uuid.uuid4()), publisher_id=publisher_id or self.publisher_id, event_type=event_type, priority=priority, payload=payload, timestamp=six.text_type(timeutils.utcnow())) def do_notify(ext): try: ext.obj.notify(ctxt, msg, priority, retry or self.retry) except Exception as e: _LOG.exception("Problem '%(e)s' attempting to send to " "notification system. Payload=%(payload)s", dict(e=e, payload=payload)) if self._driver_mgr.extensions: self._driver_mgr.map(do_notify) def audit(self, ctxt, event_type, payload): """Send a notification at audit level. :param ctxt: a request context dict :type ctxt: dict :param event_type: describes the event, for example 'compute.create_instance' :type event_type: str :param payload: the notification payload :type payload: dict :raises: MessageDeliveryFailure """ self._notify(ctxt, event_type, payload, 'AUDIT') def debug(self, ctxt, event_type, payload): """Send a notification at debug level. :param ctxt: a request context dict :type ctxt: dict :param event_type: describes the event, for example 'compute.create_instance' :type event_type: str :param payload: the notification payload :type payload: dict :raises: MessageDeliveryFailure """ self._notify(ctxt, event_type, payload, 'DEBUG') def info(self, ctxt, event_type, payload): """Send a notification at info level. :param ctxt: a request context dict :type ctxt: dict :param event_type: describes the event, for example 'compute.create_instance' :type event_type: str :param payload: the notification payload :type payload: dict :raises: MessageDeliveryFailure """ self._notify(ctxt, event_type, payload, 'INFO') def warn(self, ctxt, event_type, payload): """Send a notification at warning level. :param ctxt: a request context dict :type ctxt: dict :param event_type: describes the event, for example 'compute.create_instance' :type event_type: str :param payload: the notification payload :type payload: dict :raises: MessageDeliveryFailure """ self._notify(ctxt, event_type, payload, 'WARN') warning = warn def error(self, ctxt, event_type, payload): """Send a notification at error level. :param ctxt: a request context dict :type ctxt: dict :param event_type: describes the event, for example 'compute.create_instance' :type event_type: str :param payload: the notification payload :type payload: dict :raises: MessageDeliveryFailure """ self._notify(ctxt, event_type, payload, 'ERROR') def critical(self, ctxt, event_type, payload): """Send a notification at critical level. :param ctxt: a request context dict :type ctxt: dict :param event_type: describes the event, for example 'compute.create_instance' :type event_type: str :param payload: the notification payload :type payload: dict :raises: MessageDeliveryFailure """ self._notify(ctxt, event_type, payload, 'CRITICAL') def sample(self, ctxt, event_type, payload): """Send a notification at sample level. Sample notifications are for high-frequency events that typically contain small payloads. eg: "CPU = 70%" Not all drivers support the sample level (log, for example) so these could be dropped. :param ctxt: a request context dict :type ctxt: dict :param event_type: describes the event, for example 'compute.create_instance' :type event_type: str :param payload: the notification payload :type payload: dict :raises: MessageDeliveryFailure """ self._notify(ctxt, event_type, payload, 'SAMPLE') class _SubNotifier(Notifier): _marker = Notifier._marker def __init__(self, base, publisher_id, retry): self._base = base self.transport = base.transport self.publisher_id = publisher_id self.retry = retry self._serializer = self._base._serializer self._driver_mgr = self._base._driver_mgr def _notify(self, ctxt, event_type, payload, priority): super(_SubNotifier, self)._notify(ctxt, event_type, payload, priority) @classmethod def _prepare(cls, base, publisher_id=_marker, retry=_marker): if publisher_id is cls._marker: publisher_id = base.publisher_id if retry is cls._marker: retry = base.retry return cls(base, publisher_id, retry=retry)
eayunstack/oslo.messaging
oslo/messaging/notify/notifier.py
Python
apache-2.0
11,163
// Copyright 2015 The LUCI Authors. // // 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 authdb import ( "fmt" "net" "go.chromium.org/luci/auth/identity" "go.chromium.org/luci/server/auth/service/protocol" ) // validateAuthDB returns nil if AuthDB looks correct. func validateAuthDB(db *protocol.AuthDB) error { groups := make(map[string]*protocol.AuthGroup, len(db.Groups)) for _, g := range db.Groups { groups[g.Name] = g } for name := range groups { if err := validateAuthGroup(name, groups); err != nil { return err } } for _, wl := range db.IpWhitelists { if err := validateIPWhitelist(wl); err != nil { return fmt.Errorf("auth: bad IP whitlist %q - %s", wl.Name, err) } } if db.Realms != nil { perms := uint32(len(db.Realms.Permissions)) conds := uint32(len(db.Realms.Conditions)) for _, realm := range db.Realms.Realms { if err := validateRealm(realm, perms, conds); err != nil { return fmt.Errorf("auth: bad realm %q - %s", realm.Name, err) } } } return nil } // validateAuthGroup returns nil if AuthGroup looks correct. func validateAuthGroup(name string, groups map[string]*protocol.AuthGroup) error { g := groups[name] for _, ident := range g.Members { if _, err := identity.MakeIdentity(ident); err != nil { return fmt.Errorf("auth: invalid identity %q in group %q - %s", ident, name, err) } } for _, glob := range g.Globs { if _, err := identity.MakeGlob(glob); err != nil { return fmt.Errorf("auth: invalid glob %q in group %q - %s", glob, name, err) } } for _, nested := range g.Nested { if groups[nested] == nil { return fmt.Errorf("auth: unknown nested group %q in group %q", nested, name) } } if cycle := findGroupCycle(name, groups); len(cycle) != 0 { return fmt.Errorf("auth: dependency cycle found - %v", cycle) } return nil } // findGroupCycle searches for a group dependency cycle that contains group // `name`. Returns list of groups that form the cycle if found, empty list // if no cycles. Unknown groups are considered empty. func findGroupCycle(name string, groups map[string]*protocol.AuthGroup) []string { // Set of groups that are completely explored (all subtree is traversed). visited := map[string]bool{} // Stack of groups that are being explored now. In case a cycle is detected // it would contain that cycle. var visiting []string // Recursively explores `group` subtree, returns true if finds a cycle. var visit func(string) bool visit = func(group string) bool { g := groups[group] if g == nil { visited[group] = true return false } visiting = append(visiting, group) for _, nested := range g.GetNested() { // Cross edge. Can happen in diamond-like graph, not a cycle. if visited[nested] { continue } // Is `group` references its own ancestor -> cycle is detected. for _, v := range visiting { if v == nested { return true } } // Explore subtree. if visit(nested) { return true } } visiting = visiting[:len(visiting)-1] visited[group] = true return false } visit(name) return visiting // will contain a cycle, if any } // validateIPWhitelist checks IPs in the whitelist are parsable. func validateIPWhitelist(wl *protocol.AuthIPWhitelist) error { for _, subnet := range wl.Subnets { if _, _, err := net.ParseCIDR(subnet); err != nil { return fmt.Errorf("bad subnet %q - %s", subnet, err) } } return nil } // validateRealm checks indexes of permissions and conditions in bindings. func validateRealm(r *protocol.Realm, permsCount, condsCount uint32) error { for _, b := range r.Bindings { for _, perm := range b.Permissions { if perm >= permsCount { return fmt.Errorf("referencing out-of-bounds permission: %d>=%d", perm, permsCount) } } for _, cond := range b.Conditions { if cond >= condsCount { return fmt.Errorf("referencing out-of-bounds condition: %d>=%d", cond, condsCount) } } } return nil }
luci/luci-go
server/auth/authdb/validation.go
GO
apache-2.0
4,474
/* * Minimalist Object Storage, (C) 2014 Minio, 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. */ // Minio - Object storage inspired by Amazon S3 and Facebook Haystack. package main
flandr/minio
doc.go
GO
apache-2.0
701
#!/usr/bin/env python # Copyright (c) 2015 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """pylint error checking.""" from __future__ import print_function import json import os import re import sys from pylint import lint from pylint.reporters import text from six.moves import cStringIO as StringIO # enabled checks # http://pylint-messages.wikidot.com/all-codes ENABLED_CODES=( # refactor category "R0801", "R0911", "R0912", "R0913", "R0914", "R0915", # warning category "W0612", "W0613", "W0703", # convention category "C1001") KNOWN_PYLINT_EXCEPTIONS_FILE = "tools/pylint_exceptions" class LintOutput(object): _cached_filename = None _cached_content = None def __init__(self, filename, lineno, line_content, code, message, lintoutput): self.filename = filename self.lineno = lineno self.line_content = line_content self.code = code self.message = message self.lintoutput = lintoutput @classmethod def get_duplicate_code_location(cls, remaining_lines): module, lineno = remaining_lines.pop(0)[2:].split(":") filename = module.replace(".", os.sep) + ".py" return filename, int(lineno) @classmethod def get_line_content(cls, filename, lineno): if cls._cached_filename != filename: with open(filename) as f: cls._cached_content = list(f.readlines()) cls._cached_filename = filename # find first non-empty line lineno -= 1 while True: line_content = cls._cached_content[lineno].rstrip() lineno +=1 if line_content: return line_content @classmethod def from_line(cls, line, remaining_lines): m = re.search(r"(\S+):(\d+): \[(\S+)(, \S*)?] (.*)", line) if not m: return None matched = m.groups() filename, lineno, code, message = (matched[0], int(matched[1]), matched[2], matched[-1]) # duplicate code output needs special handling if "duplicate-code" in code: filename, lineno = cls.get_duplicate_code_location(remaining_lines) # fixes incorrectly reported file path line = line.replace(matched[0], filename) line_content = cls.get_line_content(filename, lineno) return cls(filename, lineno, line_content, code, message, line.rstrip()) @classmethod def from_msg_to_dict(cls, msg): """From the output of pylint msg, to a dict, where each key is a unique error identifier, value is a list of LintOutput """ result = {} lines = msg.splitlines() while lines: line = lines.pop(0) obj = cls.from_line(line, lines) if not obj: continue key = obj.key() if key not in result: result[key] = [] result[key].append(obj) return result def key(self): return self.message, self.line_content.strip() def json(self): return json.dumps(self.__dict__) def review_str(self): return ("File %(filename)s\nLine %(lineno)d:%(line_content)s\n" "%(code)s: %(message)s" % self.__dict__) class ErrorKeys(object): @classmethod def print_json(cls, errors, output=sys.stdout): print("# automatically generated by tools/lintstack.py", file=output) for i in sorted(errors.keys()): print(json.dumps(i), file=output) @classmethod def from_file(cls, filename): keys = set() for line in open(filename): if line and line[0] != "#": d = json.loads(line) keys.add(tuple(d)) return keys def run_pylint(): buff = StringIO() reporter = text.ParseableTextReporter(output=buff) args = ["-rn", "--disable=all", "--enable=" + ",".join(ENABLED_CODES),"murano"] lint.Run(args, reporter=reporter, exit=False) val = buff.getvalue() buff.close() return val def generate_error_keys(msg=None): print("Generating", KNOWN_PYLINT_EXCEPTIONS_FILE) if msg is None: msg = run_pylint() errors = LintOutput.from_msg_to_dict(msg) with open(KNOWN_PYLINT_EXCEPTIONS_FILE, "w") as f: ErrorKeys.print_json(errors, output=f) def validate(newmsg=None): print("Loading", KNOWN_PYLINT_EXCEPTIONS_FILE) known = ErrorKeys.from_file(KNOWN_PYLINT_EXCEPTIONS_FILE) if newmsg is None: print("Running pylint. Be patient...") newmsg = run_pylint() errors = LintOutput.from_msg_to_dict(newmsg) print() print("Unique errors reported by pylint: was %d, now %d." % (len(known), len(errors))) passed = True for err_key, err_list in errors.items(): for err in err_list: if err_key not in known: print() print(err.lintoutput) print(err.review_str()) passed = False if passed: print("Congrats! pylint check passed.") redundant = known - set(errors.keys()) if redundant: print("Extra credit: some known pylint exceptions disappeared.") for i in sorted(redundant): print(json.dumps(i)) print("Consider regenerating the exception file if you will.") else: print() print("Please fix the errors above. If you believe they are false " "positives, run 'tools/lintstack.py generate' to overwrite.") sys.exit(1) def usage(): print("""Usage: tools/lintstack.py [generate|validate] To generate pylint_exceptions file: tools/lintstack.py generate To validate the current commit: tools/lintstack.py """) def main(): option = "validate" if len(sys.argv) > 1: option = sys.argv[1] if option == "generate": generate_error_keys() elif option == "validate": validate() else: usage() if __name__ == "__main__": main()
chenyujie/hybrid-murano
tools/lintstack.py
Python
apache-2.0
6,700
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skylarkbuildapi.repository; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory; /** A Skylark structure to deliver information about the system we are running on. */ @SkylarkModule( name = "repository_os", category = SkylarkModuleCategory.NONE, doc = "Various data about the current platform Bazel is running on." ) public interface SkylarkOSApi { @SkylarkCallable(name = "environ", structField = true, doc = "The list of environment variables.") public ImmutableMap<String, String> getEnvironmentVariables(); @SkylarkCallable( name = "name", structField = true, doc = "A string identifying the current system Bazel is running on." ) public String getName(); }
dropbox/bazel
src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/SkylarkOSApi.java
Java
apache-2.0
1,570
package org.hl7.fhir.dstu3.model; /* Copyright (c) 2011+, HL7, Inc. 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 name of HL7 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. */ // Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0 import java.util.*; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.dstu3.model.Enumerations.*; import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.api.annotation.SearchParamDefinition; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.ChildOrder; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.Block; import org.hl7.fhir.instance.model.api.*; import org.hl7.fhir.exceptions.FHIRException; /** * This is the base resource type for everything. */ public abstract class Resource extends BaseResource implements IAnyResource { /** * The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes. */ @Child(name = "id", type = {IdType.class}, order=0, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Logical id of this artifact", formalDefinition="The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes." ) protected IdType id; /** * The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource. */ @Child(name = "meta", type = {Meta.class}, order=1, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Metadata about the resource", formalDefinition="The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource." ) protected Meta meta; /** * A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. */ @Child(name = "implicitRules", type = {UriType.class}, order=2, min=0, max=1, modifier=true, summary=true) @Description(shortDefinition="A set of rules under which this content was created", formalDefinition="A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content." ) protected UriType implicitRules; /** * The base language in which the resource is written. */ @Child(name = "language", type = {CodeType.class}, order=3, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Language of the resource content", formalDefinition="The base language in which the resource is written." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/languages") protected CodeType language; private static final long serialVersionUID = -559462759L; /** * Constructor */ public Resource() { super(); } /** * @return {@link #id} (The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.). This is the underlying object with id, value and extensions. The accessor "getId" gives direct access to the value */ public IdType getIdElement() { if (this.id == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Resource.id"); else if (Configuration.doAutoCreate()) this.id = new IdType(); // bb return this.id; } public boolean hasIdElement() { return this.id != null && !this.id.isEmpty(); } public boolean hasId() { return this.id != null && !this.id.isEmpty(); } /** * @param value {@link #id} (The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.). This is the underlying object with id, value and extensions. The accessor "getId" gives direct access to the value */ public Resource setIdElement(IdType value) { this.id = value; return this; } /** * @return The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes. */ public String getId() { return this.id == null ? null : this.id.getValue(); } /** * @param value The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes. */ public Resource setId(String value) { if (Utilities.noString(value)) this.id = null; else { if (this.id == null) this.id = new IdType(); this.id.setValue(value); } return this; } /** * @return {@link #meta} (The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource.) */ public Meta getMeta() { if (this.meta == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Resource.meta"); else if (Configuration.doAutoCreate()) this.meta = new Meta(); // cc return this.meta; } public boolean hasMeta() { return this.meta != null && !this.meta.isEmpty(); } /** * @param value {@link #meta} (The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource.) */ public Resource setMeta(Meta value) { this.meta = value; return this; } /** * @return {@link #implicitRules} (A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.). This is the underlying object with id, value and extensions. The accessor "getImplicitRules" gives direct access to the value */ public UriType getImplicitRulesElement() { if (this.implicitRules == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Resource.implicitRules"); else if (Configuration.doAutoCreate()) this.implicitRules = new UriType(); // bb return this.implicitRules; } public boolean hasImplicitRulesElement() { return this.implicitRules != null && !this.implicitRules.isEmpty(); } public boolean hasImplicitRules() { return this.implicitRules != null && !this.implicitRules.isEmpty(); } /** * @param value {@link #implicitRules} (A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.). This is the underlying object with id, value and extensions. The accessor "getImplicitRules" gives direct access to the value */ public Resource setImplicitRulesElement(UriType value) { this.implicitRules = value; return this; } /** * @return A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. */ public String getImplicitRules() { return this.implicitRules == null ? null : this.implicitRules.getValue(); } /** * @param value A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. */ public Resource setImplicitRules(String value) { if (Utilities.noString(value)) this.implicitRules = null; else { if (this.implicitRules == null) this.implicitRules = new UriType(); this.implicitRules.setValue(value); } return this; } /** * @return {@link #language} (The base language in which the resource is written.). This is the underlying object with id, value and extensions. The accessor "getLanguage" gives direct access to the value */ public CodeType getLanguageElement() { if (this.language == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Resource.language"); else if (Configuration.doAutoCreate()) this.language = new CodeType(); // bb return this.language; } public boolean hasLanguageElement() { return this.language != null && !this.language.isEmpty(); } public boolean hasLanguage() { return this.language != null && !this.language.isEmpty(); } /** * @param value {@link #language} (The base language in which the resource is written.). This is the underlying object with id, value and extensions. The accessor "getLanguage" gives direct access to the value */ public Resource setLanguageElement(CodeType value) { this.language = value; return this; } /** * @return The base language in which the resource is written. */ public String getLanguage() { return this.language == null ? null : this.language.getValue(); } /** * @param value The base language in which the resource is written. */ public Resource setLanguage(String value) { if (Utilities.noString(value)) this.language = null; else { if (this.language == null) this.language = new CodeType(); this.language.setValue(value); } return this; } protected void listChildren(List<Property> childrenList) { childrenList.add(new Property("id", "id", "The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.", 0, java.lang.Integer.MAX_VALUE, id)); childrenList.add(new Property("meta", "Meta", "The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource.", 0, java.lang.Integer.MAX_VALUE, meta)); childrenList.add(new Property("implicitRules", "uri", "A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.", 0, java.lang.Integer.MAX_VALUE, implicitRules)); childrenList.add(new Property("language", "code", "The base language in which the resource is written.", 0, java.lang.Integer.MAX_VALUE, language)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case 3355: /*id*/ return this.id == null ? new Base[0] : new Base[] {this.id}; // IdType case 3347973: /*meta*/ return this.meta == null ? new Base[0] : new Base[] {this.meta}; // Meta case -961826286: /*implicitRules*/ return this.implicitRules == null ? new Base[0] : new Base[] {this.implicitRules}; // UriType case -1613589672: /*language*/ return this.language == null ? new Base[0] : new Base[] {this.language}; // CodeType default: return super.getProperty(hash, name, checkValid); } } @Override public void setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case 3355: // id this.id = castToId(value); // IdType break; case 3347973: // meta this.meta = castToMeta(value); // Meta break; case -961826286: // implicitRules this.implicitRules = castToUri(value); // UriType break; case -1613589672: // language this.language = castToCode(value); // CodeType break; default: super.setProperty(hash, name, value); } } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("id")) this.id = castToId(value); // IdType else if (name.equals("meta")) this.meta = castToMeta(value); // Meta else if (name.equals("implicitRules")) this.implicitRules = castToUri(value); // UriType else if (name.equals("language")) this.language = castToCode(value); // CodeType else super.setProperty(name, value); } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case 3355: throw new FHIRException("Cannot make property id as it is not a complex type"); // IdType case 3347973: return getMeta(); // Meta case -961826286: throw new FHIRException("Cannot make property implicitRules as it is not a complex type"); // UriType case -1613589672: throw new FHIRException("Cannot make property language as it is not a complex type"); // CodeType default: return super.makeProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("id")) { throw new FHIRException("Cannot call addChild on a primitive type Resource.id"); } else if (name.equals("meta")) { this.meta = new Meta(); return this.meta; } else if (name.equals("implicitRules")) { throw new FHIRException("Cannot call addChild on a primitive type Resource.implicitRules"); } else if (name.equals("language")) { throw new FHIRException("Cannot call addChild on a primitive type Resource.language"); } else return super.addChild(name); } public String fhirType() { return "Resource"; } public abstract Resource copy(); public void copyValues(Resource dst) { dst.id = id == null ? null : id.copy(); dst.meta = meta == null ? null : meta.copy(); dst.implicitRules = implicitRules == null ? null : implicitRules.copy(); dst.language = language == null ? null : language.copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof Resource)) return false; Resource o = (Resource) other; return compareDeep(id, o.id, true) && compareDeep(meta, o.meta, true) && compareDeep(implicitRules, o.implicitRules, true) && compareDeep(language, o.language, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof Resource)) return false; Resource o = (Resource) other; return compareValues(id, o.id, true) && compareValues(implicitRules, o.implicitRules, true) && compareValues(language, o.language, true) ; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(id, meta, implicitRules , language); } @Override public String getIdBase() { return getId(); } @Override public void setIdBase(String value) { setId(value); } public abstract ResourceType getResourceType(); }
Gaduo/hapi-fhir
hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Resource.java
Java
apache-2.0
17,114
/** * Copyright 2013 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.sor.client; import org.n52.sor.ISorRequest.SorMatchingType; import org.n52.sor.OwsExceptionReport; import org.n52.sor.PropertiesManager; import org.n52.sor.util.XmlTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.x52North.sor.x031.GetMatchingDefinitionsRequestDocument; import org.x52North.sor.x031.GetMatchingDefinitionsRequestDocument.GetMatchingDefinitionsRequest; /** * @author Jan Schulte, Daniel Nüst * */ public class GetMatchingDefinitionsBean extends AbstractBean { private static Logger log = LoggerFactory.getLogger(GetMatchingDefinitionsBean.class); private String inputURI = ""; private String matchingTypeString; private int searchDepth; @Override public void buildRequest() { GetMatchingDefinitionsRequestDocument requestDoc = GetMatchingDefinitionsRequestDocument.Factory.newInstance(); GetMatchingDefinitionsRequest request = requestDoc.addNewGetMatchingDefinitionsRequest(); request.setService(PropertiesManager.getInstance().getService()); request.setVersion(PropertiesManager.getInstance().getServiceVersion()); // inputURI if ( !this.inputURI.isEmpty()) { request.setInputURI(this.inputURI); } else { this.requestString = "Please choose an input URI!"; return; } // matchingType try { request.setMatchingType(SorMatchingType.getSorMatchingType(this.matchingTypeString).getSchemaMatchingType()); } catch (OwsExceptionReport e) { log.warn("Matching type NOT supported!"); this.requestString = "The matching type is not supported!\n\n" + e.getDocument(); } // searchDepth request.setSearchDepth(this.searchDepth); if ( !requestDoc.validate()) { log.warn("Request is NOT valid, service may return error!\n" + XmlTools.validateAndIterateErrors(requestDoc)); } this.requestString = requestDoc.toString(); } public String getInputURI() { return this.inputURI; } public String getMatchingTypeString() { return this.matchingTypeString; } public int getSearchDepth() { return this.searchDepth; } public void setInputURI(String inputURI) { this.inputURI = inputURI; } public void setMatchingTypeString(String matchingTypeString) { this.matchingTypeString = matchingTypeString; } public void setSearchDepth(int searchDepth) { this.searchDepth = searchDepth; } }
52North/OpenSensorSearch
sor-common/src/main/java/org/n52/sor/client/GetMatchingDefinitionsBean.java
Java
apache-2.0
3,262
/* * Copyright 2016 e-UCM (http://www.e-ucm.es/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * This project has received funding from the European Union’s Horizon * 2020 research and innovation programme under grant agreement No 644187. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 (link is external) * * 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. */ 'use strict'; var express = require('express'), authentication = require('../util/authentication'), router = express.Router(), async = require('async'), applicationIdRoute = '/:applicationId', unselectedFields = '-__v', removeFields = ['__v']; var Validator = require('jsonschema').Validator, v = new Validator(); var appSchema = { id: '/AppSchema', type: 'object', properties: { _id: {type: 'string'}, name: { type: 'string'}, prefix: { type: 'string'}, host: { type: 'string'}, owner: { type: 'string'}, roles: { type: 'array', items: { type: 'object', properties: { roles: { anyOf: [{ type: 'array', items: {type: 'string'} },{ type: 'string' }] }, allows: { type: 'array', items: {$ref: '/AllowsSchema'} } } } }, autoroles: { type: 'array', items: {type: 'string'} }, routes: { type: 'array', items: {type: 'string'} }, anonymous: { anyOf: [{ type: 'array', items: {type: 'string'} }, { type: 'string' }] }, look: { type: 'array', items: {$ref: '/LookSchema'} } }, additionalProperties: false }; var allowsSchema = { id: '/AllowsSchema', type: 'object', properties: { resources: { type: 'array', items: {type: 'string'} }, permissions: { type: 'array', items: {type: 'string'} } } }; var lookSchema = { id: '/LookSchema', type: 'object', properties: { url: { type: 'string'}, key: { type: 'string'}, methods: { type: 'array', items: {type: 'string'} }, permissions: {type: 'object'} }, additionalProperties: false }; var putLookSchema = { id: '/PutLookSchema', type: 'object', properties: { key: {type: 'string'}, users: { type: 'array', items: {type: 'string'} }, resources: { type: 'array', items: {type: 'string'} }, methods: { type: 'array', items: {type: 'string'} }, url: {type: 'string'} }, additionalProperties: false }; v.addSchema(allowsSchema, '/AllowsSchema'); v.addSchema(lookSchema, '/LookSchema'); v.addSchema(appSchema, '/AppSchema'); v.addSchema(putLookSchema, '/PutLookSchema'); /** * @api {get} /applications Returns all the registered applications. * @apiName GetApplications * @apiGroup Applications * * @apiParam {String} [fields] The fields to be populated in the resulting objects. * An empty string will return the complete document. * @apiParam {String} [sort=_id] Place - before the field for a descending sort. * @apiParam {Number} [limit=20] * @apiParam {Number} [page=1] * * @apiPermission admin * * @apiParamExample {json} Request-Example: * { * "fields": "_id name prefix host anonymous timeCreated", * "sort": "-name", * "limit": 20, * "page": 1 * } * * @apiParamExample {json} Request-Example: * { * "fields": "", * "sort": "name", * "limit": 20, * "page": 1 * } * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "data": [ * { * "_id": "559a447831b7acec185bf513", * "name": "Gleaner App.", * "prefix": "gleaner", * "host": "localhost:3300", * "owner": "root", * "autoroles": [ * "student", * "teacher, * "developer" * ], * "timeCreated": "2015-07-06T09:03:52.636Z", * "routes": [ * "gleaner/games", * "gleaner/activities", * "gleaner/classes" * ], * "anonymous": [ * "/collector", * "/env" * ], * "look":[ * { * "url": "route/get", * "permissions: { * "user1: [ * "dashboard1", * "dashboard2" * ], * "user2: [ * "dashboard1", * "dashboard3" * ] * } * } * ] * }], * "pages": { * "current": 1, * "prev": 0, * "hasPrev": false, * "next": 2, * "hasNext": false, * "total": 1 * }, * "items": { * "limit": 20, * "begin": 1, * "end": 1, * "total": 1 * } * } * */ router.get('/', authentication.authorized, function (req, res, next) { var query = {}; var fields = req.body.fields || ''; var sort = req.body.sort || '_id'; var limit = req.body.limit || 20; var page = req.body.page || 1; req.app.db.model('application').pagedFind(query, fields, removeFields, sort, limit, page, function (err, results) { if (err) { return next(err); } res.json(results); }); }); /** * @api {post} /applications Register a new application, if an application with the same prefix already exists it will be overridden with the new values. * @apiName PostApplications * @apiGroup Applications * * @apiParam {String} prefix Application prefix. * @apiParam {String} host Application host. * @apiParam {String[]} [anonymous Express-like] routes for whom unidentified (anonymous) requests will be forwarded anyway. * @apiParam {String[]} [autoroles] Roles that the application use. * @apiParam {Object[]} [look] Allow access to routes for specific users. Key field identify specific field that the algorithm need look to * allow the access. In the next example, the user1 can use the route POST "rout/get" to see results if the req.body * contains the value "dashboard1" in "docs._id" field. * "look":[{"url": "route/get", * "permissions: { "user1: ["dashboard1"] }, * "key": "docs._id", * "_id": "59ce615e3ef2df4d94f734fc", * "methods": ["post"]}] * @apiParam {String[]} [routes] All the applications routes that are not anonymous * @apiParam {String} [owner] The (user) owner of the application * * @apiPermission admin * * @apiParamExample {json} Request-Example: * { * "name": "Gleaner", * "prefix" : "gleaner", * "host" : "localhost:3300", * "autoroles": [ * "student", * "teacher, * "developer" * ], * "look":[ * { * "url": "route/get", * "permissions: { * "user1: [ * "dashboard1", * "dashboard2" * ], * "user2: [ * "dashboard1", * "dashboard3" * ] * }, * "key": "docs._id", * "_id": "59ce615e3ef2df4d94f734fc", * "methods": [ * "post", * "put" * ] * } * ] * "anonymous": [ * "/collector", * "/env" * ], * "routes": [ * "gleaner/games", * "gleaner/activities", * "gleaner/classes" * ], * "owner": "root" * } * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [ * "/collector", * "/env" * ], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) PrefixRequired Prefix required!. * * @apiError(400) HostRequired Host required!. * */ router.post('/', authentication.authorized, function (req, res, next) { async.auto({ validate: function (done) { var err; if (!req.body.prefix) { err = new Error('Prefix required!'); return done(err); } if (!req.body.host) { err = new Error('Host required!'); return done(err); } var validationObj = v.validate(req.body, appSchema); if (validationObj.errors && validationObj.errors.length > 0) { err = new Error('Bad format: ' + validationObj.errors[0]); return done(err); } done(); }, roles: ['validate', function (done) { var rolesArray = req.body.roles; var routes = []; if (rolesArray) { rolesArray.forEach(function (role) { role.allows.forEach(function (allow) { var resources = allow.resources; for (var i = 0; i < resources.length; i++) { resources[i] = req.body.prefix + resources[i]; if (routes.indexOf(resources[i]) === -1) { routes.push(resources[i]); } } }); }); req.app.acl.allow(rolesArray, function (err) { if (err) { return done(err); } return done(null, routes); }); } else { done(null, routes); } }], application: ['roles', function (done, results) { var ApplicationModel = req.app.db.model('application'); ApplicationModel.create({ name: req.body.name || '', prefix: req.body.prefix, host: req.body.host, autoroles: req.body.autoroles, look: req.body.look || [], anonymous: req.body.anonymous || [], routes: results.roles, owner: req.user.username }, done); }] }, function (err, results) { if (err) { err.status = 400; return next(err); } var application = results.application; res.json(application); }); }); /** * @api {get} /applications/prefix/:prefix Gets the application information. * @apiName GetApplication * @apiGroup Applications * * @apiParam {String} applicationId Application id. * * @apiPermission admin * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "name": "My App Name", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) ApplicationNotFound No application with the given user id exists. * */ router.get('/prefix/:prefix', authentication.authorized, function (req, res, next) { req.app.db.model('application').findByPrefix(req.params.prefix).select(unselectedFields).exec(function (err, application) { if (err) { return next(err); } if (!application) { err = new Error('No application with the given application prefix exists.'); err.status = 400; return next(err); } res.json(application); }); }); function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * @api {get} /applications/:applicationId Gets the application information. * @apiName GetApplication * @apiGroup Applications * * @apiParam {String} applicationId Application id. * * @apiPermission admin * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "name": "My App Name", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) ApplicationNotFound No application with the given user id exists. * */ router.get(applicationIdRoute, authentication.authorized, function (req, res, next) { var applicationId = req.params.applicationId || ''; req.app.db.model('application').findById(applicationId).select(unselectedFields).exec(function (err, application) { if (err) { return next(err); } if (!application) { err = new Error('No application with the given application id exists.'); err.status = 400; return next(err); } res.json(application); }); }); /** * @api {put} /applications/:applicationId Changes the application values. * @apiName PutApplication * @apiGroup Applications * * @apiParam {String} applicationId ApplicationId id. * @apiParam {String} name The new name. * @apiParam {String} prefix Application prefix. * @apiParam {String} host Application host. * @apiParam {String[]} [anonymous] Express-like routes for whom unidentified (anonymous) requests will be forwarded anyway. * The routes from this array will be added only if they're not present yet. * @apiParam {Object[]} [look] Allow access to routes for specific users. * @apiParam {String[]} [routes] All the applications routes that are not anonymous * * @apiPermission admin * * @apiParamExample {json} Request-Example: * { * "name": "Gleaner App." * } * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "name": "Gleaner App.", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) InvalidApplicationId You must provide a valid application id. * * @apiError(400) ApplicationNotFound No application with the given application id exists. * */ router.put(applicationIdRoute, authentication.authorized, function (req, res, next) { if (!req.params.applicationId) { var err = new Error('You must provide a valid application id'); err.status = 400; return next(err); } var validationObj = v.validate(req.body, appSchema); if (validationObj.errors && validationObj.errors.length > 0) { var errVal = new Error('Bad format: ' + validationObj.errors[0]); errVal.status = 400; return next(errVal); } var applicationId = req.params.applicationId || ''; var query = { _id: applicationId, owner: req.user.username }; var update = { $set: {} }; if (req.body.name) { update.$set.name = req.body.name; } if (req.body.prefix) { update.$set.prefix = req.body.prefix; } if (req.body.host) { update.$set.host = req.body.host; } if (isArray(req.body.look)) { update.$addToSet = {look: {$each: req.body.look.filter(Boolean)}}; } if (isArray(req.body.anonymous)) { update.$addToSet = {anonymous: {$each: req.body.anonymous.filter(Boolean)}}; } var options = { new: true, /* Since Mongoose 4.0.0 we can run validators (e.g. isURL validator for the host attribute of ApplicationSchema --> /schema/application) when performing updates with the following option. More info. can be found here http://mongoosejs.com/docs/validation.html */ runValidators: true }; req.app.db.model('application').findOneAndUpdate(query, update, options).select(unselectedFields).exec(function (err, application) { if (err) { err.status = 403; return next(err); } if (!application) { err = new Error('No application with the given application id exists or ' + 'you don\'t have permission to modify the given application.'); err.status = 400; return next(err); } res.json(application); }); }); /** * @api {delete} /applications/:applicationId Removes the application. * @apiName DeleteApplication * @apiGroup Applications * * @apiParam {String} applicationId ApplicationId id. * * @apiPermission admin * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "message": "Success." * } * * @apiError(400) ApplicationNotFound No application with the given application id exists. * */ router.delete(applicationIdRoute, authentication.authorized, function (req, res, next) { var applicationId = req.params.applicationId || ''; var query = { _id: applicationId, owner: req.user.username }; req.app.db.model('application').findOneAndRemove(query, function (err, app) { if (err) { return next(err); } if (!app) { err = new Error('No application with the given application id exists.'); err.status = 400; return next(err); } app.routes.forEach(function (route) { req.app.acl.removeResource(route); }); res.sendDefaultSuccessMessage(); }); }); /** * @api {put} /applications/look/:prefix Changes the application look field. * @apiName PutApplicationLook * @apiGroup Applications * * @apiParam {String} prefix Application prefix. * @apiParam {String} key Field name to check in the body of the request. * @apiParam {String} user The user that have access to the URL. * @apiParam {String[]} resources The value of the key field that can use the user in the URL route. * @apiParam {String[]} methods URL methods allowed. * @apiParam {String} url * * @apiPermission admin * * @apiParamExample {json} Request-Example (Single-User): * { * "key": "_id", * "user": "dev", * "resources": ["id1"], * "methods": ["post", "put"], * "url": "/url/*" * } * @apiParamExample {json} Request-Example (Multiple-User): * { * "key": "_id", * "users": ["u1", "u2", "u3"], * "resources": ["id1"], * "methods": ["post", "put"], * "url": "/url/*" * } * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "name": "Gleaner App.", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [], * "look":[{ * "key":"_id", * "permissions":{ * "dev":["id1","id2"] * }, * "methods":["post","put"], * "url":"/url/*" * }], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) InvalidApplicationId You must provide a valid application name. * * @apiError(400) ApplicationNotFound No application with the given application id exists. * */ router.put('/look/:prefix', authentication.authorized, function (req, res, next) { req.app.db.model('application').findByPrefix(req.params.prefix, function (err, results) { if (err) { return next(err); } var validationObj = v.validate(req.body, putLookSchema); if (validationObj.errors && validationObj.errors.length > 0) { var errVal = new Error('Bad format: ' + validationObj.errors[0]); errVal.status = 400; return next(errVal); } var users = []; if (req.body.user) { users.push(req.body.user); } if (req.body.users) { users = users.concat(req.body.users); } var applicationId = results._id; var query = { _id: applicationId }; var existKey = false; var addNewUser = []; var updateUser = []; var error; if (results.look) { results.look.forEach(function (lookObj) { if (lookObj.url === req.body.url) { if (lookObj.key === req.body.key) { if (lookObj.permissions) { users.forEach(function(user) { if (!lookObj.permissions[user]) { addNewUser.push(user); }else { updateUser.push(user); } }); } existKey = true; } else { error = new Error('URL registered but with a different key!'); error.status = 400; } } }); } if (error) { return next(error); } var update = {}; if (!existKey) { var objToAdd = { key: req.body.key, permissions: {}, methods: req.body.methods, url: req.body.url }; users.forEach(function(user) { objToAdd.permissions[user] = req.body.resources; }); update = { $push: { } }; update.$push.look = objToAdd; } else { query['look.url'] = req.body.url; if (updateUser.length !== 0) { update.$addToSet = {}; updateUser.forEach(function(user) { var resultField = 'look.$.permissions.' + user; update.$addToSet[resultField] = { $each: req.body.resources }; }); } if (addNewUser.length !== 0) { update.$set = {}; addNewUser.forEach(function(user) { var updateProp = 'look.$.permissions.' + user; update.$set[updateProp] = req.body.resources; }); } } var options = { new: true, /* Since Mongoose 4.0.0 we can run validators (e.g. isURL validator for the host attribute of ApplicationSchema --> /schema/application) when performing updates with the following option. More info. can be found here http://mongoosejs.com/docs/validation.html */ runValidators: true }; req.app.db.model('application').findOneAndUpdate(query, update, options).select(unselectedFields).exec(function (err, application) { if (err) { err.status = 403; return next(err); } if (!application) { err = new Error('No application with the given application id exists or ' + 'you don\'t have permission to modify the given application.'); err.status = 400; return next(err); } res.json(application.look); }); }); }); module.exports = router;
e-ucm/a2
routes/applications.js
JavaScript
apache-2.0
25,370
//===--- IRGenSIL.cpp - Swift Per-Function IR Generation ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements basic setup and teardown for the class which // performs IR generation for function bodies. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "irgensil" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/Intrinsics.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Support/Debug.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TargetInfo.h" #include "swift/Basic/Range.h" #include "swift/Basic/STLExtras.h" #include "swift/AST/ASTContext.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/Pattern.h" #include "swift/AST/ParameterList.h" #include "swift/AST/SubstitutionMap.h" #include "swift/AST/Types.h" #include "swift/SIL/Dominance.h" #include "swift/SIL/PrettyStackTrace.h" #include "swift/SIL/SILDebugScope.h" #include "swift/SIL/SILDeclRef.h" #include "swift/SIL/SILLinkage.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "swift/SIL/SILVisitor.h" #include "swift/SIL/InstructionUtils.h" #include "clang/CodeGen/CodeGenABITypes.h" #include "CallEmission.h" #include "Explosion.h" #include "GenArchetype.h" #include "GenBuiltin.h" #include "GenCall.h" #include "GenCast.h" #include "GenClass.h" #include "GenConstant.h" #include "GenEnum.h" #include "GenExistential.h" #include "GenFunc.h" #include "GenHeap.h" #include "GenMeta.h" #include "GenObjC.h" #include "GenOpaque.h" #include "GenPoly.h" #include "GenProto.h" #include "GenStruct.h" #include "GenTuple.h" #include "GenType.h" #include "IRGenDebugInfo.h" #include "IRGenModule.h" #include "NativeConventionSchema.h" #include "ReferenceTypeInfo.h" #include "WeakTypeInfo.h" using namespace swift; using namespace irgen; namespace { class LoweredValue; /// Represents a statically-known function as a SIL thin function value. class StaticFunction { /// The function reference. llvm::Function *Function; ForeignFunctionInfo ForeignInfo; /// The function's native representation. SILFunctionTypeRepresentation Rep; public: StaticFunction(llvm::Function *function, ForeignFunctionInfo foreignInfo, SILFunctionTypeRepresentation rep) : Function(function), ForeignInfo(foreignInfo), Rep(rep) {} llvm::Function *getFunction() const { return Function; } SILFunctionTypeRepresentation getRepresentation() const { return Rep; } const ForeignFunctionInfo &getForeignInfo() const { return ForeignInfo; } llvm::Value *getExplosionValue(IRGenFunction &IGF) const; }; /// Represents a SIL value lowered to IR, in one of these forms: /// - an Address, corresponding to a SIL address value; /// - an Explosion of (unmanaged) Values, corresponding to a SIL "register"; or /// - a CallEmission for a partially-applied curried function or method. class LoweredValue { public: enum class Kind { /// The first two LoweredValue kinds correspond to a SIL address value. /// /// The LoweredValue of an existential alloc_stack keeps an owning container /// in addition to the address of the allocated buffer. /// Depending on the allocated type, the container may be equal to the /// buffer itself (for types with known sizes) or it may be the address /// of a fixed-size container which points to the heap-allocated buffer. /// In this case the address-part may be null, which means that the buffer /// is not allocated yet. ContainedAddress, /// The LoweredValue of a resilient, generic, or loadable typed alloc_stack /// keeps an optional stackrestore point in addition to the address of the /// allocated buffer. For all other address values the stackrestore point is /// just null. /// If the stackrestore point is set (currently, this might happen for /// opaque types: generic and resilient) the deallocation of the stack must /// reset the stack pointer to this point. Address, /// The following kinds correspond to SIL non-address values. Value_First, /// A normal value, represented as an exploded array of llvm Values. Explosion = Value_First, /// A @box together with the address of the box value. BoxWithAddress, /// A value that represents a statically-known function symbol that /// can be called directly, represented as a StaticFunction. StaticFunction, /// A value that represents an Objective-C method that must be called with /// a form of objc_msgSend. ObjCMethod, Value_Last = ObjCMethod, }; Kind kind; private: using ExplosionVector = SmallVector<llvm::Value *, 4>; union { ContainedAddress containedAddress; StackAddress address; OwnedAddress boxWithAddress; struct { ExplosionVector values; } explosion; StaticFunction staticFunction; ObjCMethod objcMethod; }; public: /// Create an address value without a stack restore point. LoweredValue(const Address &address) : kind(Kind::Address), address(address) {} /// Create an address value with an optional stack restore point. LoweredValue(const StackAddress &address) : kind(Kind::Address), address(address) {} enum ContainerForUnallocatedAddress_t { ContainerForUnallocatedAddress }; /// Create an address value for an alloc_stack, consisting of a container and /// a not yet allocated buffer. LoweredValue(const Address &container, ContainerForUnallocatedAddress_t) : kind(Kind::ContainedAddress), containedAddress(container, Address()) {} /// Create an address value for an alloc_stack, consisting of a container and /// the address of the allocated buffer. LoweredValue(const ContainedAddress &address) : kind(Kind::ContainedAddress), containedAddress(address) {} LoweredValue(StaticFunction &&staticFunction) : kind(Kind::StaticFunction), staticFunction(std::move(staticFunction)) {} LoweredValue(ObjCMethod &&objcMethod) : kind(Kind::ObjCMethod), objcMethod(std::move(objcMethod)) {} LoweredValue(Explosion &e) : kind(Kind::Explosion), explosion{{}} { auto Elts = e.claimAll(); explosion.values.append(Elts.begin(), Elts.end()); } LoweredValue(const OwnedAddress &boxWithAddress) : kind(Kind::BoxWithAddress), boxWithAddress(boxWithAddress) {} LoweredValue(LoweredValue &&lv) : kind(lv.kind) { switch (kind) { case Kind::ContainedAddress: ::new (&containedAddress) ContainedAddress(std::move(lv.containedAddress)); break; case Kind::Address: ::new (&address) StackAddress(std::move(lv.address)); break; case Kind::Explosion: ::new (&explosion.values) ExplosionVector(std::move(lv.explosion.values)); break; case Kind::BoxWithAddress: ::new (&boxWithAddress) OwnedAddress(std::move(lv.boxWithAddress)); break; case Kind::StaticFunction: ::new (&staticFunction) StaticFunction(std::move(lv.staticFunction)); break; case Kind::ObjCMethod: ::new (&objcMethod) ObjCMethod(std::move(lv.objcMethod)); break; } } LoweredValue &operator=(LoweredValue &&lv) { assert(this != &lv); this->~LoweredValue(); ::new (this) LoweredValue(std::move(lv)); return *this; } bool isAddress() const { return kind == Kind::Address && address.getAddress().isValid(); } bool isUnallocatedAddressInBuffer() const { return kind == Kind::ContainedAddress && !containedAddress.getAddress().isValid(); } bool isValue() const { return kind >= Kind::Value_First && kind <= Kind::Value_Last; } bool isBoxWithAddress() const { return kind == Kind::BoxWithAddress; } Address getAddress() const { assert(isAddress() && "not an allocated address"); return address.getAddress(); } StackAddress getStackAddress() const { assert(isAddress() && "not an allocated address"); return address; } Address getContainerOfAddress() const { assert(kind == Kind::ContainedAddress); assert(containedAddress.getContainer().isValid() && "address has no container"); return containedAddress.getContainer(); } Address getAddressInContainer() const { assert(kind == Kind::ContainedAddress); assert(containedAddress.getContainer().isValid() && "address has no container"); return containedAddress.getAddress(); } void getExplosion(IRGenFunction &IGF, Explosion &ex) const; Explosion getExplosion(IRGenFunction &IGF) const { Explosion e; getExplosion(IGF, e); return e; } Address getAddressOfBox() const { assert(kind == Kind::BoxWithAddress); return boxWithAddress.getAddress(); } llvm::Value *getSingletonExplosion(IRGenFunction &IGF) const; const StaticFunction &getStaticFunction() const { assert(kind == Kind::StaticFunction && "not a static function"); return staticFunction; } const ObjCMethod &getObjCMethod() const { assert(kind == Kind::ObjCMethod && "not an objc method"); return objcMethod; } ~LoweredValue() { switch (kind) { case Kind::Address: address.~StackAddress(); break; case Kind::ContainedAddress: containedAddress.~ContainedAddress(); break; case Kind::Explosion: explosion.values.~ExplosionVector(); break; case Kind::BoxWithAddress: boxWithAddress.~OwnedAddress(); break; case Kind::StaticFunction: staticFunction.~StaticFunction(); break; case Kind::ObjCMethod: objcMethod.~ObjCMethod(); break; } } }; using PHINodeVector = llvm::TinyPtrVector<llvm::PHINode*>; /// Represents a lowered SIL basic block. This keeps track /// of SIL branch arguments so that they can be lowered to LLVM phi nodes. struct LoweredBB { llvm::BasicBlock *bb; PHINodeVector phis; LoweredBB() = default; explicit LoweredBB(llvm::BasicBlock *bb, PHINodeVector &&phis) : bb(bb), phis(std::move(phis)) {} }; /// Visits a SIL Function and generates LLVM IR. class IRGenSILFunction : public IRGenFunction, public SILInstructionVisitor<IRGenSILFunction> { public: llvm::DenseMap<SILValue, LoweredValue> LoweredValues; llvm::DenseMap<SILType, LoweredValue> LoweredUndefs; /// All alloc_ref instructions which allocate the object on the stack. llvm::SmallPtrSet<SILInstruction *, 8> StackAllocs; /// With closure captures it is actually possible to have two function /// arguments that both have the same name. Until this is fixed, we need to /// also hash the ArgNo here. typedef std::pair<unsigned, std::pair<const SILDebugScope *, StringRef>> StackSlotKey; /// Keeps track of the mapping of source variables to -O0 shadow copy allocas. llvm::SmallDenseMap<StackSlotKey, Address, 8> ShadowStackSlots; llvm::SmallDenseMap<Decl *, SmallString<4>, 8> AnonymousVariables; /// To avoid inserting elements into ValueDomPoints twice. llvm::SmallDenseSet<llvm::Instruction *, 8> ValueVariables; /// Holds the DominancePoint of values that are storage for a source variable. SmallVector<std::pair<llvm::Instruction *, DominancePoint>, 8> ValueDomPoints; unsigned NumAnonVars = 0; unsigned NumCondFails = 0; /// Accumulative amount of allocated bytes on the stack. Used to limit the /// size for stack promoted objects. /// We calculate it on demand, so that we don't have to do it if the /// function does not have any stack promoted allocations. int EstimatedStackSize = -1; llvm::MapVector<SILBasicBlock *, LoweredBB> LoweredBBs; // Destination basic blocks for condfail traps. llvm::SmallVector<llvm::BasicBlock *, 8> FailBBs; SILFunction *CurSILFn; Address IndirectReturn; // A cached dominance analysis. std::unique_ptr<DominanceInfo> Dominance; IRGenSILFunction(IRGenModule &IGM, SILFunction *f); ~IRGenSILFunction(); /// Generate IR for the SIL Function. void emitSILFunction(); /// Calculates EstimatedStackSize. void estimateStackSize(); void setLoweredValue(SILValue v, LoweredValue &&lv) { auto inserted = LoweredValues.insert({v, std::move(lv)}); assert(inserted.second && "already had lowered value for sil value?!"); (void)inserted; } /// Create a new Address corresponding to the given SIL address value. void setLoweredAddress(SILValue v, const Address &address) { assert(v->getType().isAddress() && "address for non-address value?!"); setLoweredValue(v, address); } void setLoweredStackAddress(SILValue v, const StackAddress &address) { assert(v->getType().isAddress() && "address for non-address value?!"); setLoweredValue(v, address); } void setContainerOfUnallocatedAddress(SILValue v, const Address &buffer) { assert(v->getType().isAddress() && "address for non-address value?!"); setLoweredValue(v, LoweredValue(buffer, LoweredValue::ContainerForUnallocatedAddress)); } void overwriteAllocatedAddress(SILValue v, const Address &address) { assert(v->getType().isAddress() && "address for non-address value?!"); auto it = LoweredValues.find(v); assert(it != LoweredValues.end() && "no existing entry for overwrite?"); assert(it->second.isUnallocatedAddressInBuffer() && "not an unallocated address"); it->second = ContainedAddress(it->second.getContainerOfAddress(), address); } void setAllocatedAddressForBuffer(SILValue v, const Address &allocedAddress); /// Create a new Explosion corresponding to the given SIL value. void setLoweredExplosion(SILValue v, Explosion &e) { assert(v->getType().isObject() && "explosion for address value?!"); setLoweredValue(v, LoweredValue(e)); } void setLoweredBox(SILValue v, const OwnedAddress &box) { assert(v->getType().isObject() && "box for address value?!"); setLoweredValue(v, LoweredValue(box)); } /// Create a new StaticFunction corresponding to the given SIL value. void setLoweredStaticFunction(SILValue v, llvm::Function *f, SILFunctionTypeRepresentation rep, ForeignFunctionInfo foreignInfo) { assert(v->getType().isObject() && "function for address value?!"); assert(v->getType().is<SILFunctionType>() && "function for non-function value?!"); setLoweredValue(v, StaticFunction{f, foreignInfo, rep}); } /// Create a new Objective-C method corresponding to the given SIL value. void setLoweredObjCMethod(SILValue v, SILDeclRef method) { assert(v->getType().isObject() && "function for address value?!"); assert(v->getType().is<SILFunctionType>() && "function for non-function value?!"); setLoweredValue(v, ObjCMethod{method, SILType(), false}); } /// Create a new Objective-C method corresponding to the given SIL value that /// starts its search from the given search type. /// /// Unlike \c setLoweredObjCMethod, which finds the method in the actual /// runtime type of the object, this routine starts at the static type of the /// object and searches up the class hierarchy (toward superclasses). /// /// \param searchType The class from which the Objective-C runtime will start /// its search for a method. /// /// \param startAtSuper Whether we want to start at the superclass of the /// static type (vs. the static type itself). void setLoweredObjCMethodBounded(SILValue v, SILDeclRef method, SILType searchType, bool startAtSuper) { assert(v->getType().isObject() && "function for address value?!"); assert(v->getType().is<SILFunctionType>() && "function for non-function value?!"); setLoweredValue(v, ObjCMethod{method, searchType, startAtSuper}); } LoweredValue &getUndefLoweredValue(SILType t) { auto found = LoweredUndefs.find(t); if (found != LoweredUndefs.end()) return found->second; auto &ti = getTypeInfo(t); switch (t.getCategory()) { case SILValueCategory::Address: { Address undefAddr = ti.getAddressForPointer( llvm::UndefValue::get(ti.getStorageType()->getPointerTo())); LoweredUndefs.insert({t, LoweredValue(undefAddr)}); break; } case SILValueCategory::Object: { auto schema = ti.getSchema(); Explosion e; for (auto &elt : schema) { assert(!elt.isAggregate() && "non-scalar element in loadable type schema?!"); e.add(llvm::UndefValue::get(elt.getScalarType())); } LoweredUndefs.insert({t, LoweredValue(e)}); break; } } found = LoweredUndefs.find(t); assert(found != LoweredUndefs.end()); return found->second; } /// Get the LoweredValue corresponding to the given SIL value, which must /// have been lowered. LoweredValue &getLoweredValue(SILValue v) { if (isa<SILUndef>(v)) return getUndefLoweredValue(v->getType()); auto foundValue = LoweredValues.find(v); assert(foundValue != LoweredValues.end() && "no lowered explosion for sil value!"); return foundValue->second; } /// Get the Address of a SIL value of address type, which must have been /// lowered. Address getLoweredAddress(SILValue v) { if (getLoweredValue(v).kind == LoweredValue::Kind::Address) return getLoweredValue(v).getAddress(); else return getLoweredValue(v).getAddressInContainer(); } StackAddress getLoweredStackAddress(SILValue v) { return getLoweredValue(v).getStackAddress(); } /// Add the unmanaged LLVM values lowered from a SIL value to an explosion. void getLoweredExplosion(SILValue v, Explosion &e) { getLoweredValue(v).getExplosion(*this, e); } /// Create an Explosion containing the unmanaged LLVM values lowered from a /// SIL value. Explosion getLoweredExplosion(SILValue v) { return getLoweredValue(v).getExplosion(*this); } /// Return the single member of the lowered explosion for the /// given SIL value. llvm::Value *getLoweredSingletonExplosion(SILValue v) { return getLoweredValue(v).getSingletonExplosion(*this); } LoweredBB &getLoweredBB(SILBasicBlock *bb) { auto foundBB = LoweredBBs.find(bb); assert(foundBB != LoweredBBs.end() && "no llvm bb for sil bb?!"); return foundBB->second; } StringRef getOrCreateAnonymousVarName(VarDecl *Decl) { llvm::SmallString<4> &Name = AnonymousVariables[Decl]; if (Name.empty()) { { llvm::raw_svector_ostream S(Name); S << '_' << NumAnonVars++; } AnonymousVariables.insert({Decl, Name}); } return Name; } template <class DebugVarCarryingInst> StringRef getVarName(DebugVarCarryingInst *i) { StringRef Name = i->getVarInfo().Name; // The $match variables generated by the type checker are not // guaranteed to be unique within their scope, but they have // unique VarDecls. if ((Name.empty() || Name == "$match") && i->getDecl()) return getOrCreateAnonymousVarName(i->getDecl()); return Name; } /// At -Onone, forcibly keep all LLVM values that are tracked by /// debug variables alive by inserting an empty inline assembler /// expression depending on the value in the blocks dominated by the /// value. void emitDebugVariableRangeExtension(const SILBasicBlock *CurBB) { if (IGM.IRGen.Opts.Optimize) return; for (auto &Variable : ValueDomPoints) { auto VarDominancePoint = Variable.second; llvm::Value *Storage = Variable.first; if (getActiveDominancePoint() == VarDominancePoint || isActiveDominancePointDominatedBy(VarDominancePoint)) { llvm::Type *ArgTys; auto *Ty = Storage->getType(); // Vectors, Pointers and Floats are expected to fit into a register. if (Ty->isPointerTy() || Ty->isFloatingPointTy() || Ty->isVectorTy()) ArgTys = { Ty }; else { // If this is not a scalar or vector type, we can't handle it. if (isa<llvm::CompositeType>(Ty)) continue; // The storage is guaranteed to be no larger than the register width. // Extend the storage so it would fit into a register. llvm::Type *IntTy; switch (IGM.getClangASTContext().getTargetInfo().getRegisterWidth()) { case 64: IntTy = IGM.Int64Ty; break; case 32: IntTy = IGM.Int32Ty; break; default: llvm_unreachable("unsupported register width"); } ArgTys = { IntTy }; Storage = Builder.CreateZExtOrBitCast(Storage, IntTy); } // Emit an empty inline assembler expression depending on the register. auto *AsmFnTy = llvm::FunctionType::get(IGM.VoidTy, ArgTys, false); auto *InlineAsm = llvm::InlineAsm::get(AsmFnTy, "", "r", true); Builder.CreateCall(InlineAsm, Storage); // Propagate the dbg.value intrinsics into the later basic blocks. Note // that this shouldn't be necessary. LiveDebugValues should be doing // this but can't in general because it currently only tracks register // locations. llvm::Instruction *Value = Variable.first; auto It = llvm::BasicBlock::iterator(Value); auto *BB = Value->getParent(); auto *CurBB = Builder.GetInsertBlock(); if (BB != CurBB) for (auto I = std::next(It), E = BB->end(); I != E; ++I) { auto *DVI = dyn_cast<llvm::DbgValueInst>(I); if (DVI && DVI->getValue() == Value) IGM.DebugInfo->getBuilder().insertDbgValueIntrinsic( DVI->getValue(), 0, DVI->getVariable(), DVI->getExpression(), DVI->getDebugLoc(), &*CurBB->getFirstInsertionPt()); else // Found all dbg.value intrinsics describing this location. break; } } } } /// Account for bugs in LLVM. /// /// - The LLVM type legalizer currently doesn't update debug /// intrinsics when a large value is split up into smaller /// pieces. Note that this heuristic as a bit too conservative /// on 32-bit targets as it will also fire for doubles. /// /// - CodeGen Prepare may drop dbg.values pointing to PHI instruction. bool needsShadowCopy(llvm::Value *Storage) { return (IGM.DataLayout.getTypeSizeInBits(Storage->getType()) > IGM.getClangASTContext().getTargetInfo().getRegisterWidth()) || isa<llvm::PHINode>(Storage); } /// At -Onone, emit a shadow copy of an Address in an alloca, so the /// register allocator doesn't elide the dbg.value intrinsic when /// register pressure is high. There is a trade-off to this: With /// shadow copies, we lose the precise lifetime. llvm::Value *emitShadowCopy(llvm::Value *Storage, const SILDebugScope *Scope, StringRef Name, unsigned ArgNo, Alignment Align = Alignment(0)) { auto Ty = Storage->getType(); // Never emit shadow copies when optimizing, or if already on the stack. if (IGM.IRGen.Opts.Optimize || isa<llvm::AllocaInst>(Storage) || isa<llvm::UndefValue>(Storage) || Ty == IGM.RefCountedPtrTy) // No debug info is emitted for refcounts. return Storage; // Always emit shadow copies for function arguments. if (ArgNo == 0) // Otherwise only if debug value range extension is not feasible. if (!needsShadowCopy(Storage)) { // Mark for debug value range extension unless this is a constant. if (auto *Value = dyn_cast<llvm::Instruction>(Storage)) if (ValueVariables.insert(Value).second) ValueDomPoints.push_back({Value, getActiveDominancePoint()}); return Storage; } if (Align.isZero()) Align = IGM.getPointerAlignment(); auto &Alloca = ShadowStackSlots[{ArgNo, {Scope, Name}}]; if (!Alloca.isValid()) Alloca = createAlloca(Ty, Align, Name+".addr"); ArtificialLocation AutoRestore(getDebugScope(), IGM.DebugInfo, Builder); Builder.CreateStore(Storage, Alloca.getAddress(), Align); return Alloca.getAddress(); } llvm::Value *emitShadowCopy(Address Storage, const SILDebugScope *Scope, StringRef Name, unsigned ArgNo) { return emitShadowCopy(Storage.getAddress(), Scope, Name, ArgNo, Storage.getAlignment()); } void emitShadowCopy(ArrayRef<llvm::Value *> vals, const SILDebugScope *Scope, StringRef Name, unsigned ArgNo, llvm::SmallVectorImpl<llvm::Value *> &copy) { // Only do this at -O0. if (IGM.IRGen.Opts.Optimize) { copy.append(vals.begin(), vals.end()); return; } // Single or empty values. if (vals.size() <= 1) { for (auto val : vals) copy.push_back(emitShadowCopy(val, Scope, Name, ArgNo)); return; } // Create a single aggregate alloca for explosions. // TODO: why are we doing this instead of using the TypeInfo? llvm::StructType *aggregateType = [&] { SmallVector<llvm::Type *, 8> eltTypes; for (auto val : vals) eltTypes.push_back(val->getType()); return llvm::StructType::get(IGM.LLVMContext, eltTypes); }(); auto layout = IGM.DataLayout.getStructLayout(aggregateType); Alignment align(layout->getAlignment()); auto alloca = createAlloca(aggregateType, align, Name + ".debug"); ArtificialLocation AutoRestore(getDebugScope(), IGM.DebugInfo, Builder); size_t i = 0; for (auto val : vals) { auto addr = Builder.CreateStructGEP(alloca, i, Size(layout->getElementOffset(i))); Builder.CreateStore(val, addr); i++; } copy.push_back(alloca.getAddress()); } /// Determine whether a generic variable has been inlined. static bool isInlinedGeneric(VarDecl *VarDecl, const SILDebugScope *DS) { if (!DS->InlinedCallSite) return false; if (VarDecl->hasType()) return VarDecl->getType()->hasArchetype(); return VarDecl->getInterfaceType()->hasTypeParameter(); } /// Emit debug info for a function argument or a local variable. template <typename StorageType> void emitDebugVariableDeclaration(StorageType Storage, DebugTypeInfo Ty, SILType SILTy, const SILDebugScope *DS, VarDecl *VarDecl, StringRef Name, unsigned ArgNo = 0, IndirectionKind Indirection = DirectValue) { // Force all archetypes referenced by the type to be bound by this point. // TODO: just make sure that we have a path to them that the debug info // can follow. // FIXME: The debug info type of all inlined instances of a variable must be // the same as the type of the abstract variable. if (isInlinedGeneric(VarDecl, DS)) return; auto runtimeTy = getRuntimeReifiedType(IGM, Ty.getType()->getCanonicalType()); if (!IGM.IRGen.Opts.Optimize && runtimeTy->hasArchetype()) runtimeTy.visit([&](CanType t) { if (auto archetype = dyn_cast<ArchetypeType>(t)) emitTypeMetadataRef(archetype); }); assert(IGM.DebugInfo && "debug info not enabled"); if (ArgNo) { PrologueLocation AutoRestore(IGM.DebugInfo, Builder); IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, Ty, DS, VarDecl, Name, ArgNo, Indirection); } else IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, Ty, DS, VarDecl, Name, 0, Indirection); } void emitFailBB() { if (!FailBBs.empty()) { // Move the trap basic blocks to the end of the function. for (auto *FailBB : FailBBs) { auto &BlockList = CurFn->getBasicBlockList(); BlockList.splice(BlockList.end(), BlockList, FailBB); } } } //===--------------------------------------------------------------------===// // SIL instruction lowering //===--------------------------------------------------------------------===// void visitSILBasicBlock(SILBasicBlock *BB); void emitErrorResultVar(SILResultInfo ErrorInfo, DebugValueInst *DbgValue); void emitDebugInfoForAllocStack(AllocStackInst *i, const TypeInfo &type, llvm::Value *addr); void visitAllocStackInst(AllocStackInst *i); void visitAllocRefInst(AllocRefInst *i); void visitAllocRefDynamicInst(AllocRefDynamicInst *i); void visitAllocBoxInst(AllocBoxInst *i); void visitProjectBoxInst(ProjectBoxInst *i); void visitApplyInst(ApplyInst *i); void visitTryApplyInst(TryApplyInst *i); void visitFullApplySite(FullApplySite i); void visitPartialApplyInst(PartialApplyInst *i); void visitBuiltinInst(BuiltinInst *i); void visitFunctionRefInst(FunctionRefInst *i); void visitAllocGlobalInst(AllocGlobalInst *i); void visitGlobalAddrInst(GlobalAddrInst *i); void visitIntegerLiteralInst(IntegerLiteralInst *i); void visitFloatLiteralInst(FloatLiteralInst *i); void visitStringLiteralInst(StringLiteralInst *i); void visitLoadInst(LoadInst *i); void visitStoreInst(StoreInst *i); void visitAssignInst(AssignInst *i) { llvm_unreachable("assign is not valid in canonical SIL"); } void visitMarkUninitializedInst(MarkUninitializedInst *i) { llvm_unreachable("mark_uninitialized is not valid in canonical SIL"); } void visitMarkUninitializedBehaviorInst(MarkUninitializedBehaviorInst *i) { llvm_unreachable("mark_uninitialized_behavior is not valid in canonical SIL"); } void visitMarkFunctionEscapeInst(MarkFunctionEscapeInst *i) { llvm_unreachable("mark_function_escape is not valid in canonical SIL"); } void visitLoadBorrowInst(LoadBorrowInst *i) { llvm_unreachable("unimplemented"); } void visitDebugValueInst(DebugValueInst *i); void visitDebugValueAddrInst(DebugValueAddrInst *i); void visitLoadWeakInst(LoadWeakInst *i); void visitStoreWeakInst(StoreWeakInst *i); void visitRetainValueInst(RetainValueInst *i); void visitCopyValueInst(CopyValueInst *i); void visitCopyUnownedValueInst(CopyUnownedValueInst *i) { llvm_unreachable("unimplemented"); } void visitReleaseValueInst(ReleaseValueInst *i); void visitDestroyValueInst(DestroyValueInst *i); void visitAutoreleaseValueInst(AutoreleaseValueInst *i); void visitSetDeallocatingInst(SetDeallocatingInst *i); void visitStructInst(StructInst *i); void visitTupleInst(TupleInst *i); void visitEnumInst(EnumInst *i); void visitInitEnumDataAddrInst(InitEnumDataAddrInst *i); void visitSelectEnumInst(SelectEnumInst *i); void visitSelectEnumAddrInst(SelectEnumAddrInst *i); void visitSelectValueInst(SelectValueInst *i); void visitUncheckedEnumDataInst(UncheckedEnumDataInst *i); void visitUncheckedTakeEnumDataAddrInst(UncheckedTakeEnumDataAddrInst *i); void visitInjectEnumAddrInst(InjectEnumAddrInst *i); void visitObjCProtocolInst(ObjCProtocolInst *i); void visitMetatypeInst(MetatypeInst *i); void visitValueMetatypeInst(ValueMetatypeInst *i); void visitExistentialMetatypeInst(ExistentialMetatypeInst *i); void visitTupleExtractInst(TupleExtractInst *i); void visitTupleElementAddrInst(TupleElementAddrInst *i); void visitStructExtractInst(StructExtractInst *i); void visitStructElementAddrInst(StructElementAddrInst *i); void visitRefElementAddrInst(RefElementAddrInst *i); void visitRefTailAddrInst(RefTailAddrInst *i); void visitClassMethodInst(ClassMethodInst *i); void visitSuperMethodInst(SuperMethodInst *i); void visitWitnessMethodInst(WitnessMethodInst *i); void visitDynamicMethodInst(DynamicMethodInst *i); void visitAllocValueBufferInst(AllocValueBufferInst *i); void visitProjectValueBufferInst(ProjectValueBufferInst *i); void visitDeallocValueBufferInst(DeallocValueBufferInst *i); void visitOpenExistentialAddrInst(OpenExistentialAddrInst *i); void visitOpenExistentialMetatypeInst(OpenExistentialMetatypeInst *i); void visitOpenExistentialRefInst(OpenExistentialRefInst *i); void visitOpenExistentialOpaqueInst(OpenExistentialOpaqueInst *i); void visitInitExistentialAddrInst(InitExistentialAddrInst *i); void visitInitExistentialOpaqueInst(InitExistentialOpaqueInst *i); void visitInitExistentialMetatypeInst(InitExistentialMetatypeInst *i); void visitInitExistentialRefInst(InitExistentialRefInst *i); void visitDeinitExistentialAddrInst(DeinitExistentialAddrInst *i); void visitDeinitExistentialOpaqueInst(DeinitExistentialOpaqueInst *i); void visitAllocExistentialBoxInst(AllocExistentialBoxInst *i); void visitOpenExistentialBoxInst(OpenExistentialBoxInst *i); void visitProjectExistentialBoxInst(ProjectExistentialBoxInst *i); void visitDeallocExistentialBoxInst(DeallocExistentialBoxInst *i); void visitProjectBlockStorageInst(ProjectBlockStorageInst *i); void visitInitBlockStorageHeaderInst(InitBlockStorageHeaderInst *i); void visitFixLifetimeInst(FixLifetimeInst *i); void visitEndLifetimeInst(EndLifetimeInst *i) { llvm_unreachable("unimplemented"); } void visitUncheckedOwnershipConversionInst(UncheckedOwnershipConversionInst *i) { llvm_unreachable("unimplemented"); } void visitBeginBorrowInst(BeginBorrowInst *i) { llvm_unreachable("unimplemented"); } void visitEndBorrowInst(EndBorrowInst *i) { llvm_unreachable("unimplemented"); } void visitEndBorrowArgumentInst(EndBorrowArgumentInst *i) { llvm_unreachable("unimplemented"); } void visitStoreBorrowInst(StoreBorrowInst *i) { llvm_unreachable("unimplemented"); } void visitBeginAccessInst(BeginAccessInst *i); void visitEndAccessInst(EndAccessInst *i); void visitUnmanagedRetainValueInst(UnmanagedRetainValueInst *i) { llvm_unreachable("unimplemented"); } void visitUnmanagedReleaseValueInst(UnmanagedReleaseValueInst *i) { llvm_unreachable("unimplemented"); } void visitUnmanagedAutoreleaseValueInst(UnmanagedAutoreleaseValueInst *i) { llvm_unreachable("unimplemented"); } void visitMarkDependenceInst(MarkDependenceInst *i); void visitCopyBlockInst(CopyBlockInst *i); void visitStrongPinInst(StrongPinInst *i); void visitStrongUnpinInst(StrongUnpinInst *i); void visitStrongRetainInst(StrongRetainInst *i); void visitStrongReleaseInst(StrongReleaseInst *i); void visitStrongRetainUnownedInst(StrongRetainUnownedInst *i); void visitUnownedRetainInst(UnownedRetainInst *i); void visitUnownedReleaseInst(UnownedReleaseInst *i); void visitLoadUnownedInst(LoadUnownedInst *i); void visitStoreUnownedInst(StoreUnownedInst *i); void visitIsUniqueInst(IsUniqueInst *i); void visitIsUniqueOrPinnedInst(IsUniqueOrPinnedInst *i); void visitDeallocStackInst(DeallocStackInst *i); void visitDeallocBoxInst(DeallocBoxInst *i); void visitDeallocRefInst(DeallocRefInst *i); void visitDeallocPartialRefInst(DeallocPartialRefInst *i); void visitCopyAddrInst(CopyAddrInst *i); void visitDestroyAddrInst(DestroyAddrInst *i); void visitBindMemoryInst(BindMemoryInst *i); void visitCondFailInst(CondFailInst *i); void visitConvertFunctionInst(ConvertFunctionInst *i); void visitThinFunctionToPointerInst(ThinFunctionToPointerInst *i); void visitPointerToThinFunctionInst(PointerToThinFunctionInst *i); void visitUpcastInst(UpcastInst *i); void visitAddressToPointerInst(AddressToPointerInst *i); void visitPointerToAddressInst(PointerToAddressInst *i); void visitUncheckedRefCastInst(UncheckedRefCastInst *i); void visitUncheckedRefCastAddrInst(UncheckedRefCastAddrInst *i); void visitUncheckedAddrCastInst(UncheckedAddrCastInst *i); void visitUncheckedTrivialBitCastInst(UncheckedTrivialBitCastInst *i); void visitUncheckedBitwiseCastInst(UncheckedBitwiseCastInst *i); void visitRefToRawPointerInst(RefToRawPointerInst *i); void visitRawPointerToRefInst(RawPointerToRefInst *i); void visitRefToUnownedInst(RefToUnownedInst *i); void visitUnownedToRefInst(UnownedToRefInst *i); void visitRefToUnmanagedInst(RefToUnmanagedInst *i); void visitUnmanagedToRefInst(UnmanagedToRefInst *i); void visitThinToThickFunctionInst(ThinToThickFunctionInst *i); void visitThickToObjCMetatypeInst(ThickToObjCMetatypeInst *i); void visitObjCToThickMetatypeInst(ObjCToThickMetatypeInst *i); void visitUnconditionalCheckedCastInst(UnconditionalCheckedCastInst *i); void visitUnconditionalCheckedCastAddrInst(UnconditionalCheckedCastAddrInst *i); void visitUnconditionalCheckedCastValueInst(UnconditionalCheckedCastValueInst *i); void visitObjCMetatypeToObjectInst(ObjCMetatypeToObjectInst *i); void visitObjCExistentialMetatypeToObjectInst( ObjCExistentialMetatypeToObjectInst *i); void visitRefToBridgeObjectInst(RefToBridgeObjectInst *i); void visitBridgeObjectToRefInst(BridgeObjectToRefInst *i); void visitBridgeObjectToWordInst(BridgeObjectToWordInst *i); void visitIsNonnullInst(IsNonnullInst *i); void visitIndexAddrInst(IndexAddrInst *i); void visitTailAddrInst(TailAddrInst *i); void visitIndexRawPointerInst(IndexRawPointerInst *i); void visitUnreachableInst(UnreachableInst *i); void visitBranchInst(BranchInst *i); void visitCondBranchInst(CondBranchInst *i); void visitReturnInst(ReturnInst *i); void visitThrowInst(ThrowInst *i); void visitSwitchValueInst(SwitchValueInst *i); void visitSwitchEnumInst(SwitchEnumInst *i); void visitSwitchEnumAddrInst(SwitchEnumAddrInst *i); void visitDynamicMethodBranchInst(DynamicMethodBranchInst *i); void visitCheckedCastBranchInst(CheckedCastBranchInst *i); void visitCheckedCastValueBranchInst(CheckedCastValueBranchInst *i); void visitCheckedCastAddrBranchInst(CheckedCastAddrBranchInst *i); }; } // end anonymous namespace llvm::Value *StaticFunction::getExplosionValue(IRGenFunction &IGF) const { return IGF.Builder.CreateBitCast(Function, IGF.IGM.Int8PtrTy); } void LoweredValue::getExplosion(IRGenFunction &IGF, Explosion &ex) const { switch (kind) { case Kind::Address: case Kind::ContainedAddress: llvm_unreachable("not a value"); case Kind::Explosion: for (auto *value : explosion.values) ex.add(value); break; case Kind::BoxWithAddress: ex.add(boxWithAddress.getOwner()); break; case Kind::StaticFunction: ex.add(staticFunction.getExplosionValue(IGF)); break; case Kind::ObjCMethod: ex.add(objcMethod.getExplosionValue(IGF)); break; } } llvm::Value *LoweredValue::getSingletonExplosion(IRGenFunction &IGF) const { switch (kind) { case Kind::Address: case Kind::ContainedAddress: llvm_unreachable("not a value"); case Kind::Explosion: assert(explosion.values.size() == 1); return explosion.values[0]; case Kind::BoxWithAddress: return boxWithAddress.getOwner(); case Kind::StaticFunction: return staticFunction.getExplosionValue(IGF); case Kind::ObjCMethod: return objcMethod.getExplosionValue(IGF); } llvm_unreachable("bad lowered value kind!"); } IRGenSILFunction::IRGenSILFunction(IRGenModule &IGM, SILFunction *f) : IRGenFunction(IGM, IGM.getAddrOfSILFunction(f, ForDefinition), f->getDebugScope(), f->getLocation()), CurSILFn(f) { // Apply sanitizer attributes to the function. // TODO: Check if the function is ASan black listed either in the external // file or via annotations. if (IGM.IRGen.Opts.Sanitize == SanitizerKind::Address) CurFn->addFnAttr(llvm::Attribute::SanitizeAddress); if (IGM.IRGen.Opts.Sanitize == SanitizerKind::Thread) { if (dyn_cast_or_null<DestructorDecl>(f->getDeclContext())) // Do not report races in deinit and anything called from it // because TSan does not observe synchronization between retain // count dropping to '0' and the object deinitialization. CurFn->addFnAttr("sanitize_thread_no_checking_at_run_time"); else CurFn->addFnAttr(llvm::Attribute::SanitizeThread); } } IRGenSILFunction::~IRGenSILFunction() { assert(Builder.hasPostTerminatorIP() && "did not terminate BB?!"); // Emit the fail BB if we have one. if (!FailBBs.empty()) emitFailBB(); DEBUG(CurFn->print(llvm::dbgs())); } template<typename ValueVector> static void emitPHINodesForType(IRGenSILFunction &IGF, SILType type, const TypeInfo &ti, unsigned predecessors, ValueVector &phis) { if (type.isAddress()) { phis.push_back(IGF.Builder.CreatePHI(ti.getStorageType()->getPointerTo(), predecessors)); } else { // PHIs are always emitted with maximal explosion. ExplosionSchema schema = ti.getSchema(); for (auto &elt : schema) { if (elt.isScalar()) phis.push_back( IGF.Builder.CreatePHI(elt.getScalarType(), predecessors)); else phis.push_back( IGF.Builder.CreatePHI(elt.getAggregateType()->getPointerTo(), predecessors)); } } } static PHINodeVector emitPHINodesForBBArgs(IRGenSILFunction &IGF, SILBasicBlock *silBB, llvm::BasicBlock *llBB) { PHINodeVector phis; unsigned predecessors = std::distance(silBB->pred_begin(), silBB->pred_end()); IGF.Builder.SetInsertPoint(llBB); if (IGF.IGM.DebugInfo) { // Use the location of the first instruction in the basic block // for the φ-nodes. if (!silBB->empty()) { SILInstruction &I = *silBB->begin(); auto DS = I.getDebugScope(); assert(DS); IGF.IGM.DebugInfo->setCurrentLoc(IGF.Builder, DS, I.getLoc()); } } for (SILArgument *arg : make_range(silBB->args_begin(), silBB->args_end())) { size_t first = phis.size(); const TypeInfo &ti = IGF.getTypeInfo(arg->getType()); emitPHINodesForType(IGF, arg->getType(), ti, predecessors, phis); if (arg->getType().isAddress()) { IGF.setLoweredAddress(arg, ti.getAddressForPointer(phis.back())); } else { Explosion argValue; for (llvm::PHINode *phi : swift::make_range(phis.begin()+first, phis.end())) argValue.add(phi); IGF.setLoweredExplosion(arg, argValue); } } // Since we return to the entry of the function, reset the location. if (IGF.IGM.DebugInfo) IGF.IGM.DebugInfo->clearLoc(IGF.Builder); return phis; } static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF, LoweredBB &lbb, unsigned &phiIndex, Explosion &argValue); // TODO: Handle this during SIL AddressLowering. static ArrayRef<SILArgument*> emitEntryPointIndirectReturn( IRGenSILFunction &IGF, SILBasicBlock *entry, Explosion &params, CanSILFunctionType funcTy, llvm::function_ref<bool(SILType)> requiresIndirectResult) { // Map an indirect return for a type SIL considers loadable but still // requires an indirect return at the IR level. SILFunctionConventions fnConv(funcTy, IGF.getSILModule()); SILType directResultType = IGF.CurSILFn->mapTypeIntoContext(fnConv.getSILResultType()); if (requiresIndirectResult(directResultType)) { auto &retTI = IGF.IGM.getTypeInfo(directResultType); IGF.IndirectReturn = retTI.getAddressForPointer(params.claimNext()); } auto bbargs = entry->getArguments(); // Map the indirect returns if present. unsigned numIndirectResults = fnConv.getNumIndirectSILResults(); for (unsigned i = 0; i != numIndirectResults; ++i) { SILArgument *ret = bbargs[i]; auto &retTI = IGF.IGM.getTypeInfo(ret->getType()); IGF.setLoweredAddress(ret, retTI.getAddressForPointer(params.claimNext())); } return bbargs.slice(numIndirectResults); } static void bindParameter(IRGenSILFunction &IGF, SILArgument *param, Explosion &allParamValues) { // Pull out the parameter value and its formal type. auto &paramTI = IGF.getTypeInfo(param->getType()); // If the SIL parameter isn't passed indirectly, we need to map it // to an explosion. if (param->getType().isObject()) { Explosion paramValues; auto &loadableTI = cast<LoadableTypeInfo>(paramTI); // If the explosion must be passed indirectly, load the value from the // indirect address. auto &nativeSchema = paramTI.nativeParameterValueSchema(IGF.IGM); if (nativeSchema.requiresIndirect()) { Address paramAddr = loadableTI.getAddressForPointer(allParamValues.claimNext()); loadableTI.loadAsTake(IGF, paramAddr, paramValues); } else { if (!nativeSchema.empty()) { // Otherwise, we map from the native convention to the type's explosion // schema. Explosion nativeParam; allParamValues.transferInto(nativeParam, nativeSchema.size()); paramValues = nativeSchema.mapFromNative(IGF.IGM, IGF, nativeParam, param->getType()); } else { assert(paramTI.getSchema().empty()); } } IGF.setLoweredExplosion(param, paramValues); return; } // Okay, the type is passed indirectly in SIL, so we need to map // it to an address. // FIXME: that doesn't mean we should physically pass it // indirectly at this resilience expansion. An @in or @in_guaranteed parameter // could be passed by value in the right resilience domain. Address paramAddr = paramTI.getAddressForPointer(allParamValues.claimNext()); IGF.setLoweredAddress(param, paramAddr); } /// Emit entry point arguments for a SILFunction with the Swift calling /// convention. static void emitEntryPointArgumentsNativeCC(IRGenSILFunction &IGF, SILBasicBlock *entry, Explosion &allParamValues) { auto funcTy = IGF.CurSILFn->getLoweredFunctionType(); // Map the indirect return if present. ArrayRef<SILArgument *> params = emitEntryPointIndirectReturn( IGF, entry, allParamValues, funcTy, [&](SILType retType) -> bool { auto &schema = IGF.IGM.getTypeInfo(retType).nativeReturnValueSchema(IGF.IGM); return schema.requiresIndirect(); }); // The witness method CC passes Self as a final argument. WitnessMetadata witnessMetadata; if (funcTy->getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod) { collectTrailingWitnessMetadata(IGF, *IGF.CurSILFn, allParamValues, witnessMetadata); } // Bind the error result by popping it off the parameter list. if (funcTy->hasErrorResult()) { IGF.setErrorResultSlot(allParamValues.takeLast()); } // The 'self' argument might be in the context position, which is // now the end of the parameter list. Bind it now. if (funcTy->hasSelfParam() && isSelfContextParameter(funcTy->getSelfParameter())) { SILArgument *selfParam = params.back(); params = params.drop_back(); Explosion selfTemp; selfTemp.add(allParamValues.takeLast()); bindParameter(IGF, selfParam, selfTemp); // Even if we don't have a 'self', if we have an error result, we // should have a placeholder argument here. } else if (funcTy->hasErrorResult() || funcTy->getRepresentation() == SILFunctionTypeRepresentation::Thick) { llvm::Value *contextPtr = allParamValues.takeLast(); (void) contextPtr; assert(contextPtr->getType() == IGF.IGM.RefCountedPtrTy); } // Map the remaining SIL parameters to LLVM parameters. for (SILArgument *param : params) { bindParameter(IGF, param, allParamValues); } // Bind polymorphic arguments. This can only be done after binding // all the value parameters. if (hasPolymorphicParameters(funcTy)) { emitPolymorphicParameters(IGF, *IGF.CurSILFn, allParamValues, &witnessMetadata, [&](unsigned paramIndex) -> llvm::Value* { SILValue parameter = IGF.CurSILFn->getArgumentsWithoutIndirectResults()[paramIndex]; return IGF.getLoweredSingletonExplosion(parameter); }); } assert(allParamValues.empty() && "didn't claim all parameters!"); } /// Emit entry point arguments for the parameters of a C function, or the /// method parameters of an ObjC method. static void emitEntryPointArgumentsCOrObjC(IRGenSILFunction &IGF, SILBasicBlock *entry, Explosion &params, CanSILFunctionType funcTy) { // First, lower the method type. ForeignFunctionInfo foreignInfo = IGF.IGM.getForeignFunctionInfo(funcTy); assert(foreignInfo.ClangInfo); auto &FI = *foreignInfo.ClangInfo; // Okay, start processing the parameters explosion. // First, claim all the indirect results. ArrayRef<SILArgument*> args = emitEntryPointIndirectReturn(IGF, entry, params, funcTy, [&](SILType directResultType) -> bool { return FI.getReturnInfo().isIndirect(); }); unsigned nextArgTyIdx = 0; // Handle the arguments of an ObjC method. if (IGF.CurSILFn->getRepresentation() == SILFunctionTypeRepresentation::ObjCMethod) { // Claim the self argument from the end of the formal arguments. SILArgument *selfArg = args.back(); args = args.slice(0, args.size() - 1); // Set the lowered explosion for the self argument. auto &selfTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(selfArg->getType())); auto selfSchema = selfTI.getSchema(); assert(selfSchema.size() == 1 && "Expected self to be a single element!"); auto *selfValue = params.claimNext(); auto *bodyType = selfSchema.begin()->getScalarType(); if (selfValue->getType() != bodyType) selfValue = IGF.coerceValue(selfValue, bodyType, IGF.IGM.DataLayout); Explosion self; self.add(selfValue); IGF.setLoweredExplosion(selfArg, self); // Discard the implicit _cmd argument. params.claimNext(); // We've handled the self and _cmd arguments, so when we deal with // generating explosions for the remaining arguments we can skip // these. nextArgTyIdx = 2; } assert(args.size() == (FI.arg_size() - nextArgTyIdx) && "Number of arguments not equal to number of argument types!"); // Generate lowered explosions for each explicit argument. for (auto i : indices(args)) { SILArgument *arg = args[i]; auto argTyIdx = i + nextArgTyIdx; auto &argTI = IGF.getTypeInfo(arg->getType()); // Bitcast indirect argument pointers to the right storage type. if (arg->getType().isAddress()) { llvm::Value *ptr = params.claimNext(); ptr = IGF.Builder.CreateBitCast(ptr, argTI.getStorageType()->getPointerTo()); IGF.setLoweredAddress(arg, Address(ptr, argTI.getBestKnownAlignment())); continue; } auto &loadableArgTI = cast<LoadableTypeInfo>(argTI); Explosion argExplosion; emitForeignParameter(IGF, params, foreignInfo, argTyIdx, arg->getType(), loadableArgTI, argExplosion); IGF.setLoweredExplosion(arg, argExplosion); } assert(params.empty() && "didn't claim all parameters!"); // emitPolymorphicParameters() may create function calls, so we need // to initialize the debug location here. ArtificialLocation Loc(IGF.getDebugScope(), IGF.IGM.DebugInfo, IGF.Builder); // Bind polymorphic arguments. This can only be done after binding // all the value parameters, and must be done even for non-polymorphic // functions because of imported Objective-C generics. emitPolymorphicParameters( IGF, *IGF.CurSILFn, params, nullptr, [&](unsigned paramIndex) -> llvm::Value * { SILValue parameter = entry->getArguments()[paramIndex]; return IGF.getLoweredSingletonExplosion(parameter); }); } /// Get metadata for the dynamic Self type if we have it. static void emitLocalSelfMetadata(IRGenSILFunction &IGF) { if (!IGF.CurSILFn->hasSelfMetadataParam()) return; const SILArgument *selfArg = IGF.CurSILFn->getSelfMetadataArgument(); CanMetatypeType metaTy = dyn_cast<MetatypeType>(selfArg->getType().getSwiftRValueType()); IRGenFunction::LocalSelfKind selfKind; if (!metaTy) selfKind = IRGenFunction::ObjectReference; else switch (metaTy->getRepresentation()) { case MetatypeRepresentation::Thin: llvm_unreachable("class metatypes are never thin"); case MetatypeRepresentation::Thick: selfKind = IRGenFunction::SwiftMetatype; break; case MetatypeRepresentation::ObjC: selfKind = IRGenFunction::ObjCMetatype; break; } llvm::Value *value = IGF.getLoweredExplosion(selfArg).claimNext(); IGF.setLocalSelfMetadata(value, selfKind); } /// Emit the definition for the given SIL constant. void IRGenModule::emitSILFunction(SILFunction *f) { if (f->isExternalDeclaration()) return; PrettyStackTraceSILFunction stackTrace("emitting IR", f); IRGenSILFunction(*this, f).emitSILFunction(); } void IRGenSILFunction::emitSILFunction() { DEBUG(llvm::dbgs() << "emitting SIL function: "; CurSILFn->printName(llvm::dbgs()); llvm::dbgs() << '\n'; CurSILFn->print(llvm::dbgs())); assert(!CurSILFn->empty() && "function has no basic blocks?!"); // Configure the dominance resolver. // TODO: consider re-using a dom analysis from the PassManager // TODO: consider using a cheaper analysis at -O0 setDominanceResolver([](IRGenFunction &IGF_, DominancePoint activePoint, DominancePoint dominatingPoint) -> bool { IRGenSILFunction &IGF = static_cast<IRGenSILFunction&>(IGF_); if (!IGF.Dominance) { IGF.Dominance.reset(new DominanceInfo(IGF.CurSILFn)); } return IGF.Dominance->dominates(dominatingPoint.as<SILBasicBlock>(), activePoint.as<SILBasicBlock>()); }); if (IGM.DebugInfo) IGM.DebugInfo->emitFunction(*CurSILFn, CurFn); // Map the entry bb. LoweredBBs[&*CurSILFn->begin()] = LoweredBB(&*CurFn->begin(), {}); // Create LLVM basic blocks for the other bbs. for (auto bi = std::next(CurSILFn->begin()), be = CurSILFn->end(); bi != be; ++bi) { // FIXME: Use the SIL basic block's name. llvm::BasicBlock *llBB = llvm::BasicBlock::Create(IGM.getLLVMContext()); auto phis = emitPHINodesForBBArgs(*this, &*bi, llBB); CurFn->getBasicBlockList().push_back(llBB); LoweredBBs[&*bi] = LoweredBB(llBB, std::move(phis)); } auto entry = LoweredBBs.begin(); Builder.SetInsertPoint(entry->second.bb); // Map the LLVM arguments to arguments on the entry point BB. Explosion params = collectParameters(); auto funcTy = CurSILFn->getLoweredFunctionType(); switch (funcTy->getLanguage()) { case SILFunctionLanguage::Swift: emitEntryPointArgumentsNativeCC(*this, entry->first, params); break; case SILFunctionLanguage::C: emitEntryPointArgumentsCOrObjC(*this, entry->first, params, funcTy); break; } emitLocalSelfMetadata(*this); assert(params.empty() && "did not map all llvm params to SIL params?!"); // It's really nice to be able to assume that we've already emitted // all the values from dominating blocks --- it makes simple // peepholing more powerful and allows us to avoid the need for // nasty "forward-declared" values. We can do this by emitting // blocks using a simple walk through the successor graph. // // We do want to preserve the original source order, but that's done // by having previously added all the primary blocks to the LLVM // function in their original order. As long as any secondary // blocks are inserted after the current IP instead of at the end // of the function, we're fine. // Invariant: for every block in the work queue, we have visited all // of its dominators. llvm::SmallPtrSet<SILBasicBlock*, 8> visitedBlocks; SmallVector<SILBasicBlock*, 8> workQueue; // really a stack // Queue up the entry block, for which the invariant trivially holds. visitedBlocks.insert(&*CurSILFn->begin()); workQueue.push_back(&*CurSILFn->begin()); while (!workQueue.empty()) { auto bb = workQueue.pop_back_val(); // Emit the block. visitSILBasicBlock(bb); #ifndef NDEBUG // Assert that the current IR IP (if valid) is immediately prior // to the initial IR block for the next primary SIL block. // It's not semantically necessary to preserve SIL block order, // but we really should. if (auto curBB = Builder.GetInsertBlock()) { auto next = std::next(SILFunction::iterator(bb)); if (next != CurSILFn->end()) { auto nextBB = LoweredBBs[&*next].bb; assert(&*std::next(curBB->getIterator()) == nextBB && "lost source SIL order?"); } } #endif // The immediate dominator of a successor of this block needn't be // this block, but it has to be something which dominates this // block. In either case, we've visited it. // // Therefore the invariant holds of all the successors, and we can // queue them up if we haven't already visited them. for (auto *succBB : bb->getSuccessorBlocks()) { if (visitedBlocks.insert(succBB).second) workQueue.push_back(succBB); } } // If there are dead blocks in the SIL function, we might have left // invalid blocks in the IR. Do another pass and kill them off. for (SILBasicBlock &bb : *CurSILFn) if (!visitedBlocks.count(&bb)) LoweredBBs[&bb].bb->eraseFromParent(); } void IRGenSILFunction::estimateStackSize() { if (EstimatedStackSize >= 0) return; // TODO: as soon as we generate alloca instructions with accurate lifetimes // we should also do a better stack size calculation here. Currently we // add all stack sizes even if life ranges do not overlap. for (SILBasicBlock &BB : *CurSILFn) { for (SILInstruction &I : BB) { if (auto *ASI = dyn_cast<AllocStackInst>(&I)) { const TypeInfo &type = getTypeInfo(ASI->getElementType()); if (llvm::Constant *SizeConst = type.getStaticSize(IGM)) { auto *SizeInt = cast<llvm::ConstantInt>(SizeConst); EstimatedStackSize += (int)SizeInt->getSExtValue(); } } } } } void IRGenSILFunction::visitSILBasicBlock(SILBasicBlock *BB) { // Insert into the lowered basic block. llvm::BasicBlock *llBB = getLoweredBB(BB).bb; Builder.SetInsertPoint(llBB); bool InEntryBlock = BB->pred_empty(); // Set this block as the dominance point. This implicitly communicates // with the dominance resolver configured in emitSILFunction. DominanceScope dominance(*this, InEntryBlock ? DominancePoint::universal() : DominancePoint(BB)); // The basic blocks are visited in a random order. Reset the debug location. std::unique_ptr<AutoRestoreLocation> ScopedLoc; if (InEntryBlock) ScopedLoc = llvm::make_unique<PrologueLocation>(IGM.DebugInfo, Builder); else ScopedLoc = llvm::make_unique<ArtificialLocation>( CurSILFn->getDebugScope(), IGM.DebugInfo, Builder); // Generate the body. bool InCleanupBlock = false; bool KeepCurrentLocation = false; for (auto InsnIter = BB->begin(); InsnIter != BB->end(); ++InsnIter) { auto &I = *InsnIter; if (IGM.DebugInfo) { // Set the debug info location for I, if applicable. SILLocation ILoc = I.getLoc(); auto DS = I.getDebugScope(); // Handle cleanup locations. if (ILoc.is<CleanupLocation>()) { // Cleanup locations point to the decl of the value that is // being destroyed (for diagnostic generation). As far as // the linetable is concerned, cleanups at the end of a // lexical scope should point to the cleanup location, which // is the location of the last instruction in the basic block. if (!InCleanupBlock) { InCleanupBlock = true; // Scan ahead to see if this is the final cleanup block in // this basic block. auto It = InsnIter; do ++It; while (It != BB->end() && It->getLoc().is<CleanupLocation>()); // We are still in the middle of a basic block? if (It != BB->end() && !isa<TermInst>(It)) KeepCurrentLocation = true; } // Assign the cleanup location to this instruction. if (!KeepCurrentLocation) { assert(BB->getTerminator()); ILoc = BB->getTerminator()->getLoc(); DS = BB->getTerminator()->getDebugScope(); } } else if (InCleanupBlock) { KeepCurrentLocation = false; InCleanupBlock = false; } // Until SILDebugScopes are properly serialized, bare functions // are allowed to not have a scope. if (!DS) { if (CurSILFn->isBare()) DS = CurSILFn->getDebugScope(); assert(maybeScopeless(I) && "instruction has location, but no scope"); } // Set the builder's debug location. if (DS && !KeepCurrentLocation) IGM.DebugInfo->setCurrentLoc(Builder, DS, ILoc); else // Use an artificial (line 0) location. IGM.DebugInfo->setCurrentLoc(Builder, DS); if (isa<TermInst>(&I)) emitDebugVariableRangeExtension(BB); } visit(&I); } assert(Builder.hasPostTerminatorIP() && "SIL bb did not terminate block?!"); } void IRGenSILFunction::visitFunctionRefInst(FunctionRefInst *i) { auto fn = i->getReferencedFunction(); llvm::Function *fnptr = IGM.getAddrOfSILFunction(fn, NotForDefinition); auto foreignInfo = IGM.getForeignFunctionInfo(fn->getLoweredFunctionType()); // Store the function constant and calling // convention as a StaticFunction so we can avoid bitcasting or thunking if // we don't need to. setLoweredStaticFunction(i, fnptr, fn->getRepresentation(), foreignInfo); } void IRGenSILFunction::visitAllocGlobalInst(AllocGlobalInst *i) { SILGlobalVariable *var = i->getReferencedGlobal(); SILType loweredTy = var->getLoweredType(); auto &ti = getTypeInfo(loweredTy); auto expansion = IGM.getResilienceExpansionForLayout(var); // If the global is fixed-size in all resilience domains that can see it, // we allocated storage for it statically, and there's nothing to do. if (ti.isFixedSize(expansion)) return; // Otherwise, the static storage for the global consists of a fixed-size // buffer. Address addr = IGM.getAddrOfSILGlobalVariable(var, ti, NotForDefinition); if (getSILModule().getOptions().UseCOWExistentials) { emitAllocateValueInBuffer(*this, loweredTy, addr); } else { (void) ti.allocateBuffer(*this, addr, loweredTy); } } void IRGenSILFunction::visitGlobalAddrInst(GlobalAddrInst *i) { SILGlobalVariable *var = i->getReferencedGlobal(); SILType loweredTy = var->getLoweredType(); assert(loweredTy == i->getType().getObjectType()); auto &ti = getTypeInfo(loweredTy); auto expansion = IGM.getResilienceExpansionForLayout(var); // If the variable is empty in all resilience domains that can see it, // don't actually emit a symbol for the global at all, just return undef. if (ti.isKnownEmpty(expansion)) { setLoweredAddress(i, ti.getUndefAddress()); return; } Address addr = IGM.getAddrOfSILGlobalVariable(var, ti, NotForDefinition); // If the global is fixed-size in all resilience domains that can see it, // we allocated storage for it statically, and there's nothing to do. if (ti.isFixedSize(expansion)) { setLoweredAddress(i, addr); return; } // Otherwise, the static storage for the global consists of a fixed-size // buffer; project it. if (getSILModule().getOptions().UseCOWExistentials) { addr = emitProjectValueInBuffer(*this, loweredTy, addr); } else { addr = ti.projectBuffer(*this, addr, loweredTy); } setLoweredAddress(i, addr); } void IRGenSILFunction::visitMetatypeInst(swift::MetatypeInst *i) { auto metaTy = i->getType().castTo<MetatypeType>(); Explosion e; emitMetatypeRef(*this, metaTy, e); setLoweredExplosion(i, e); } static llvm::Value *getClassBaseValue(IRGenSILFunction &IGF, SILValue v) { if (v->getType().isAddress()) { auto addr = IGF.getLoweredAddress(v); return IGF.Builder.CreateLoad(addr); } Explosion e = IGF.getLoweredExplosion(v); return e.claimNext(); } static llvm::Value *getClassMetatype(IRGenFunction &IGF, llvm::Value *baseValue, MetatypeRepresentation repr, SILType instanceType) { switch (repr) { case MetatypeRepresentation::Thin: llvm_unreachable("Class metatypes are never thin"); case MetatypeRepresentation::Thick: return emitDynamicTypeOfHeapObject(IGF, baseValue, instanceType); case MetatypeRepresentation::ObjC: return emitHeapMetadataRefForHeapObject(IGF, baseValue, instanceType); } llvm_unreachable("Not a valid MetatypeRepresentation."); } void IRGenSILFunction::visitValueMetatypeInst(swift::ValueMetatypeInst *i) { SILType instanceTy = i->getOperand()->getType(); auto metaTy = i->getType().castTo<MetatypeType>(); if (metaTy->getRepresentation() == MetatypeRepresentation::Thin) { Explosion empty; setLoweredExplosion(i, empty); return; } Explosion e; if (instanceTy.getClassOrBoundGenericClass()) { e.add(getClassMetatype(*this, getClassBaseValue(*this, i->getOperand()), metaTy->getRepresentation(), instanceTy)); } else if (auto arch = instanceTy.getAs<ArchetypeType>()) { if (arch->requiresClass()) { e.add(getClassMetatype(*this, getClassBaseValue(*this, i->getOperand()), metaTy->getRepresentation(), instanceTy)); } else { Address base = getLoweredAddress(i->getOperand()); e.add(emitDynamicTypeOfOpaqueArchetype(*this, base, i->getOperand()->getType())); // FIXME: We need to convert this back to an ObjC class for an // ObjC metatype representation. if (metaTy->getRepresentation() == MetatypeRepresentation::ObjC) unimplemented(i->getLoc().getSourceLoc(), "objc metatype of non-class-bounded archetype"); } } else { emitMetatypeRef(*this, metaTy, e); } setLoweredExplosion(i, e); } void IRGenSILFunction::visitExistentialMetatypeInst( swift::ExistentialMetatypeInst *i) { Explosion result; SILValue op = i->getOperand(); SILType opType = op->getType(); switch (opType.getPreferredExistentialRepresentation(IGM.getSILModule())) { case ExistentialRepresentation::Metatype: { Explosion existential = getLoweredExplosion(op); emitMetatypeOfMetatype(*this, existential, opType, result); break; } case ExistentialRepresentation::Class: { Explosion existential = getLoweredExplosion(op); emitMetatypeOfClassExistential(*this, existential, i->getType(), opType, result); break; } case ExistentialRepresentation::Boxed: { Explosion existential = getLoweredExplosion(op); emitMetatypeOfBoxedExistential(*this, existential, opType, result); break; } case ExistentialRepresentation::Opaque: { Address existential = getLoweredAddress(op); emitMetatypeOfOpaqueExistential(*this, existential, opType, result); break; } case ExistentialRepresentation::None: llvm_unreachable("Bad existential representation"); } setLoweredExplosion(i, result); } static void emitApplyArgument(IRGenSILFunction &IGF, SILValue arg, SILType paramType, Explosion &out) { bool isSubstituted = (arg->getType() != paramType); // For indirect arguments, we just need to pass a pointer. if (paramType.isAddress()) { // This address is of the substituted type. auto addr = IGF.getLoweredAddress(arg); // If a substitution is in play, just bitcast the address. if (isSubstituted) { auto origType = IGF.IGM.getStoragePointerType(paramType); addr = IGF.Builder.CreateBitCast(addr, origType); } out.add(addr.getAddress()); return; } // Otherwise, it's an explosion, which we may need to translate, // both in terms of explosion level and substitution levels. assert(arg->getType().isObject()); // Fast path: avoid an unnecessary temporary explosion. if (!isSubstituted) { IGF.getLoweredExplosion(arg, out); return; } Explosion temp = IGF.getLoweredExplosion(arg); reemitAsUnsubstituted(IGF, paramType, arg->getType(), temp, out); } static llvm::Value *getObjCClassForValue(IRGenSILFunction &IGF, llvm::Value *selfValue, CanAnyMetatypeType selfType) { // If we have a Swift metatype, map it to the heap metadata, which // will be the Class for an ObjC type. switch (selfType->getRepresentation()) { case swift::MetatypeRepresentation::ObjC: return selfValue; case swift::MetatypeRepresentation::Thick: // Convert thick metatype to Objective-C metatype. return emitClassHeapMetadataRefForMetatype(IGF, selfValue, selfType.getInstanceType()); case swift::MetatypeRepresentation::Thin: llvm_unreachable("Cannot convert Thin metatype to ObjC metatype"); } llvm_unreachable("bad metatype representation"); } static llvm::Value *emitWitnessTableForLoweredCallee(IRGenSILFunction &IGF, CanSILFunctionType origCalleeType, SubstitutionList subs) { auto &M = *IGF.getSwiftModule(); llvm::Value *wtable; if (auto *proto = origCalleeType->getDefaultWitnessMethodProtocol(M)) { // The generic signature for a witness method with abstract Self must // have exactly one protocol requirement. // // We recover the witness table from the substitution that was used to // produce the substituted callee type. auto subMap = origCalleeType->getGenericSignature() ->getSubstitutionMap(subs); auto origSelfType = proto->getSelfInterfaceType()->getCanonicalType(); auto substSelfType = origSelfType.subst(subMap)->getCanonicalType(); auto conformance = *subMap.lookupConformance(origSelfType, proto); llvm::Value *argMetadata = IGF.emitTypeMetadataRef(substSelfType); wtable = emitWitnessTableRef(IGF, substSelfType, &argMetadata, conformance); } else { // Otherwise, we have no way of knowing the original protocol or // conformance, since the witness has a concrete self type. // // Protocol witnesses for concrete types are thus not allowed to touch // the witness table; they already know all the witnesses, and we can't // say who they are. wtable = llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy); } assert(wtable->getType() == IGF.IGM.WitnessTablePtrTy); return wtable; } static CallEmission getCallEmissionForLoweredValue(IRGenSILFunction &IGF, CanSILFunctionType origCalleeType, CanSILFunctionType substCalleeType, const LoweredValue &lv, llvm::Value *selfValue, SubstitutionList substitutions, WitnessMetadata *witnessMetadata, Explosion &args) { llvm::Value *calleeFn, *calleeData; ForeignFunctionInfo foreignInfo; switch (lv.kind) { case LoweredValue::Kind::StaticFunction: calleeFn = lv.getStaticFunction().getFunction(); calleeData = selfValue; foreignInfo = lv.getStaticFunction().getForeignInfo(); if (origCalleeType->getRepresentation() == SILFunctionType::Representation::WitnessMethod) { llvm::Value *wtable = emitWitnessTableForLoweredCallee( IGF, origCalleeType, substitutions); witnessMetadata->SelfWitnessTable = wtable; } break; case LoweredValue::Kind::ObjCMethod: { assert(selfValue); auto &objcMethod = lv.getObjCMethod(); ObjCMessageKind kind = objcMethod.getMessageKind(); CallEmission emission = prepareObjCMethodRootCall(IGF, objcMethod.getMethod(), origCalleeType, substCalleeType, substitutions, kind); // Convert a metatype 'self' argument to the ObjC Class pointer. // FIXME: Should be represented in SIL. if (auto metatype = dyn_cast<AnyMetatypeType>( origCalleeType->getSelfParameter().getType())) { selfValue = getObjCClassForValue(IGF, selfValue, metatype); } addObjCMethodCallImplicitArguments(IGF, args, objcMethod.getMethod(), selfValue, objcMethod.getSearchType()); return emission; } case LoweredValue::Kind::Explosion: { switch (origCalleeType->getRepresentation()) { case SILFunctionType::Representation::Block: { assert(!selfValue && "block function with self?"); // Grab the block pointer and make it the first physical argument. llvm::Value *blockPtr = lv.getSingletonExplosion(IGF); blockPtr = IGF.Builder.CreateBitCast(blockPtr, IGF.IGM.ObjCBlockPtrTy); args.add(blockPtr); // Extract the invocation pointer for blocks. llvm::Value *invokeAddr = IGF.Builder.CreateStructGEP( /*Ty=*/nullptr, blockPtr, 3); calleeFn = IGF.Builder.CreateLoad(invokeAddr, IGF.IGM.getPointerAlignment()); calleeData = nullptr; break; } case SILFunctionType::Representation::Thin: case SILFunctionType::Representation::CFunctionPointer: case SILFunctionType::Representation::Method: case SILFunctionType::Representation::Closure: case SILFunctionType::Representation::ObjCMethod: case SILFunctionType::Representation::WitnessMethod: case SILFunctionType::Representation::Thick: { Explosion calleeValues = lv.getExplosion(IGF); calleeFn = calleeValues.claimNext(); if (origCalleeType->getRepresentation() == SILFunctionType::Representation::WitnessMethod) { witnessMetadata->SelfWitnessTable = emitWitnessTableForLoweredCallee( IGF, origCalleeType, substitutions); } if (origCalleeType->getRepresentation() == SILFunctionType::Representation::Thick) { // @convention(thick) callees are exploded as a pair // consisting of the function and the self value. assert(!selfValue); calleeData = calleeValues.claimNext(); } else { calleeData = selfValue; } break; } } // Cast the callee pointer to the right function type. llvm::AttributeSet attrs; llvm::FunctionType *fnTy = IGF.IGM.getFunctionType(origCalleeType, attrs, &foreignInfo); calleeFn = IGF.Builder.CreateBitCast(calleeFn, fnTy->getPointerTo()); break; } case LoweredValue::Kind::BoxWithAddress: llvm_unreachable("@box isn't a valid callee"); case LoweredValue::Kind::ContainedAddress: case LoweredValue::Kind::Address: llvm_unreachable("sil address isn't a valid callee"); } Callee callee = Callee::forKnownFunction(origCalleeType, substCalleeType, substitutions, calleeFn, calleeData, foreignInfo); CallEmission callEmission(IGF, callee); if (IGF.CurSILFn->isThunk()) callEmission.addAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoInline); return callEmission; } void IRGenSILFunction::visitBuiltinInst(swift::BuiltinInst *i) { auto argValues = i->getArguments(); Explosion args; for (auto argValue : argValues) { // Builtin arguments should never be substituted, so use the value's type // as the parameter type. emitApplyArgument(*this, argValue, argValue->getType(), args); } Explosion result; emitBuiltinCall(*this, i->getName(), i->getType(), args, result, i->getSubstitutions()); setLoweredExplosion(i, result); } void IRGenSILFunction::visitApplyInst(swift::ApplyInst *i) { visitFullApplySite(i); } void IRGenSILFunction::visitTryApplyInst(swift::TryApplyInst *i) { visitFullApplySite(i); } void IRGenSILFunction::visitFullApplySite(FullApplySite site) { const LoweredValue &calleeLV = getLoweredValue(site.getCallee()); auto origCalleeType = site.getOrigCalleeType(); auto substCalleeType = site.getSubstCalleeType(); auto args = site.getArguments(); SILFunctionConventions origConv(origCalleeType, getSILModule()); assert(origConv.getNumSILArguments() == args.size()); // Extract 'self' if it needs to be passed as the context parameter. llvm::Value *selfValue = nullptr; if (origCalleeType->hasSelfParam() && isSelfContextParameter(origCalleeType->getSelfParameter())) { SILValue selfArg = args.back(); args = args.drop_back(); if (selfArg->getType().isObject()) { selfValue = getLoweredSingletonExplosion(selfArg); } else { selfValue = getLoweredAddress(selfArg).getAddress(); } } Explosion llArgs; WitnessMetadata witnessMetadata; CallEmission emission = getCallEmissionForLoweredValue(*this, origCalleeType, substCalleeType, calleeLV, selfValue, site.getSubstitutions(), &witnessMetadata, llArgs); // Lower the arguments and return value in the callee's generic context. GenericContextScope scope(IGM, origCalleeType->getGenericSignature()); // Lower the SIL arguments to IR arguments. // Turn the formal SIL parameters into IR-gen things. for (auto index : indices(args)) { emitApplyArgument(*this, args[index], origConv.getSILArgumentType(index), llArgs); } // Pass the generic arguments. if (hasPolymorphicParameters(origCalleeType)) { SubstitutionMap subMap; if (auto genericSig = origCalleeType->getGenericSignature()) subMap = genericSig->getSubstitutionMap(site.getSubstitutions()); emitPolymorphicArguments(*this, origCalleeType, substCalleeType, subMap, &witnessMetadata, llArgs); } // Add all those arguments. emission.setArgs(llArgs, &witnessMetadata); SILInstruction *i = site.getInstruction(); Explosion result; emission.emitToExplosion(result); if (isa<ApplyInst>(i)) { setLoweredExplosion(i, result); } else { auto tryApplyInst = cast<TryApplyInst>(i); // Load the error value. SILFunctionConventions substConv(substCalleeType, getSILModule()); SILType errorType = substConv.getSILErrorType(); Address errorSlot = getErrorResultSlot(errorType); auto errorValue = Builder.CreateLoad(errorSlot); auto &normalDest = getLoweredBB(tryApplyInst->getNormalBB()); auto &errorDest = getLoweredBB(tryApplyInst->getErrorBB()); // Zero the error slot to maintain the invariant that it always // contains null. This will frequently become a dead store. auto nullError = llvm::Constant::getNullValue(errorValue->getType()); if (!tryApplyInst->getErrorBB()->getSinglePredecessorBlock()) { // Only do that here if we can't move the store to the error block. // See below. Builder.CreateStore(nullError, errorSlot); } // If the error value is non-null, branch to the error destination. auto hasError = Builder.CreateICmpNE(errorValue, nullError); Builder.CreateCondBr(hasError, errorDest.bb, normalDest.bb); // Set up the PHI nodes on the normal edge. unsigned firstIndex = 0; addIncomingExplosionToPHINodes(*this, normalDest, firstIndex, result); assert(firstIndex == normalDest.phis.size()); // Set up the PHI nodes on the error edge. assert(errorDest.phis.size() == 1); errorDest.phis[0]->addIncoming(errorValue, Builder.GetInsertBlock()); if (tryApplyInst->getErrorBB()->getSinglePredecessorBlock()) { // Zeroing out the error slot only in the error block increases the chance // that it will become a dead store. auto origBB = Builder.GetInsertBlock(); Builder.SetInsertPoint(errorDest.bb); Builder.CreateStore(nullError, errorSlot); Builder.SetInsertPoint(origBB); } } } /// If the value is a @convention(witness_method) function, the context /// is the witness table that must be passed to the call. /// /// \param v A value of possibly-polymorphic SILFunctionType. /// \param subs This is the set of substitutions that we are going to be /// applying to 'v'. static std::tuple<llvm::Value*, llvm::Value*, CanSILFunctionType> getPartialApplicationFunction(IRGenSILFunction &IGF, SILValue v, SubstitutionList subs) { LoweredValue &lv = IGF.getLoweredValue(v); auto fnType = v->getType().castTo<SILFunctionType>(); switch (lv.kind) { case LoweredValue::Kind::ContainedAddress: case LoweredValue::Kind::Address: llvm_unreachable("can't partially apply an address"); case LoweredValue::Kind::BoxWithAddress: llvm_unreachable("can't partially apply a @box"); case LoweredValue::Kind::ObjCMethod: llvm_unreachable("objc method partial application shouldn't get here"); case LoweredValue::Kind::StaticFunction: { llvm::Value *context = nullptr; switch (lv.getStaticFunction().getRepresentation()) { case SILFunctionTypeRepresentation::CFunctionPointer: case SILFunctionTypeRepresentation::Block: case SILFunctionTypeRepresentation::ObjCMethod: assert(false && "partial_apply of foreign functions not implemented"); break; case SILFunctionTypeRepresentation::WitnessMethod: context = emitWitnessTableForLoweredCallee(IGF, fnType, subs); break; case SILFunctionTypeRepresentation::Thick: case SILFunctionTypeRepresentation::Thin: case SILFunctionTypeRepresentation::Method: case SILFunctionTypeRepresentation::Closure: break; } return std::make_tuple(lv.getStaticFunction().getFunction(), context, v->getType().castTo<SILFunctionType>()); } case LoweredValue::Kind::Explosion: { Explosion ex = lv.getExplosion(IGF); llvm::Value *fn = ex.claimNext(); llvm::Value *context = nullptr; switch (fnType->getRepresentation()) { case SILFunctionType::Representation::Thin: case SILFunctionType::Representation::Method: case SILFunctionType::Representation::Closure: case SILFunctionType::Representation::ObjCMethod: break; case SILFunctionType::Representation::WitnessMethod: context = emitWitnessTableForLoweredCallee(IGF, fnType, subs); break; case SILFunctionType::Representation::CFunctionPointer: break; case SILFunctionType::Representation::Thick: context = ex.claimNext(); break; case SILFunctionType::Representation::Block: llvm_unreachable("partial application of block not implemented"); } return std::make_tuple(fn, context, fnType); } } llvm_unreachable("Not a valid SILFunctionType."); } void IRGenSILFunction::visitPartialApplyInst(swift::PartialApplyInst *i) { SILValue v(i); // NB: We collect the arguments under the substituted type. auto args = i->getArguments(); auto params = i->getSubstCalleeType()->getParameters(); params = params.slice(params.size() - args.size(), args.size()); Explosion llArgs; { // Lower the parameters in the callee's generic context. GenericContextScope scope(IGM, i->getOrigCalleeType()->getGenericSignature()); for (auto index : indices(args)) { assert(args[index]->getType() == IGM.silConv.getSILType(params[index])); emitApplyArgument(*this, args[index], IGM.silConv.getSILType(params[index]), llArgs); } } auto &lv = getLoweredValue(i->getCallee()); if (lv.kind == LoweredValue::Kind::ObjCMethod) { // Objective-C partial applications require a different path. There's no // actual function pointer to capture, and we semantically can't cache // dispatch, so we need to perform the message send in the partial // application thunk. auto &objcMethod = lv.getObjCMethod(); assert(i->getArguments().size() == 1 && "only partial application of objc method to self implemented"); assert(llArgs.size() == 1 && "objc partial_apply argument is not a single retainable pointer?!"); llvm::Value *selfVal = llArgs.claimNext(); Explosion function; emitObjCPartialApplication(*this, objcMethod, i->getOrigCalleeType(), i->getType().castTo<SILFunctionType>(), selfVal, i->getArguments()[0]->getType(), function); setLoweredExplosion(i, function); return; } // Get the function value. llvm::Value *calleeFn = nullptr; llvm::Value *innerContext = nullptr; CanSILFunctionType origCalleeTy; std::tie(calleeFn, innerContext, origCalleeTy) = getPartialApplicationFunction(*this, i->getCallee(), i->getSubstitutions()); // Create the thunk and function value. Explosion function; emitFunctionPartialApplication(*this, *CurSILFn, calleeFn, innerContext, llArgs, params, i->getSubstitutions(), origCalleeTy, i->getSubstCalleeType(), i->getType().castTo<SILFunctionType>(), function); setLoweredExplosion(v, function); } void IRGenSILFunction::visitIntegerLiteralInst(swift::IntegerLiteralInst *i) { llvm::Value *constant = emitConstantInt(IGM, i); Explosion e; e.add(constant); setLoweredExplosion(i, e); } void IRGenSILFunction::visitFloatLiteralInst(swift::FloatLiteralInst *i) { llvm::Value *constant = emitConstantFP(IGM, i); Explosion e; e.add(constant); setLoweredExplosion(i, e); } void IRGenSILFunction::visitStringLiteralInst(swift::StringLiteralInst *i) { llvm::Value *addr; // Emit a load of a selector. if (i->getEncoding() == swift::StringLiteralInst::Encoding::ObjCSelector) addr = emitObjCSelectorRefLoad(i->getValue()); else addr = emitAddrOfConstantString(IGM, i); Explosion e; e.add(addr); setLoweredExplosion(i, e); } void IRGenSILFunction::visitUnreachableInst(swift::UnreachableInst *i) { Builder.CreateUnreachable(); } static void emitReturnInst(IRGenSILFunction &IGF, SILType resultTy, Explosion &result) { // The invariant on the out-parameter is that it's always zeroed, so // there's nothing to do here. // Even if SIL has a direct return, the IR-level calling convention may // require an indirect return. if (IGF.IndirectReturn.isValid()) { auto &retTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(resultTy)); retTI.initialize(IGF, result, IGF.IndirectReturn); IGF.Builder.CreateRetVoid(); } else { auto funcLang = IGF.CurSILFn->getLoweredFunctionType()->getLanguage(); auto swiftCCReturn = funcLang == SILFunctionLanguage::Swift; assert(swiftCCReturn || funcLang == SILFunctionLanguage::C && "Need to handle all cases"); IGF.emitScalarReturn(resultTy, result, swiftCCReturn); } } void IRGenSILFunction::visitReturnInst(swift::ReturnInst *i) { Explosion result = getLoweredExplosion(i->getOperand()); // Implicitly autorelease the return value if the function's result // convention is autoreleased. auto fnConv = CurSILFn->getConventions(); if (fnConv.getNumDirectSILResults() == 1 && (fnConv.getDirectSILResults().begin()->getConvention() == ResultConvention::Autoreleased)) { Explosion temp; temp.add(emitObjCAutoreleaseReturnValue(*this, result.claimNext())); result = std::move(temp); } emitReturnInst(*this, i->getOperand()->getType(), result); } void IRGenSILFunction::visitThrowInst(swift::ThrowInst *i) { // Store the exception to the error slot. llvm::Value *exn = getLoweredSingletonExplosion(i->getOperand()); Builder.CreateStore(exn, getCallerErrorResultSlot()); // Create a normal return, but leaving the return value undefined. auto fnTy = CurFn->getType()->getPointerElementType(); auto retTy = cast<llvm::FunctionType>(fnTy)->getReturnType(); if (retTy->isVoidTy()) { Builder.CreateRetVoid(); } else { Builder.CreateRet(llvm::UndefValue::get(retTy)); } } static llvm::BasicBlock *emitBBMapForSwitchValue( IRGenSILFunction &IGF, SmallVectorImpl<std::pair<SILValue, llvm::BasicBlock*>> &dests, SwitchValueInst *inst) { for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); dests.push_back({casePair.first, IGF.getLoweredBB(casePair.second).bb}); } llvm::BasicBlock *defaultDest = nullptr; if (inst->hasDefault()) defaultDest = IGF.getLoweredBB(inst->getDefaultBB()).bb; return defaultDest; } static llvm::ConstantInt * getSwitchCaseValue(IRGenFunction &IGF, SILValue val) { if (auto *IL = dyn_cast<IntegerLiteralInst>(val)) { return dyn_cast<llvm::ConstantInt>(emitConstantInt(IGF.IGM, IL)); } else { llvm_unreachable("Switch value cases should be integers"); } } static void emitSwitchValueDispatch(IRGenSILFunction &IGF, SILType ty, Explosion &value, ArrayRef<std::pair<SILValue, llvm::BasicBlock*>> dests, llvm::BasicBlock *defaultDest) { // Create an unreachable block for the default if the original SIL // instruction had none. bool unreachableDefault = false; if (!defaultDest) { unreachableDefault = true; defaultDest = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext()); } if (ty.is<BuiltinIntegerType>()) { auto *discriminator = value.claimNext(); auto *i = IGF.Builder.CreateSwitch(discriminator, defaultDest, dests.size()); for (auto &dest : dests) i->addCase(getSwitchCaseValue(IGF, dest.first), dest.second); } else { // Get the value we're testing, which is a function. llvm::Value *val; llvm::BasicBlock *nextTest = nullptr; if (ty.is<SILFunctionType>()) { val = value.claimNext(); // Function pointer. //values.claimNext(); // Ignore the data pointer. } else { llvm_unreachable("switch_value operand has an unknown type"); } for (int i = 0, e = dests.size(); i < e; ++i) { auto casePair = dests[i]; llvm::Value *caseval; auto casevalue = IGF.getLoweredExplosion(casePair.first); if (casePair.first->getType().is<SILFunctionType>()) { caseval = casevalue.claimNext(); // Function pointer. //values.claimNext(); // Ignore the data pointer. } else { llvm_unreachable("switch_value operand has an unknown type"); } // Compare operand with a case tag value. llvm::Value *cond = IGF.Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, val, caseval); if (i == e -1 && !unreachableDefault) { nextTest = nullptr; IGF.Builder.CreateCondBr(cond, casePair.second, defaultDest); } else { nextTest = IGF.createBasicBlock("next-test"); IGF.Builder.CreateCondBr(cond, casePair.second, nextTest); IGF.Builder.emitBlock(nextTest); IGF.Builder.SetInsertPoint(nextTest); } } if (nextTest) { IGF.Builder.CreateBr(defaultDest); } } if (unreachableDefault) { IGF.Builder.emitBlock(defaultDest); IGF.Builder.CreateUnreachable(); } } void IRGenSILFunction::visitSwitchValueInst(SwitchValueInst *inst) { Explosion value = getLoweredExplosion(inst->getOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<SILValue, llvm::BasicBlock*>, 4> dests; auto *defaultDest = emitBBMapForSwitchValue(*this, dests, inst); emitSwitchValueDispatch(*this, inst->getOperand()->getType(), value, dests, defaultDest); } // Bind an incoming explosion value to an explosion of LLVM phi node(s). static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF, ArrayRef<llvm::Value*> phis, Explosion &argValue) { llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock(); unsigned phiIndex = 0; while (!argValue.empty()) cast<llvm::PHINode>(phis[phiIndex++]) ->addIncoming(argValue.claimNext(), curBB); assert(phiIndex == phis.size() && "explosion doesn't match number of phis"); } // Bind an incoming explosion value to a SILArgument's LLVM phi node(s). static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF, LoweredBB &lbb, unsigned &phiIndex, Explosion &argValue) { llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock(); while (!argValue.empty()) lbb.phis[phiIndex++]->addIncoming(argValue.claimNext(), curBB); } // Bind an incoming address value to a SILArgument's LLVM phi node(s). static void addIncomingAddressToPHINodes(IRGenSILFunction &IGF, ArrayRef<llvm::Value*> phis, Address argValue) { llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock(); assert(phis.size() == 1 && "more than one phi for address?!"); cast<llvm::PHINode>(phis[0])->addIncoming(argValue.getAddress(), curBB); } // Bind an incoming address value to a SILArgument's LLVM phi node(s). static void addIncomingAddressToPHINodes(IRGenSILFunction &IGF, LoweredBB &lbb, unsigned &phiIndex, Address argValue) { llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock(); lbb.phis[phiIndex++]->addIncoming(argValue.getAddress(), curBB); } // Add branch arguments to destination phi nodes. static void addIncomingSILArgumentsToPHINodes(IRGenSILFunction &IGF, LoweredBB &lbb, OperandValueArrayRef args) { unsigned phiIndex = 0; for (SILValue arg : args) { const LoweredValue &lv = IGF.getLoweredValue(arg); if (lv.isAddress()) { addIncomingAddressToPHINodes(IGF, lbb, phiIndex, lv.getAddress()); continue; } Explosion argValue = lv.getExplosion(IGF); addIncomingExplosionToPHINodes(IGF, lbb, phiIndex, argValue); } } static llvm::BasicBlock *emitBBMapForSwitchEnum( IRGenSILFunction &IGF, SmallVectorImpl<std::pair<EnumElementDecl*, llvm::BasicBlock*>> &dests, SwitchEnumInstBase *inst) { for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); // If the destination BB accepts the case argument, set up a waypoint BB so // we can feed the values into the argument's PHI node(s). // // FIXME: This is cheesy when the destination BB has only the switch // as a predecessor. if (!casePair.second->args_empty()) dests.push_back({casePair.first, llvm::BasicBlock::Create(IGF.IGM.getLLVMContext())}); else dests.push_back({casePair.first, IGF.getLoweredBB(casePair.second).bb}); } llvm::BasicBlock *defaultDest = nullptr; if (inst->hasDefault()) defaultDest = IGF.getLoweredBB(inst->getDefaultBB()).bb; return defaultDest; } void IRGenSILFunction::visitSwitchEnumInst(SwitchEnumInst *inst) { Explosion value = getLoweredExplosion(inst->getOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest = emitBBMapForSwitchEnum(*this, dests, inst); // Emit the dispatch. auto &EIS = getEnumImplStrategy(IGM, inst->getOperand()->getType()); EIS.emitValueSwitch(*this, value, dests, defaultDest); // Bind arguments for cases that want them. for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); if (!casePair.second->args_empty()) { auto waypointBB = dests[i].second; auto &destLBB = getLoweredBB(casePair.second); Builder.emitBlock(waypointBB); Explosion inValue = getLoweredExplosion(inst->getOperand()); Explosion projected; emitProjectLoadableEnum(*this, inst->getOperand()->getType(), inValue, casePair.first, projected); unsigned phiIndex = 0; addIncomingExplosionToPHINodes(*this, destLBB, phiIndex, projected); Builder.CreateBr(destLBB.bb); } } } void IRGenSILFunction::visitSwitchEnumAddrInst(SwitchEnumAddrInst *inst) { Address value = getLoweredAddress(inst->getOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest = emitBBMapForSwitchEnum(*this, dests, inst); // Emit the dispatch. emitSwitchAddressOnlyEnumDispatch(*this, inst->getOperand()->getType(), value, dests, defaultDest); } // FIXME: We could lower select_enum directly to LLVM select in a lot of cases. // For now, just emit a switch and phi nodes, like a chump. template<class C, class T> static llvm::BasicBlock * emitBBMapForSelect(IRGenSILFunction &IGF, Explosion &resultPHI, SmallVectorImpl<std::pair<T, llvm::BasicBlock*>> &BBs, llvm::BasicBlock *&defaultBB, SelectInstBase<C, T> *inst) { auto origBB = IGF.Builder.GetInsertBlock(); // Set up a continuation BB and phi nodes to receive the result value. llvm::BasicBlock *contBB = IGF.createBasicBlock("select_enum"); IGF.Builder.SetInsertPoint(contBB); // Emit an explosion of phi node(s) to receive the value. SmallVector<llvm::Value*, 4> phis; auto &ti = IGF.getTypeInfo(inst->getType()); emitPHINodesForType(IGF, inst->getType(), ti, inst->getNumCases() + inst->hasDefault(), phis); resultPHI.add(phis); IGF.Builder.SetInsertPoint(origBB); auto addIncoming = [&](SILValue value) { if (value->getType().isAddress()) { addIncomingAddressToPHINodes(IGF, resultPHI.getAll(), IGF.getLoweredAddress(value)); } else { Explosion ex = IGF.getLoweredExplosion(value); addIncomingExplosionToPHINodes(IGF, resultPHI.getAll(), ex); } }; for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); // Create a basic block destination for this case. llvm::BasicBlock *destBB = IGF.createBasicBlock(""); IGF.Builder.emitBlock(destBB); // Feed the corresponding result into the phi nodes. addIncoming(casePair.second); // Jump immediately to the continuation. IGF.Builder.CreateBr(contBB); BBs.push_back(std::make_pair(casePair.first, destBB)); } if (inst->hasDefault()) { defaultBB = IGF.createBasicBlock(""); IGF.Builder.emitBlock(defaultBB); addIncoming(inst->getDefaultResult()); IGF.Builder.CreateBr(contBB); } else { defaultBB = nullptr; } IGF.Builder.emitBlock(contBB); IGF.Builder.SetInsertPoint(origBB); return contBB; } // Try to map the value of a select_enum directly to an int type with a simple // cast from the tag value to the result type. Optionally also by adding a // constant offset. // This is useful, e.g. for rawValue or hashValue of C-like enums. static llvm::Value * mapTriviallyToInt(IRGenSILFunction &IGF, const EnumImplStrategy &EIS, SelectEnumInst *inst) { // All cases must be covered if (inst->hasDefault()) return nullptr; auto &ti = IGF.getTypeInfo(inst->getType()); ExplosionSchema schema = ti.getSchema(); // Check if the select_enum's result is a single integer scalar. if (schema.size() != 1) return nullptr; if (!schema[0].isScalar()) return nullptr; llvm::Type *type = schema[0].getScalarType(); llvm::IntegerType *resultType = dyn_cast<llvm::IntegerType>(type); if (!resultType) return nullptr; // Check if the case values directly map to the tag values, maybe with a // constant offset. APInt commonOffset; bool offsetValid = false; for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); int64_t index = EIS.getDiscriminatorIndex(casePair.first); if (index < 0) return nullptr; IntegerLiteralInst *intLit = dyn_cast<IntegerLiteralInst>(casePair.second); if (!intLit) return nullptr; APInt caseValue = intLit->getValue(); APInt offset = caseValue - index; if (offsetValid) { if (offset != commonOffset) return nullptr; } else { commonOffset = offset; offsetValid = true; } } // Ask the enum implementation strategy to extract the enum tag as an integer // value. Explosion enumValue = IGF.getLoweredExplosion(inst->getEnumOperand()); llvm::Value *result = EIS.emitExtractDiscriminator(IGF, enumValue); if (!result) { (void)enumValue.claimAll(); return nullptr; } // Cast to the result type. result = IGF.Builder.CreateIntCast(result, resultType, false); if (commonOffset != 0) { // The offset, if any. auto *offsetConst = llvm::ConstantInt::get(resultType, commonOffset); result = IGF.Builder.CreateAdd(result, offsetConst); } return result; } template <class C, class T> static LoweredValue getLoweredValueForSelect(IRGenSILFunction &IGF, Explosion &result, SelectInstBase<C, T> *inst) { if (inst->getType().isAddress()) // FIXME: Loses potentially better alignment info we might have. return LoweredValue(Address(result.claimNext(), IGF.getTypeInfo(inst->getType()).getBestKnownAlignment())); return LoweredValue(result); } static void emitSingleEnumMemberSelectResult(IRGenSILFunction &IGF, SelectEnumInstBase *inst, llvm::Value *isTrue, Explosion &result) { assert((inst->getNumCases() == 1 && inst->hasDefault()) || (inst->getNumCases() == 2 && !inst->hasDefault())); // Extract the true values. auto trueValue = inst->getCase(0).second; SmallVector<llvm::Value*, 4> TrueValues; if (trueValue->getType().isAddress()) { TrueValues.push_back(IGF.getLoweredAddress(trueValue).getAddress()); } else { Explosion ex = IGF.getLoweredExplosion(trueValue); while (!ex.empty()) TrueValues.push_back(ex.claimNext()); } // Extract the false values. auto falseValue = inst->hasDefault() ? inst->getDefaultResult() : inst->getCase(1).second; SmallVector<llvm::Value*, 4> FalseValues; if (falseValue->getType().isAddress()) { FalseValues.push_back(IGF.getLoweredAddress(falseValue).getAddress()); } else { Explosion ex = IGF.getLoweredExplosion(falseValue); while (!ex.empty()) FalseValues.push_back(ex.claimNext()); } assert(TrueValues.size() == FalseValues.size() && "explosions didn't produce same element count?"); for (unsigned i = 0, e = FalseValues.size(); i != e; ++i) { auto *TV = TrueValues[i], *FV = FalseValues[i]; // It is pretty common to select between zero and 1 as the result of the // select. Instead of emitting an obviously dumb select, emit nothing or // a zext. if (auto *TC = dyn_cast<llvm::ConstantInt>(TV)) if (auto *FC = dyn_cast<llvm::ConstantInt>(FV)) if (TC->isOne() && FC->isZero()) { result.add(IGF.Builder.CreateZExtOrBitCast(isTrue, TV->getType())); continue; } result.add(IGF.Builder.CreateSelect(isTrue, TV, FalseValues[i])); } } void IRGenSILFunction::visitSelectEnumInst(SelectEnumInst *inst) { auto &EIS = getEnumImplStrategy(IGM, inst->getEnumOperand()->getType()); Explosion result; if (llvm::Value *R = mapTriviallyToInt(*this, EIS, inst)) { result.add(R); } else if ((inst->getNumCases() == 1 && inst->hasDefault()) || (inst->getNumCases() == 2 && !inst->hasDefault())) { // If this is testing for one case, do simpler codegen. This is // particularly common when testing optionals. Explosion value = getLoweredExplosion(inst->getEnumOperand()); auto isTrue = EIS.emitValueCaseTest(*this, value, inst->getCase(0).first); emitSingleEnumMemberSelectResult(*this, inst, isTrue, result); } else { Explosion value = getLoweredExplosion(inst->getEnumOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest; llvm::BasicBlock *contBB = emitBBMapForSelect(*this, result, dests, defaultDest, inst); // Emit the dispatch. EIS.emitValueSwitch(*this, value, dests, defaultDest); // emitBBMapForSelectEnum set up a continuation block and phi nodes to // receive the result. Builder.SetInsertPoint(contBB); } setLoweredValue(inst, getLoweredValueForSelect(*this, result, inst)); } void IRGenSILFunction::visitSelectEnumAddrInst(SelectEnumAddrInst *inst) { Address value = getLoweredAddress(inst->getEnumOperand()); Explosion result; if ((inst->getNumCases() == 1 && inst->hasDefault()) || (inst->getNumCases() == 2 && !inst->hasDefault())) { auto &EIS = getEnumImplStrategy(IGM, inst->getEnumOperand()->getType()); // If this is testing for one case, do simpler codegen. This is // particularly common when testing optionals. auto isTrue = EIS.emitIndirectCaseTest(*this, inst->getEnumOperand()->getType(), value, inst->getCase(0).first); emitSingleEnumMemberSelectResult(*this, inst, isTrue, result); } else { // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest; llvm::BasicBlock *contBB = emitBBMapForSelect(*this, result, dests, defaultDest, inst); // Emit the dispatch. emitSwitchAddressOnlyEnumDispatch(*this, inst->getEnumOperand()->getType(), value, dests, defaultDest); // emitBBMapForSelectEnum set up a phi node to receive the result. Builder.SetInsertPoint(contBB); } setLoweredValue(inst, getLoweredValueForSelect(*this, result, inst)); } void IRGenSILFunction::visitSelectValueInst(SelectValueInst *inst) { Explosion value = getLoweredExplosion(inst->getOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<SILValue, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest; Explosion result; auto *contBB = emitBBMapForSelect(*this, result, dests, defaultDest, inst); // Emit the dispatch. emitSwitchValueDispatch(*this, inst->getOperand()->getType(), value, dests, defaultDest); // emitBBMapForSelectEnum set up a continuation block and phi nodes to // receive the result. Builder.SetInsertPoint(contBB); setLoweredValue(inst, getLoweredValueForSelect(*this, result, inst)); } void IRGenSILFunction::visitDynamicMethodBranchInst(DynamicMethodBranchInst *i){ LoweredBB &hasMethodBB = getLoweredBB(i->getHasMethodBB()); LoweredBB &noMethodBB = getLoweredBB(i->getNoMethodBB()); // Emit the respondsToSelector: call. StringRef selector; llvm::SmallString<64> selectorBuffer; if (auto fnDecl = dyn_cast<FuncDecl>(i->getMember().getDecl())) selector = fnDecl->getObjCSelector().getString(selectorBuffer); else if (auto var = dyn_cast<AbstractStorageDecl>(i->getMember().getDecl())) selector = var->getObjCGetterSelector().getString(selectorBuffer); else llvm_unreachable("Unhandled dynamic method branch query"); llvm::Value *object = getLoweredExplosion(i->getOperand()).claimNext(); if (object->getType() != IGM.ObjCPtrTy) object = Builder.CreateBitCast(object, IGM.ObjCPtrTy); llvm::Value *loadSel = emitObjCSelectorRefLoad(selector); llvm::Value *respondsToSelector = emitObjCSelectorRefLoad("respondsToSelector:"); llvm::Constant *messenger = IGM.getObjCMsgSendFn(); llvm::Type *argTys[] = { IGM.ObjCPtrTy, IGM.Int8PtrTy, IGM.Int8PtrTy, }; auto respondsToSelectorTy = llvm::FunctionType::get(IGM.Int1Ty, argTys, /*isVarArg*/ false) ->getPointerTo(); messenger = llvm::ConstantExpr::getBitCast(messenger, respondsToSelectorTy); llvm::CallInst *call = Builder.CreateCall(messenger, {object, respondsToSelector, loadSel}); call->setDoesNotThrow(); // FIXME: Assume (probably safely) that the hasMethodBB has only us as a // predecessor, and cannibalize its bb argument so we can represent is as an // ObjCMethod lowered value. This is hella gross but saves us having to // implement ObjCMethod-to-Explosion lowering and creating a thunk we don't // want. assert(std::next(i->getHasMethodBB()->pred_begin()) == i->getHasMethodBB()->pred_end() && "lowering dynamic_method_br with multiple preds for destination " "not implemented"); // Kill the existing lowered value for the bb arg and its phi nodes. SILValue methodArg = i->getHasMethodBB()->args_begin()[0]; Explosion formerLLArg = getLoweredExplosion(methodArg); for (llvm::Value *val : formerLLArg.claimAll()) { auto phi = cast<llvm::PHINode>(val); assert(phi->getNumIncomingValues() == 0 && "phi already used"); phi->removeFromParent(); delete phi; } LoweredValues.erase(methodArg); // Replace the lowered value with an ObjCMethod lowering. setLoweredObjCMethod(methodArg, i->getMember()); // Create the branch. Builder.CreateCondBr(call, hasMethodBB.bb, noMethodBB.bb); } void IRGenSILFunction::visitBranchInst(swift::BranchInst *i) { LoweredBB &lbb = getLoweredBB(i->getDestBB()); addIncomingSILArgumentsToPHINodes(*this, lbb, i->getArgs()); Builder.CreateBr(lbb.bb); } void IRGenSILFunction::visitCondBranchInst(swift::CondBranchInst *i) { LoweredBB &trueBB = getLoweredBB(i->getTrueBB()); LoweredBB &falseBB = getLoweredBB(i->getFalseBB()); llvm::Value *condValue = getLoweredExplosion(i->getCondition()).claimNext(); addIncomingSILArgumentsToPHINodes(*this, trueBB, i->getTrueArgs()); addIncomingSILArgumentsToPHINodes(*this, falseBB, i->getFalseArgs()); Builder.CreateCondBr(condValue, trueBB.bb, falseBB.bb); } void IRGenSILFunction::visitRetainValueInst(swift::RetainValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); Explosion out; cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .copy(*this, in, out, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); (void)out.claimAll(); } void IRGenSILFunction::visitCopyValueInst(swift::CopyValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); Explosion out; cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .copy(*this, in, out, getDefaultAtomicity()); setLoweredExplosion(i, out); } // TODO: Implement this more generally for arbitrary values. Currently the // SIL verifier restricts it to single-refcounted-pointer types. void IRGenSILFunction::visitAutoreleaseValueInst(swift::AutoreleaseValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); auto val = in.claimNext(); emitObjCAutoreleaseCall(val); } void IRGenSILFunction::visitSetDeallocatingInst(SetDeallocatingInst *i) { auto *ARI = dyn_cast<AllocRefInst>(i->getOperand()); if (ARI && StackAllocs.count(ARI)) { // A small peep-hole optimization: If the operand is allocated on stack and // there is no "significant" code between the set_deallocating and the final // dealloc_ref, the set_deallocating is not required. // %0 = alloc_ref [stack] // ... // set_deallocating %0 // not needed // // code which does not depend on the RC_DEALLOCATING_FLAG flag. // dealloc_ref %0 // not needed (stems from the inlined deallocator) // ... // dealloc_ref [stack] %0 SILBasicBlock::iterator Iter(i); SILBasicBlock::iterator End = i->getParent()->end(); for (++Iter; Iter != End; ++Iter) { SILInstruction *I = &*Iter; if (auto *DRI = dyn_cast<DeallocRefInst>(I)) { if (DRI->getOperand() == ARI) { // The set_deallocating is followed by a dealloc_ref -> we can ignore // it. return; } } // Assume that any instruction with side-effects may depend on the // RC_DEALLOCATING_FLAG flag. if (I->mayHaveSideEffects()) break; } } Explosion lowered = getLoweredExplosion(i->getOperand()); emitNativeSetDeallocating(lowered.claimNext()); } void IRGenSILFunction::visitReleaseValueInst(swift::ReleaseValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .consume(*this, in, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitDestroyValueInst(swift::DestroyValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .consume(*this, in, getDefaultAtomicity()); } void IRGenSILFunction::visitStructInst(swift::StructInst *i) { Explosion out; for (SILValue elt : i->getElements()) out.add(getLoweredExplosion(elt).claimAll()); setLoweredExplosion(i, out); } void IRGenSILFunction::visitTupleInst(swift::TupleInst *i) { Explosion out; for (SILValue elt : i->getElements()) out.add(getLoweredExplosion(elt).claimAll()); setLoweredExplosion(i, out); } void IRGenSILFunction::visitEnumInst(swift::EnumInst *i) { Explosion data = (i->hasOperand()) ? getLoweredExplosion(i->getOperand()) : Explosion(); Explosion out; emitInjectLoadableEnum(*this, i->getType(), i->getElement(), data, out); setLoweredExplosion(i, out); } void IRGenSILFunction::visitInitEnumDataAddrInst(swift::InitEnumDataAddrInst *i) { Address enumAddr = getLoweredAddress(i->getOperand()); Address dataAddr = emitProjectEnumAddressForStore(*this, i->getOperand()->getType(), enumAddr, i->getElement()); setLoweredAddress(i, dataAddr); } void IRGenSILFunction::visitUncheckedEnumDataInst(swift::UncheckedEnumDataInst *i) { Explosion enumVal = getLoweredExplosion(i->getOperand()); Explosion data; emitProjectLoadableEnum(*this, i->getOperand()->getType(), enumVal, i->getElement(), data); setLoweredExplosion(i, data); } void IRGenSILFunction::visitUncheckedTakeEnumDataAddrInst(swift::UncheckedTakeEnumDataAddrInst *i) { Address enumAddr = getLoweredAddress(i->getOperand()); Address dataAddr = emitDestructiveProjectEnumAddressForLoad(*this, i->getOperand()->getType(), enumAddr, i->getElement()); setLoweredAddress(i, dataAddr); } void IRGenSILFunction::visitInjectEnumAddrInst(swift::InjectEnumAddrInst *i) { Address enumAddr = getLoweredAddress(i->getOperand()); emitStoreEnumTagToAddress(*this, i->getOperand()->getType(), enumAddr, i->getElement()); } void IRGenSILFunction::visitTupleExtractInst(swift::TupleExtractInst *i) { Explosion fullTuple = getLoweredExplosion(i->getOperand()); Explosion output; SILType baseType = i->getOperand()->getType(); projectTupleElementFromExplosion(*this, baseType, fullTuple, i->getFieldNo(), output); (void)fullTuple.claimAll(); setLoweredExplosion(i, output); } void IRGenSILFunction::visitTupleElementAddrInst(swift::TupleElementAddrInst *i) { Address base = getLoweredAddress(i->getOperand()); SILType baseType = i->getOperand()->getType(); Address field = projectTupleElementAddress(*this, base, baseType, i->getFieldNo()); setLoweredAddress(i, field); } void IRGenSILFunction::visitStructExtractInst(swift::StructExtractInst *i) { Explosion operand = getLoweredExplosion(i->getOperand()); Explosion lowered; SILType baseType = i->getOperand()->getType(); projectPhysicalStructMemberFromExplosion(*this, baseType, operand, i->getField(), lowered); (void)operand.claimAll(); setLoweredExplosion(i, lowered); } void IRGenSILFunction::visitStructElementAddrInst( swift::StructElementAddrInst *i) { Address base = getLoweredAddress(i->getOperand()); SILType baseType = i->getOperand()->getType(); Address field = projectPhysicalStructMemberAddress(*this, base, baseType, i->getField()); setLoweredAddress(i, field); } void IRGenSILFunction::visitRefElementAddrInst(swift::RefElementAddrInst *i) { Explosion base = getLoweredExplosion(i->getOperand()); llvm::Value *value = base.claimNext(); SILType baseTy = i->getOperand()->getType(); Address field = projectPhysicalClassMemberAddress(*this, value, baseTy, i->getType(), i->getField()) .getAddress(); setLoweredAddress(i, field); } void IRGenSILFunction::visitRefTailAddrInst(RefTailAddrInst *i) { SILValue Ref = i->getOperand(); llvm::Value *RefValue = getLoweredExplosion(Ref).claimNext(); Address TailAddr = emitTailProjection(*this, RefValue, Ref->getType(), i->getTailType()); setLoweredAddress(i, TailAddr); } static bool isInvariantAddress(SILValue v) { auto root = getUnderlyingAddressRoot(v); if (auto ptrRoot = dyn_cast<PointerToAddressInst>(root)) { return ptrRoot->isInvariant(); } // TODO: We could be more aggressive about considering addresses based on // `let` variables as invariant when the type of the address is known not to // have any sharably-mutable interior storage (in other words, no weak refs, // atomics, etc.) return false; } void IRGenSILFunction::visitLoadInst(swift::LoadInst *i) { Explosion lowered; Address source = getLoweredAddress(i->getOperand()); SILType objType = i->getType().getObjectType(); const auto &typeInfo = cast<LoadableTypeInfo>(getTypeInfo(objType)); switch (i->getOwnershipQualifier()) { case LoadOwnershipQualifier::Unqualified: case LoadOwnershipQualifier::Trivial: case LoadOwnershipQualifier::Take: typeInfo.loadAsTake(*this, source, lowered); break; case LoadOwnershipQualifier::Copy: typeInfo.loadAsCopy(*this, source, lowered); break; } if (isInvariantAddress(i->getOperand())) { // It'd be better to push this down into `loadAs` methods, perhaps... for (auto value : lowered.getAll()) if (auto load = dyn_cast<llvm::LoadInst>(value)) setInvariantLoad(load); } setLoweredExplosion(i, lowered); } void IRGenSILFunction::visitStoreInst(swift::StoreInst *i) { Explosion source = getLoweredExplosion(i->getSrc()); Address dest = getLoweredAddress(i->getDest()); SILType objType = i->getSrc()->getType().getObjectType(); const auto &typeInfo = cast<LoadableTypeInfo>(getTypeInfo(objType)); switch (i->getOwnershipQualifier()) { case StoreOwnershipQualifier::Unqualified: case StoreOwnershipQualifier::Init: case StoreOwnershipQualifier::Trivial: typeInfo.initialize(*this, source, dest); break; case StoreOwnershipQualifier::Assign: typeInfo.assign(*this, source, dest); break; } } /// Emit the artificial error result argument. void IRGenSILFunction::emitErrorResultVar(SILResultInfo ErrorInfo, DebugValueInst *DbgValue) { // We don't need a shadow error variable for debugging on ABI's that return // swifterror in a register. if (IGM.IsSwiftErrorInRegister) return; auto ErrorResultSlot = getErrorResultSlot(IGM.silConv.getSILType(ErrorInfo)); SILDebugVariable Var = DbgValue->getVarInfo(); auto Storage = emitShadowCopy(ErrorResultSlot.getAddress(), getDebugScope(), Var.Name, Var.ArgNo); DebugTypeInfo DTI(nullptr, nullptr, ErrorInfo.getType(), ErrorResultSlot->getType(), IGM.getPointerSize(), IGM.getPointerAlignment()); IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, DTI, getDebugScope(), nullptr, Var.Name, Var.ArgNo, IndirectValue, ArtificialValue); } void IRGenSILFunction::visitDebugValueInst(DebugValueInst *i) { if (!IGM.DebugInfo) return; auto SILVal = i->getOperand(); if (isa<SILUndef>(SILVal)) { // We cannot track the location of inlined error arguments because it has no // representation in SIL. if (!i->getDebugScope()->InlinedCallSite && i->getVarInfo().Name == "$error") { auto funcTy = CurSILFn->getLoweredFunctionType(); emitErrorResultVar(funcTy->getErrorResult(), i); } return; } StringRef Name = getVarName(i); DebugTypeInfo DbgTy; SILType SILTy = SILVal->getType(); auto RealTy = SILVal->getType().getSwiftRValueType(); if (VarDecl *Decl = i->getDecl()) { DbgTy = DebugTypeInfo::getLocalVariable( CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), Decl, RealTy, getTypeInfo(SILVal->getType()), /*Unwrap=*/false); } else if (i->getFunction()->isBare() && !SILTy.hasArchetype() && !Name.empty()) { // Preliminary support for .sil debug information. DbgTy = DebugTypeInfo::getFromTypeInfo(CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), RealTy, getTypeInfo(SILTy)); } else return; // Put the value into a stack slot at -Onone. llvm::SmallVector<llvm::Value *, 8> Copy; Explosion e = getLoweredExplosion(SILVal); unsigned ArgNo = i->getVarInfo().ArgNo; emitShadowCopy(e.claimAll(), i->getDebugScope(), Name, ArgNo, Copy); emitDebugVariableDeclaration(Copy, DbgTy, SILTy, i->getDebugScope(), i->getDecl(), Name, ArgNo); } void IRGenSILFunction::visitDebugValueAddrInst(DebugValueAddrInst *i) { if (!IGM.DebugInfo) return; VarDecl *Decl = i->getDecl(); if (!Decl) return; auto SILVal = i->getOperand(); if (isa<SILUndef>(SILVal)) return; StringRef Name = getVarName(i); auto Addr = getLoweredAddress(SILVal).getAddress(); SILType SILTy = SILVal->getType(); auto RealType = SILTy.getSwiftRValueType(); if (SILTy.isAddress()) RealType = CanInOutType::get(RealType); // Unwrap implicitly indirect types and types that are passed by // reference only at the SIL level and below. // // FIXME: Should this check if the lowered SILType is address only // instead? Otherwise optionals of archetypes etc will still have // 'Unwrap' set to false. bool Unwrap = i->getVarInfo().Constant || SILTy.is<ArchetypeType>(); auto DbgTy = DebugTypeInfo::getLocalVariable( CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), Decl, RealType, getTypeInfo(SILVal->getType()), Unwrap); // Put the value's address into a stack slot at -Onone and emit a debug // intrinsic. unsigned ArgNo = i->getVarInfo().ArgNo; emitDebugVariableDeclaration( emitShadowCopy(Addr, i->getDebugScope(), Name, ArgNo), DbgTy, i->getType(), i->getDebugScope(), Decl, Name, ArgNo, DbgTy.isImplicitlyIndirect() ? DirectValue : IndirectValue); } void IRGenSILFunction::visitLoadWeakInst(swift::LoadWeakInst *i) { Address source = getLoweredAddress(i->getOperand()); auto &weakTI = cast<WeakTypeInfo>(getTypeInfo(i->getOperand()->getType())); Explosion result; if (i->isTake()) { weakTI.weakTakeStrong(*this, source, result); } else { weakTI.weakLoadStrong(*this, source, result); } setLoweredExplosion(i, result); } void IRGenSILFunction::visitStoreWeakInst(swift::StoreWeakInst *i) { Explosion source = getLoweredExplosion(i->getSrc()); Address dest = getLoweredAddress(i->getDest()); auto &weakTI = cast<WeakTypeInfo>(getTypeInfo(i->getDest()->getType())); if (i->isInitializationOfDest()) { weakTI.weakInit(*this, source, dest); } else { weakTI.weakAssign(*this, source, dest); } } void IRGenSILFunction::visitFixLifetimeInst(swift::FixLifetimeInst *i) { if (i->getOperand()->getType().isAddress()) { // Just pass in the address to fix lifetime if we have one. We will not do // anything to it so nothing bad should happen. emitFixLifetime(getLoweredAddress(i->getOperand()).getAddress()); return; } // Handle objects. Explosion in = getLoweredExplosion(i->getOperand()); cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .fixLifetime(*this, in); } void IRGenSILFunction::visitMarkDependenceInst(swift::MarkDependenceInst *i) { // Dependency-marking is purely for SIL. Just forward the input as // the result. SILValue value = i->getValue(); if (value->getType().isAddress()) { setLoweredAddress(i, getLoweredAddress(value)); } else { Explosion temp = getLoweredExplosion(value); setLoweredExplosion(i, temp); } } void IRGenSILFunction::visitCopyBlockInst(CopyBlockInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); llvm::Value *copied = emitBlockCopyCall(lowered.claimNext()); Explosion result; result.add(copied); setLoweredExplosion(i, result); } void IRGenSILFunction::visitStrongPinInst(swift::StrongPinInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); llvm::Value *object = lowered.claimNext(); llvm::Value *pinHandle = emitNativeTryPin(object, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); Explosion result; result.add(pinHandle); setLoweredExplosion(i, result); } void IRGenSILFunction::visitStrongUnpinInst(swift::StrongUnpinInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); llvm::Value *pinHandle = lowered.claimNext(); emitNativeUnpin(pinHandle, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitStrongRetainInst(swift::StrongRetainInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = cast<ReferenceTypeInfo>(getTypeInfo(i->getOperand()->getType())); ti.strongRetain(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitStrongReleaseInst(swift::StrongReleaseInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = cast<ReferenceTypeInfo>(getTypeInfo(i->getOperand()->getType())); ti.strongRelease(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } /// Given a SILType which is a ReferenceStorageType, return the type /// info for the underlying reference type. static const ReferenceTypeInfo &getReferentTypeInfo(IRGenFunction &IGF, SILType silType) { auto type = silType.castTo<ReferenceStorageType>().getReferentType(); return cast<ReferenceTypeInfo>(IGF.getTypeInfoForLowered(type)); } void IRGenSILFunction:: visitStrongRetainUnownedInst(swift::StrongRetainUnownedInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType()); ti.strongRetainUnowned(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitUnownedRetainInst(swift::UnownedRetainInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType()); ti.unownedRetain(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitUnownedReleaseInst(swift::UnownedReleaseInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType()); ti.unownedRelease(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitLoadUnownedInst(swift::LoadUnownedInst *i) { Address source = getLoweredAddress(i->getOperand()); auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType()); Explosion result; if (i->isTake()) { ti.unownedTakeStrong(*this, source, result); } else { ti.unownedLoadStrong(*this, source, result); } setLoweredExplosion(i, result); } void IRGenSILFunction::visitStoreUnownedInst(swift::StoreUnownedInst *i) { Explosion source = getLoweredExplosion(i->getSrc()); Address dest = getLoweredAddress(i->getDest()); auto &ti = getReferentTypeInfo(*this, i->getDest()->getType()); if (i->isInitializationOfDest()) { ti.unownedInit(*this, source, dest); } else { ti.unownedAssign(*this, source, dest); } } static bool hasReferenceSemantics(IRGenSILFunction &IGF, SILType silType) { auto operType = silType.getSwiftRValueType(); auto valueType = operType->getAnyOptionalObjectType(); auto objType = valueType ? valueType : operType; return (objType->mayHaveSuperclass() || objType->isClassExistentialType() || objType->is<BuiltinNativeObjectType>() || objType->is<BuiltinBridgeObjectType>() || objType->is<BuiltinUnknownObjectType>()); } static llvm::Value *emitIsUnique(IRGenSILFunction &IGF, SILValue operand, SourceLoc loc, bool checkPinned) { if (!hasReferenceSemantics(IGF, operand->getType())) { llvm::Function *trapIntrinsic = llvm::Intrinsic::getDeclaration( &IGF.IGM.Module, llvm::Intrinsic::ID::trap); IGF.Builder.CreateCall(trapIntrinsic, {}); return llvm::UndefValue::get(IGF.IGM.Int1Ty); } auto &operTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(operand->getType())); LoadedRef ref = operTI.loadRefcountedPtr(IGF, loc, IGF.getLoweredAddress(operand)); return IGF.emitIsUniqueCall(ref.getValue(), loc, ref.isNonNull(), checkPinned); } void IRGenSILFunction::visitIsUniqueInst(swift::IsUniqueInst *i) { llvm::Value *result = emitIsUnique(*this, i->getOperand(), i->getLoc().getSourceLoc(), false); Explosion out; out.add(result); setLoweredExplosion(i, out); } void IRGenSILFunction:: visitIsUniqueOrPinnedInst(swift::IsUniqueOrPinnedInst *i) { llvm::Value *result = emitIsUnique(*this, i->getOperand(), i->getLoc().getSourceLoc(), true); Explosion out; out.add(result); setLoweredExplosion(i, out); } static bool tryDeferFixedSizeBufferInitialization(IRGenSILFunction &IGF, SILInstruction *allocInst, const TypeInfo &ti, Address fixedSizeBuffer, const llvm::Twine &name) { // There's no point in doing this for fixed-sized types, since we'll allocate // an appropriately-sized buffer for them statically. if (ti.isFixedSize()) return false; // TODO: More interesting dominance analysis could be done here to see // if the alloc_stack is dominated by copy_addrs into it on all paths. // For now, check only that the copy_addr is the first use within the same // block. for (auto ii = std::next(allocInst->getIterator()), ie = std::prev(allocInst->getParent()->end()); ii != ie; ++ii) { auto *inst = &*ii; // Does this instruction use the allocation? If not, continue. auto Ops = inst->getAllOperands(); if (std::none_of(Ops.begin(), Ops.end(), [allocInst](const Operand &Op) { return Op.get() == allocInst; })) continue; // Is this a copy? auto *copy = dyn_cast<swift::CopyAddrInst>(inst); if (!copy) return false; // Destination must be the allocation. if (copy->getDest() != SILValue(allocInst)) return false; // Copy must be an initialization. if (!copy->isInitializationOfDest()) return false; // We can defer to this initialization. Allocate the fixed-size buffer // now, but don't allocate the value inside it. if (!fixedSizeBuffer.getAddress()) { fixedSizeBuffer = IGF.createFixedSizeBufferAlloca(name); IGF.Builder.CreateLifetimeStart(fixedSizeBuffer, getFixedBufferSize(IGF.IGM)); } IGF.setContainerOfUnallocatedAddress(allocInst, fixedSizeBuffer); return true; } return false; } void IRGenSILFunction::emitDebugInfoForAllocStack(AllocStackInst *i, const TypeInfo &type, llvm::Value *addr) { VarDecl *Decl = i->getDecl(); if (IGM.DebugInfo && Decl) { // Ignore compiler-generated patterns but not optional bindings. if (auto *Pattern = Decl->getParentPattern()) if (Pattern->isImplicit() && Pattern->getKind() != PatternKind::OptionalSome) return; SILType SILTy = i->getType(); auto RealType = SILTy.getSwiftRValueType(); auto DbgTy = DebugTypeInfo::getLocalVariable( CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), Decl, RealType, type, false); StringRef Name = getVarName(i); if (auto DS = i->getDebugScope()) emitDebugVariableDeclaration(addr, DbgTy, SILTy, DS, Decl, Name, i->getVarInfo().ArgNo); } } void IRGenSILFunction::visitAllocStackInst(swift::AllocStackInst *i) { const TypeInfo &type = getTypeInfo(i->getElementType()); // Derive name from SIL location. VarDecl *Decl = i->getDecl(); StringRef dbgname; # ifndef NDEBUG // If this is a DEBUG build, use pretty names for the LLVM IR. dbgname = getVarName(i); # endif (void) Decl; bool isEntryBlock = i->getParentBlock() == i->getFunction()->getEntryBlock(); auto addr = type.allocateStack(*this, i->getElementType(), isEntryBlock, dbgname); emitDebugInfoForAllocStack(i, type, addr.getAddress().getAddress()); setLoweredStackAddress(i, addr); } static void buildTailArrays(IRGenSILFunction &IGF, SmallVectorImpl<std::pair<SILType, llvm::Value *>> &TailArrays, AllocRefInstBase *ARI) { auto Types = ARI->getTailAllocatedTypes(); auto Counts = ARI->getTailAllocatedCounts(); for (unsigned Idx = 0, NumTypes = Types.size(); Idx < NumTypes; ++Idx) { Explosion ElemCount = IGF.getLoweredExplosion(Counts[Idx].get()); TailArrays.push_back({Types[Idx], ElemCount.claimNext()}); } } void IRGenSILFunction::visitAllocRefInst(swift::AllocRefInst *i) { int StackAllocSize = -1; if (i->canAllocOnStack()) { estimateStackSize(); // Is there enough space for stack allocation? StackAllocSize = IGM.IRGen.Opts.StackPromotionSizeLimit - EstimatedStackSize; } SmallVector<std::pair<SILType, llvm::Value *>, 4> TailArrays; buildTailArrays(*this, TailArrays, i); llvm::Value *alloced = emitClassAllocation(*this, i->getType(), i->isObjC(), StackAllocSize, TailArrays); if (StackAllocSize >= 0) { // Remember that this alloc_ref allocates the object on the stack. StackAllocs.insert(i); EstimatedStackSize += StackAllocSize; } Explosion e; e.add(alloced); setLoweredExplosion(i, e); } void IRGenSILFunction::visitAllocRefDynamicInst(swift::AllocRefDynamicInst *i) { SmallVector<std::pair<SILType, llvm::Value *>, 4> TailArrays; buildTailArrays(*this, TailArrays, i); Explosion metadata = getLoweredExplosion(i->getMetatypeOperand()); auto metadataValue = metadata.claimNext(); llvm::Value *alloced = emitClassAllocationDynamic(*this, metadataValue, i->getType(), i->isObjC(), TailArrays); Explosion e; e.add(alloced); setLoweredExplosion(i, e); } void IRGenSILFunction::visitDeallocStackInst(swift::DeallocStackInst *i) { auto allocatedType = i->getOperand()->getType(); const TypeInfo &allocatedTI = getTypeInfo(allocatedType); StackAddress stackAddr = getLoweredStackAddress(i->getOperand()); allocatedTI.deallocateStack(*this, stackAddr, allocatedType); } void IRGenSILFunction::visitDeallocRefInst(swift::DeallocRefInst *i) { // Lower the operand. Explosion self = getLoweredExplosion(i->getOperand()); auto selfValue = self.claimNext(); auto *ARI = dyn_cast<AllocRefInst>(i->getOperand()); if (!i->canAllocOnStack()) { if (ARI && StackAllocs.count(ARI)) { // We can ignore dealloc_refs (without [stack]) for stack allocated // objects. // // %0 = alloc_ref [stack] // ... // dealloc_ref %0 // not needed (stems from the inlined deallocator) // ... // dealloc_ref [stack] %0 return; } auto classType = i->getOperand()->getType(); emitClassDeallocation(*this, classType, selfValue); return; } // It's a dealloc_ref [stack]. Even if the alloc_ref did not allocate the // object on the stack, we don't have to deallocate it, because it is // deallocated in the final release. assert(ARI->canAllocOnStack()); if (StackAllocs.count(ARI)) { if (IGM.IRGen.Opts.EmitStackPromotionChecks) { selfValue = Builder.CreateBitCast(selfValue, IGM.RefCountedPtrTy); emitVerifyEndOfLifetimeCall(selfValue); } else { // This has two purposes: // 1. Tell LLVM the lifetime of the allocated stack memory. // 2. Avoid tail-call optimization which may convert the call to the final // release to a jump, which is done after the stack frame is // destructed. Builder.CreateLifetimeEnd(selfValue); } } } void IRGenSILFunction::visitDeallocPartialRefInst(swift::DeallocPartialRefInst *i) { Explosion self = getLoweredExplosion(i->getInstance()); auto selfValue = self.claimNext(); Explosion metadata = getLoweredExplosion(i->getMetatype()); auto metadataValue = metadata.claimNext(); auto classType = i->getInstance()->getType(); emitPartialClassDeallocation(*this, classType, selfValue, metadataValue); } void IRGenSILFunction::visitDeallocBoxInst(swift::DeallocBoxInst *i) { Explosion owner = getLoweredExplosion(i->getOperand()); llvm::Value *ownerPtr = owner.claimNext(); auto boxTy = i->getOperand()->getType().castTo<SILBoxType>(); emitDeallocateBox(*this, ownerPtr, boxTy); } void IRGenSILFunction::visitAllocBoxInst(swift::AllocBoxInst *i) { assert(i->getBoxType()->getLayout()->getFields().size() == 1 && "multi field boxes not implemented yet"); const TypeInfo &type = getTypeInfo(i->getBoxType() ->getFieldType(IGM.getSILModule(), 0)); // Derive name from SIL location. VarDecl *Decl = i->getDecl(); StringRef Name = getVarName(i); StringRef DbgName = # ifndef NDEBUG // If this is a DEBUG build, use pretty names for the LLVM IR. Name; # else ""; # endif auto boxTy = i->getType().castTo<SILBoxType>(); OwnedAddress boxWithAddr = emitAllocateBox(*this, boxTy, CurSILFn->getGenericEnvironment(), DbgName); setLoweredBox(i, boxWithAddr); if (IGM.DebugInfo && Decl) { // FIXME: This is a workaround to not produce local variables for // capture list arguments like "[weak self]". The better solution // would be to require all variables to be described with a // SILDebugValue(Addr) and then not describe capture list // arguments. if (Name == IGM.Context.Id_self.str()) return; assert(i->getBoxType()->getLayout()->getFields().size() == 1 && "box for a local variable should only have one field"); auto SILTy = i->getBoxType()->getFieldType(IGM.getSILModule(), 0); auto RealType = SILTy.getSwiftRValueType(); if (SILTy.isAddress()) RealType = CanInOutType::get(RealType); auto DbgTy = DebugTypeInfo::getLocalVariable( CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), Decl, RealType, type, /*Unwrap=*/false); if (isInlinedGeneric(Decl, i->getDebugScope())) return; IGM.DebugInfo->emitVariableDeclaration( Builder, emitShadowCopy(boxWithAddr.getAddress(), i->getDebugScope(), Name, 0), DbgTy, i->getDebugScope(), Decl, Name, 0, DbgTy.isImplicitlyIndirect() ? DirectValue : IndirectValue); } } void IRGenSILFunction::visitProjectBoxInst(swift::ProjectBoxInst *i) { auto boxTy = i->getOperand()->getType().castTo<SILBoxType>(); const LoweredValue &val = getLoweredValue(i->getOperand()); if (val.isBoxWithAddress()) { // The operand is an alloc_box. We can directly reuse the address. setLoweredAddress(i, val.getAddressOfBox()); } else { // The slow-path: we have to emit code to get from the box to it's // value address. Explosion box = val.getExplosion(*this); auto addr = emitProjectBox(*this, box.claimNext(), boxTy); setLoweredAddress(i, addr); } } static void emitBeginAccess(IRGenSILFunction &IGF, BeginAccessInst *access, Address addr) { switch (access->getEnforcement()) { case SILAccessEnforcement::Unknown: llvm_unreachable("unknown access enforcement in IRGen!"); case SILAccessEnforcement::Static: case SILAccessEnforcement::Unsafe: // nothing to do return; case SILAccessEnforcement::Dynamic: // TODO return; } llvm_unreachable("bad access enforcement"); } static void emitEndAccess(IRGenSILFunction &IGF, BeginAccessInst *access) { switch (access->getEnforcement()) { case SILAccessEnforcement::Unknown: llvm_unreachable("unknown access enforcement in IRGen!"); case SILAccessEnforcement::Static: case SILAccessEnforcement::Unsafe: // nothing to do return; case SILAccessEnforcement::Dynamic: // TODO return; } llvm_unreachable("bad access enforcement"); } void IRGenSILFunction::visitBeginAccessInst(BeginAccessInst *i) { Address addr = getLoweredAddress(i->getOperand()); emitBeginAccess(*this, i, addr); setLoweredAddress(i, addr); } void IRGenSILFunction::visitEndAccessInst(EndAccessInst *i) { emitEndAccess(*this, i->getBeginAccess()); } void IRGenSILFunction::visitConvertFunctionInst(swift::ConvertFunctionInst *i) { // This instruction is specified to be a no-op. Explosion temp = getLoweredExplosion(i->getOperand()); setLoweredExplosion(i, temp); } void IRGenSILFunction::visitThinFunctionToPointerInst( swift::ThinFunctionToPointerInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); llvm::Value *fn = in.claimNext(); fn = Builder.CreateBitCast(fn, IGM.Int8PtrTy); Explosion out; out.add(fn); setLoweredExplosion(i, out); } void IRGenSILFunction::visitPointerToThinFunctionInst( swift::PointerToThinFunctionInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); llvm::Value *fn = in.claimNext(); fn = Builder.CreateBitCast(fn, IGM.FunctionPtrTy); Explosion out; out.add(fn); setLoweredExplosion(i, out); } void IRGenSILFunction::visitAddressToPointerInst(swift::AddressToPointerInst *i) { Explosion to; llvm::Value *addrValue = getLoweredAddress(i->getOperand()).getAddress(); if (addrValue->getType() != IGM.Int8PtrTy) addrValue = Builder.CreateBitCast(addrValue, IGM.Int8PtrTy); to.add(addrValue); setLoweredExplosion(i, to); } // Ignores the isStrict flag because Swift TBAA is not lowered into LLVM IR. void IRGenSILFunction::visitPointerToAddressInst(swift::PointerToAddressInst *i) { Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *ptrValue = from.claimNext(); auto &ti = getTypeInfo(i->getType()); llvm::Type *destType = ti.getStorageType()->getPointerTo(); ptrValue = Builder.CreateBitCast(ptrValue, destType); setLoweredAddress(i, ti.getAddressForPointer(ptrValue)); } static void emitPointerCastInst(IRGenSILFunction &IGF, SILValue src, SILValue dest, const TypeInfo &ti) { Explosion from = IGF.getLoweredExplosion(src); llvm::Value *ptrValue = from.claimNext(); // The input may have witness tables or other additional data, but the class // reference is always first. (void)from.claimAll(); auto schema = ti.getSchema(); assert(schema.size() == 1 && schema[0].isScalar() && "pointer schema is not a single scalar?!"); auto castToType = schema[0].getScalarType(); // A retainable pointer representation may be wrapped in an optional, so we // need to provide inttoptr/ptrtoint in addition to bitcast. ptrValue = IGF.Builder.CreateBitOrPointerCast(ptrValue, castToType); Explosion to; to.add(ptrValue); IGF.setLoweredExplosion(dest, to); } void IRGenSILFunction::visitUncheckedRefCastInst( swift::UncheckedRefCastInst *i) { auto &ti = getTypeInfo(i->getType()); emitPointerCastInst(*this, i->getOperand(), i, ti); } // TODO: Although runtime checks are not required, we get them anyway when // asking the runtime to perform this cast. If this is a performance impact, we // can add a CheckedCastMode::Unchecked. void IRGenSILFunction:: visitUncheckedRefCastAddrInst(swift::UncheckedRefCastAddrInst *i) { Address dest = getLoweredAddress(i->getDest()); Address src = getLoweredAddress(i->getSrc()); emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(), i->getConsumptionKind(), CheckedCastMode::Unconditional); } void IRGenSILFunction::visitUncheckedAddrCastInst( swift::UncheckedAddrCastInst *i) { auto addr = getLoweredAddress(i->getOperand()); auto &ti = getTypeInfo(i->getType()); auto result = Builder.CreateBitCast(addr,ti.getStorageType()->getPointerTo()); setLoweredAddress(i, result); } static bool isStructurallySame(const llvm::Type *T1, const llvm::Type *T2) { if (T1 == T2) return true; if (auto *S1 = dyn_cast<llvm::StructType>(T1)) if (auto *S2 = dyn_cast<llvm::StructType>(T2)) return S1->isLayoutIdentical(const_cast<llvm::StructType*>(S2)); return false; } // Emit a trap in the event a type does not match expected layout constraints. // // We can hit this case in specialized functions even for correct user code. // If the user dynamically checks for correct type sizes in the generic // function, a specialized function can contain the (not executed) bitcast // with mismatching fixed sizes. // Usually llvm can eliminate this code again because the user's safety // check should be constant foldable on llvm level. static void emitTrapAndUndefValue(IRGenSILFunction &IGF, Explosion &in, Explosion &out, const LoadableTypeInfo &outTI) { llvm::BasicBlock *failBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext()); IGF.Builder.CreateBr(failBB); IGF.FailBBs.push_back(failBB); IGF.Builder.emitBlock(failBB); llvm::Function *trapIntrinsic = llvm::Intrinsic::getDeclaration( &IGF.IGM.Module, llvm::Intrinsic::ID::trap); IGF.Builder.CreateCall(trapIntrinsic, {}); IGF.Builder.CreateUnreachable(); llvm::BasicBlock *contBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext()); IGF.Builder.emitBlock(contBB); (void)in.claimAll(); for (auto schema : outTI.getSchema()) out.add(llvm::UndefValue::get(schema.getScalarType())); } static void emitUncheckedValueBitCast(IRGenSILFunction &IGF, SourceLoc loc, Explosion &in, const LoadableTypeInfo &inTI, Explosion &out, const LoadableTypeInfo &outTI) { // If the transfer is doable bitwise, and if the elements of the explosion are // the same type, then just transfer the elements. if (inTI.isBitwiseTakable(ResilienceExpansion::Maximal) && outTI.isBitwiseTakable(ResilienceExpansion::Maximal) && isStructurallySame(inTI.getStorageType(), outTI.getStorageType())) { in.transferInto(out, in.size()); return; } // TODO: We could do bitcasts entirely in the value domain in some cases, but // for simplicity, let's just always go through the stack for now. // Create the allocation. auto inStorage = IGF.createAlloca(inTI.getStorageType(), std::max(inTI.getFixedAlignment(), outTI.getFixedAlignment()), "bitcast"); auto maxSize = std::max(inTI.getFixedSize(), outTI.getFixedSize()); IGF.Builder.CreateLifetimeStart(inStorage, maxSize); // Store the 'in' value. inTI.initialize(IGF, in, inStorage); // Load the 'out' value as the destination type. auto outStorage = IGF.Builder.CreateBitCast(inStorage, outTI.getStorageType()->getPointerTo()); outTI.loadAsTake(IGF, outStorage, out); IGF.Builder.CreateLifetimeEnd(inStorage, maxSize); return; } static void emitValueBitwiseCast(IRGenSILFunction &IGF, SourceLoc loc, Explosion &in, const LoadableTypeInfo &inTI, Explosion &out, const LoadableTypeInfo &outTI) { // Unfortunately, we can't check this invariant until we get to IRGen, since // the AST and SIL don't know anything about type layout. if (inTI.getFixedSize() < outTI.getFixedSize()) { emitTrapAndUndefValue(IGF, in, out, outTI); return; } emitUncheckedValueBitCast(IGF, loc, in, inTI, out, outTI); } void IRGenSILFunction::visitUncheckedTrivialBitCastInst( swift::UncheckedTrivialBitCastInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); Explosion out; emitValueBitwiseCast(*this, i->getLoc().getSourceLoc(), in, cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())), out, cast<LoadableTypeInfo>(getTypeInfo(i->getType()))); setLoweredExplosion(i, out); } void IRGenSILFunction:: visitUncheckedBitwiseCastInst(swift::UncheckedBitwiseCastInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); Explosion out; emitValueBitwiseCast(*this, i->getLoc().getSourceLoc(), in, cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())), out, cast<LoadableTypeInfo>(getTypeInfo(i->getType()))); setLoweredExplosion(i, out); } void IRGenSILFunction::visitRefToRawPointerInst( swift::RefToRawPointerInst *i) { auto &ti = getTypeInfo(i->getType()); emitPointerCastInst(*this, i->getOperand(), i, ti); } void IRGenSILFunction::visitRawPointerToRefInst(swift::RawPointerToRefInst *i) { auto &ti = getTypeInfo(i->getType()); emitPointerCastInst(*this, i->getOperand(), i, ti); } // SIL scalar conversions which never change the IR type. // FIXME: Except for optionals, which get bit-packed into an integer. static void trivialRefConversion(IRGenSILFunction &IGF, SILValue input, SILValue result) { Explosion temp = IGF.getLoweredExplosion(input); auto &inputTI = IGF.getTypeInfo(input->getType()); auto &resultTI = IGF.getTypeInfo(result->getType()); // If the types are the same, forward the existing value. if (inputTI.getStorageType() == resultTI.getStorageType()) { IGF.setLoweredExplosion(result, temp); return; } auto schema = resultTI.getSchema(); Explosion out; for (auto schemaElt : schema) { auto resultTy = schemaElt.getScalarType(); llvm::Value *value = temp.claimNext(); if (value->getType() == resultTy) { // Nothing to do. This happens with the unowned conversions. } else if (resultTy->isPointerTy()) { value = IGF.Builder.CreateIntToPtr(value, resultTy); } else { value = IGF.Builder.CreatePtrToInt(value, resultTy); } out.add(value); } IGF.setLoweredExplosion(result, out); } // SIL scalar conversions which never change the IR type. // FIXME: Except for optionals, which get bit-packed into an integer. #define NOOP_CONVERSION(KIND) \ void IRGenSILFunction::visit##KIND##Inst(swift::KIND##Inst *i) { \ ::trivialRefConversion(*this, i->getOperand(), i); \ } NOOP_CONVERSION(UnownedToRef) NOOP_CONVERSION(RefToUnowned) NOOP_CONVERSION(UnmanagedToRef) NOOP_CONVERSION(RefToUnmanaged) #undef NOOP_CONVERSION void IRGenSILFunction::visitThinToThickFunctionInst( swift::ThinToThickFunctionInst *i) { // Take the incoming function pointer and add a null context pointer to it. Explosion from = getLoweredExplosion(i->getOperand()); Explosion to; to.add(from.claimNext()); to.add(IGM.RefCountedNull); setLoweredExplosion(i, to); } void IRGenSILFunction::visitThickToObjCMetatypeInst(ThickToObjCMetatypeInst *i){ Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *swiftMeta = from.claimNext(); CanType instanceType(i->getType().castTo<AnyMetatypeType>().getInstanceType()); Explosion to; llvm::Value *classPtr = emitClassHeapMetadataRefForMetatype(*this, swiftMeta, instanceType); to.add(Builder.CreateBitCast(classPtr, IGM.ObjCClassPtrTy)); setLoweredExplosion(i, to); } void IRGenSILFunction::visitObjCToThickMetatypeInst( ObjCToThickMetatypeInst *i) { Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *classPtr = from.claimNext(); // Fetch the metadata for that class. Explosion to; auto metadata = emitObjCMetadataRefForMetadata(*this, classPtr); to.add(metadata); setLoweredExplosion(i, to); } void IRGenSILFunction::visitUnconditionalCheckedCastInst( swift::UnconditionalCheckedCastInst *i) { Explosion value = getLoweredExplosion(i->getOperand()); Explosion ex; emitScalarCheckedCast(*this, value, i->getOperand()->getType(), i->getType(), CheckedCastMode::Unconditional, ex); setLoweredExplosion(i, ex); } void IRGenSILFunction::visitObjCMetatypeToObjectInst( ObjCMetatypeToObjectInst *i){ // Bitcast the @objc metatype reference, which is already an ObjC object, to // the destination type. Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *value = from.claimNext(); value = Builder.CreateBitCast(value, IGM.UnknownRefCountedPtrTy); Explosion to; to.add(value); setLoweredExplosion(i, to); } void IRGenSILFunction::visitObjCExistentialMetatypeToObjectInst( ObjCExistentialMetatypeToObjectInst *i){ // Bitcast the @objc metatype reference, which is already an ObjC object, to // the destination type. The metatype may carry additional witness tables we // can drop. Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *value = from.claimNext(); (void)from.claimAll(); value = Builder.CreateBitCast(value, IGM.UnknownRefCountedPtrTy); Explosion to; to.add(value); setLoweredExplosion(i, to); } void IRGenSILFunction::visitObjCProtocolInst(ObjCProtocolInst *i) { // Get the protocol reference. llvm::Value *protoRef = emitReferenceToObjCProtocol(*this, i->getProtocol()); // Bitcast it to the class reference type. protoRef = Builder.CreateBitCast(protoRef, getTypeInfo(i->getType()).getStorageType()); Explosion ex; ex.add(protoRef); setLoweredExplosion(i, ex); } void IRGenSILFunction::visitRefToBridgeObjectInst( swift::RefToBridgeObjectInst *i) { Explosion refEx = getLoweredExplosion(i->getConverted()); llvm::Value *ref = refEx.claimNext(); Explosion bitsEx = getLoweredExplosion(i->getBitsOperand()); llvm::Value *bits = bitsEx.claimNext(); // Mask the bits into the pointer representation. llvm::Value *val = Builder.CreatePtrToInt(ref, IGM.SizeTy); val = Builder.CreateOr(val, bits); val = Builder.CreateIntToPtr(val, IGM.BridgeObjectPtrTy); Explosion resultEx; resultEx.add(val); setLoweredExplosion(i, resultEx); } void IRGenSILFunction::visitBridgeObjectToRefInst( swift::BridgeObjectToRefInst *i) { Explosion boEx = getLoweredExplosion(i->getConverted()); llvm::Value *bo = boEx.claimNext(); Explosion resultEx; auto &refTI = getTypeInfo(i->getType()); llvm::Type *refType = refTI.getSchema()[0].getScalarType(); // If the value is an ObjC tagged pointer, pass it through verbatim. llvm::BasicBlock *taggedCont = nullptr, *tagged = nullptr, *notTagged = nullptr; llvm::Value *taggedRef = nullptr; llvm::Value *boBits = nullptr; ClassDecl *Cl = i->getType().getClassOrBoundGenericClass(); if (IGM.TargetInfo.hasObjCTaggedPointers() && (!Cl || !isKnownNotTaggedPointer(IGM, Cl))) { boBits = Builder.CreatePtrToInt(bo, IGM.SizeTy); APInt maskValue = IGM.TargetInfo.ObjCPointerReservedBits.asAPInt(); llvm::Value *mask = llvm::ConstantInt::get(IGM.getLLVMContext(), maskValue); llvm::Value *reserved = Builder.CreateAnd(boBits, mask); llvm::Value *cond = Builder.CreateICmpEQ(reserved, llvm::ConstantInt::get(IGM.SizeTy, 0)); tagged = createBasicBlock("tagged-pointer"), notTagged = createBasicBlock("not-tagged-pointer"); taggedCont = createBasicBlock("tagged-cont"); Builder.CreateCondBr(cond, notTagged, tagged); Builder.emitBlock(tagged); taggedRef = Builder.CreateBitCast(bo, refType); Builder.CreateBr(taggedCont); // If it's not a tagged pointer, mask off the spare bits. Builder.emitBlock(notTagged); } // Mask off the spare bits (if they exist). auto &spareBits = IGM.getHeapObjectSpareBits(); llvm::Value *result; if (spareBits.any()) { APInt maskValue = ~spareBits.asAPInt(); if (!boBits) boBits = Builder.CreatePtrToInt(bo, IGM.SizeTy); llvm::Value *mask = llvm::ConstantInt::get(IGM.getLLVMContext(), maskValue); llvm::Value *masked = Builder.CreateAnd(boBits, mask); result = Builder.CreateIntToPtr(masked, refType); } else { result = Builder.CreateBitCast(bo, refType); } if (taggedCont) { Builder.CreateBr(taggedCont); Builder.emitBlock(taggedCont); auto phi = Builder.CreatePHI(refType, 2); phi->addIncoming(taggedRef, tagged); phi->addIncoming(result, notTagged); result = phi; } resultEx.add(result); setLoweredExplosion(i, resultEx); } void IRGenSILFunction::visitBridgeObjectToWordInst( swift::BridgeObjectToWordInst *i) { Explosion boEx = getLoweredExplosion(i->getConverted()); llvm::Value *val = boEx.claimNext(); val = Builder.CreatePtrToInt(val, IGM.SizeTy); Explosion wordEx; wordEx.add(val); setLoweredExplosion(i, wordEx); } void IRGenSILFunction::visitUnconditionalCheckedCastAddrInst( swift::UnconditionalCheckedCastAddrInst *i) { Address dest = getLoweredAddress(i->getDest()); Address src = getLoweredAddress(i->getSrc()); emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(), i->getConsumptionKind(), CheckedCastMode::Unconditional); } void IRGenSILFunction::visitUnconditionalCheckedCastValueInst( swift::UnconditionalCheckedCastValueInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitCheckedCastValueBranchInst( swift::CheckedCastValueBranchInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitCheckedCastBranchInst( swift::CheckedCastBranchInst *i) { SILType destTy = i->getCastType(); FailableCastResult castResult; Explosion ex; if (i->isExact()) { auto operand = i->getOperand(); Explosion source = getLoweredExplosion(operand); castResult = emitClassIdenticalCast(*this, source.claimNext(), operand->getType(), destTy); } else { Explosion value = getLoweredExplosion(i->getOperand()); emitScalarCheckedCast(*this, value, i->getOperand()->getType(), i->getCastType(), CheckedCastMode::Conditional, ex); auto val = ex.claimNext(); castResult.casted = val; llvm::Value *nil = llvm::ConstantPointerNull::get(cast<llvm::PointerType>(val->getType())); castResult.succeeded = Builder.CreateICmpNE(val, nil); } // Branch on the success of the cast. // All cast operations currently return null on failure. auto &successBB = getLoweredBB(i->getSuccessBB()); llvm::Type *toTy = IGM.getTypeInfo(destTy).getStorageType(); if (toTy->isPointerTy()) castResult.casted = Builder.CreateBitCast(castResult.casted, toTy); Builder.CreateCondBr(castResult.succeeded, successBB.bb, getLoweredBB(i->getFailureBB()).bb); // Feed the cast result into the nonnull branch. unsigned phiIndex = 0; Explosion ex2; ex2.add(castResult.casted); ex2.add(ex.claimAll()); addIncomingExplosionToPHINodes(*this, successBB, phiIndex, ex2); } void IRGenSILFunction::visitCheckedCastAddrBranchInst( swift::CheckedCastAddrBranchInst *i) { Address dest = getLoweredAddress(i->getDest()); Address src = getLoweredAddress(i->getSrc()); llvm::Value *castSucceeded = emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(), i->getConsumptionKind(), CheckedCastMode::Conditional); Builder.CreateCondBr(castSucceeded, getLoweredBB(i->getSuccessBB()).bb, getLoweredBB(i->getFailureBB()).bb); } void IRGenSILFunction::visitIsNonnullInst(swift::IsNonnullInst *i) { // Get the value we're testing, which may be a function, an address or an // instance pointer. llvm::Value *val; const LoweredValue &lv = getLoweredValue(i->getOperand()); if (i->getOperand()->getType().is<SILFunctionType>()) { Explosion values = lv.getExplosion(*this); val = values.claimNext(); // Function pointer. values.claimNext(); // Ignore the data pointer. } else if (lv.isAddress()) { val = lv.getAddress().getAddress(); } else { Explosion values = lv.getExplosion(*this); val = values.claimNext(); } // Check that the result isn't null. auto *valTy = cast<llvm::PointerType>(val->getType()); llvm::Value *result = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, val, llvm::ConstantPointerNull::get(valTy)); Explosion out; out.add(result); setLoweredExplosion(i, out); } void IRGenSILFunction::visitUpcastInst(swift::UpcastInst *i) { auto toTy = getTypeInfo(i->getType()).getSchema()[0].getScalarType(); // If we have an address, just bitcast, don't explode. if (i->getOperand()->getType().isAddress()) { Address fromAddr = getLoweredAddress(i->getOperand()); llvm::Value *toValue = Builder.CreateBitCast( fromAddr.getAddress(), toTy->getPointerTo()); Address Addr(toValue, fromAddr.getAlignment()); setLoweredAddress(i, Addr); return; } Explosion from = getLoweredExplosion(i->getOperand()); Explosion to; assert(from.size() == 1 && "class should explode to single value"); llvm::Value *fromValue = from.claimNext(); to.add(Builder.CreateBitCast(fromValue, toTy)); setLoweredExplosion(i, to); } void IRGenSILFunction::visitIndexAddrInst(swift::IndexAddrInst *i) { Address base = getLoweredAddress(i->getBase()); Explosion indexValues = getLoweredExplosion(i->getIndex()); llvm::Value *index = indexValues.claimNext(); auto baseTy = i->getBase()->getType(); auto &ti = getTypeInfo(baseTy); Address dest = ti.indexArray(*this, base, index, baseTy); setLoweredAddress(i, dest); } void IRGenSILFunction::visitTailAddrInst(swift::TailAddrInst *i) { Address base = getLoweredAddress(i->getBase()); Explosion indexValues = getLoweredExplosion(i->getIndex()); llvm::Value *index = indexValues.claimNext(); SILType baseTy = i->getBase()->getType(); const TypeInfo &baseTI = getTypeInfo(baseTy); Address dest = baseTI.indexArray(*this, base, index, baseTy); const TypeInfo &TailTI = getTypeInfo(i->getTailType()); dest = TailTI.roundUpToTypeAlignment(*this, dest, i->getTailType()); llvm::Type *destType = TailTI.getStorageType()->getPointerTo(); dest = Builder.CreateBitCast(dest, destType); setLoweredAddress(i, dest); } void IRGenSILFunction::visitIndexRawPointerInst(swift::IndexRawPointerInst *i) { Explosion baseValues = getLoweredExplosion(i->getBase()); llvm::Value *base = baseValues.claimNext(); Explosion indexValues = getLoweredExplosion(i->getIndex()); llvm::Value *index = indexValues.claimNext(); // We don't expose a non-inbounds GEP operation. llvm::Value *destValue = Builder.CreateInBoundsGEP(base, index); Explosion result; result.add(destValue); setLoweredExplosion(i, result); } void IRGenSILFunction::visitAllocValueBufferInst( swift::AllocValueBufferInst *i) { Address buffer = getLoweredAddress(i->getOperand()); auto valueType = i->getValueType(); Address value; if (getSILModule().getOptions().UseCOWExistentials) { value = emitAllocateValueInBuffer(*this, valueType, buffer); } else { value = getTypeInfo(valueType).allocateBuffer(*this, buffer, valueType); } setLoweredAddress(i, value); } void IRGenSILFunction::visitProjectValueBufferInst( swift::ProjectValueBufferInst *i) { Address buffer = getLoweredAddress(i->getOperand()); auto valueType = i->getValueType(); Address value; if (getSILModule().getOptions().UseCOWExistentials) { value = emitProjectValueInBuffer(*this, valueType, buffer); } else { value = getTypeInfo(valueType).projectBuffer(*this, buffer, valueType); } setLoweredAddress(i, value); } void IRGenSILFunction::visitDeallocValueBufferInst( swift::DeallocValueBufferInst *i) { Address buffer = getLoweredAddress(i->getOperand()); auto valueType = i->getValueType(); if (getSILModule().getOptions().UseCOWExistentials) { emitDeallocateValueInBuffer(*this, valueType, buffer); return; } getTypeInfo(valueType).deallocateBuffer(*this, buffer, valueType); } void IRGenSILFunction::visitInitExistentialAddrInst(swift::InitExistentialAddrInst *i) { Address container = getLoweredAddress(i->getOperand()); SILType destType = i->getOperand()->getType(); Address buffer = emitOpaqueExistentialContainerInit(*this, container, destType, i->getFormalConcreteType(), i->getLoweredConcreteType(), i->getConformances()); auto srcType = i->getLoweredConcreteType(); auto &srcTI = getTypeInfo(srcType); // Allocate a COW box for the value if necessary. if (getSILModule().getOptions().UseCOWExistentials) { auto *genericEnv = CurSILFn->getGenericEnvironment(); setLoweredAddress(i, emitAllocateBoxedOpaqueExistentialBuffer( *this, destType, srcType, container, genericEnv)); return; } // See if we can defer initialization of the buffer to a copy_addr into it. if (tryDeferFixedSizeBufferInitialization(*this, i, srcTI, buffer, "")) return; // Allocate in the destination fixed-size buffer. Address address = srcTI.allocateBuffer(*this, buffer, srcType); setLoweredAddress(i, address); } void IRGenSILFunction::visitInitExistentialOpaqueInst( swift::InitExistentialOpaqueInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitInitExistentialMetatypeInst( InitExistentialMetatypeInst *i) { Explosion metatype = getLoweredExplosion(i->getOperand()); Explosion result; emitExistentialMetatypeContainer(*this, result, i->getType(), metatype.claimNext(), i->getOperand()->getType(), i->getConformances()); setLoweredExplosion(i, result); } void IRGenSILFunction::visitInitExistentialRefInst(InitExistentialRefInst *i) { Explosion instance = getLoweredExplosion(i->getOperand()); Explosion result; emitClassExistentialContainer(*this, result, i->getType(), instance.claimNext(), i->getFormalConcreteType(), i->getOperand()->getType(), i->getConformances()); setLoweredExplosion(i, result); } void IRGenSILFunction::visitDeinitExistentialAddrInst( swift::DeinitExistentialAddrInst *i) { Address container = getLoweredAddress(i->getOperand()); // Deallocate the COW box for the value if necessary. if (getSILModule().getOptions().UseCOWExistentials) { emitDeallocateBoxedOpaqueExistentialBuffer( *this, i->getOperand()->getType(), container); return; } emitOpaqueExistentialContainerDeinit(*this, container, i->getOperand()->getType()); } void IRGenSILFunction::visitDeinitExistentialOpaqueInst( swift::DeinitExistentialOpaqueInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitOpenExistentialAddrInst(OpenExistentialAddrInst *i) { SILType baseTy = i->getOperand()->getType(); Address base = getLoweredAddress(i->getOperand()); auto openedArchetype = cast<ArchetypeType>( i->getType().getSwiftRValueType()); // Insert a copy of the boxed value for COW semantics if necessary. if (getSILModule().getOptions().UseCOWExistentials) { auto accessKind = i->getAccessKind(); Address object = emitOpaqueBoxedExistentialProjection( *this, accessKind, base, baseTy, openedArchetype); setLoweredAddress(i, object); return; } Address object = emitOpaqueExistentialProjection(*this, base, baseTy, openedArchetype); setLoweredAddress(i, object); } void IRGenSILFunction::visitOpenExistentialRefInst(OpenExistentialRefInst *i) { SILType baseTy = i->getOperand()->getType(); Explosion base = getLoweredExplosion(i->getOperand()); auto openedArchetype = cast<ArchetypeType>( i->getType().getSwiftRValueType()); Explosion result; llvm::Value *instance = emitClassExistentialProjection(*this, base, baseTy, openedArchetype); result.add(instance); setLoweredExplosion(i, result); } void IRGenSILFunction::visitOpenExistentialMetatypeInst( OpenExistentialMetatypeInst *i) { SILType baseTy = i->getOperand()->getType(); Explosion base = getLoweredExplosion(i->getOperand()); auto openedTy = i->getType().getSwiftRValueType(); llvm::Value *metatype = emitExistentialMetatypeProjection(*this, base, baseTy, openedTy); Explosion result; result.add(metatype); setLoweredExplosion(i, result); } void IRGenSILFunction::visitOpenExistentialOpaqueInst( OpenExistentialOpaqueInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitProjectBlockStorageInst(ProjectBlockStorageInst *i){ // TODO Address block = getLoweredAddress(i->getOperand()); Address capture = projectBlockStorageCapture(*this, block, i->getOperand()->getType().castTo<SILBlockStorageType>()); setLoweredAddress(i, capture); } void IRGenSILFunction::visitInitBlockStorageHeaderInst( InitBlockStorageHeaderInst *i) { auto addr = getLoweredAddress(i->getBlockStorage()); // We currently only support static invoke functions. auto &invokeVal = getLoweredValue(i->getInvokeFunction()); llvm::Function *invokeFn = nullptr; ForeignFunctionInfo foreignInfo; if (invokeVal.kind != LoweredValue::Kind::StaticFunction) { IGM.unimplemented(i->getLoc().getSourceLoc(), "non-static block invoke function"); } else { invokeFn = invokeVal.getStaticFunction().getFunction(); foreignInfo = invokeVal.getStaticFunction().getForeignInfo(); } assert(foreignInfo.ClangInfo && "no clang info for block function?"); // Initialize the header. emitBlockHeader(*this, addr, i->getBlockStorage()->getType().castTo<SILBlockStorageType>(), invokeFn, i->getInvokeFunction()->getType().castTo<SILFunctionType>(), foreignInfo); // Cast the storage to the block type to produce the result value. llvm::Value *asBlock = Builder.CreateBitCast(addr.getAddress(), IGM.ObjCBlockPtrTy); Explosion e; e.add(asBlock); setLoweredExplosion(i, e); } void IRGenSILFunction::visitAllocExistentialBoxInst(AllocExistentialBoxInst *i){ OwnedAddress boxWithAddr = emitBoxedExistentialContainerAllocation(*this, i->getExistentialType(), i->getFormalConcreteType(), i->getConformances()); setLoweredBox(i, boxWithAddr); } void IRGenSILFunction::visitDeallocExistentialBoxInst( DeallocExistentialBoxInst *i) { Explosion box = getLoweredExplosion(i->getOperand()); emitBoxedExistentialContainerDeallocation(*this, box, i->getOperand()->getType(), i->getConcreteType()); } void IRGenSILFunction::visitOpenExistentialBoxInst(OpenExistentialBoxInst *i) { Explosion box = getLoweredExplosion(i->getOperand()); auto openedArchetype = cast<ArchetypeType>(i->getType().getSwiftRValueType()); auto addr = emitOpenExistentialBox(*this, box, i->getOperand()->getType(), openedArchetype); setLoweredAddress(i, addr); } void IRGenSILFunction::visitProjectExistentialBoxInst(ProjectExistentialBoxInst *i) { const LoweredValue &val = getLoweredValue(i->getOperand()); if (val.isBoxWithAddress()) { // The operand is an alloc_existential_box. // We can directly reuse the address. setLoweredAddress(i, val.getAddressOfBox()); } else { Explosion box = getLoweredExplosion(i->getOperand()); auto caddr = emitBoxedExistentialProjection(*this, box, i->getOperand()->getType(), i->getType().getSwiftRValueType()); setLoweredAddress(i, caddr.getAddress()); } } void IRGenSILFunction::visitDynamicMethodInst(DynamicMethodInst *i) { assert(i->getMember().isForeign && "dynamic_method requires [objc] method"); setLoweredObjCMethod(i, i->getMember()); return; } void IRGenSILFunction::visitWitnessMethodInst(swift::WitnessMethodInst *i) { // For Objective-C classes we need to arrange for a msgSend // to happen when the method is called. if (i->getMember().isForeign) { setLoweredObjCMethod(i, i->getMember()); return; } CanType baseTy = i->getLookupType(); ProtocolConformanceRef conformance = i->getConformance(); SILDeclRef member = i->getMember(); // It would be nice if this weren't discarded. llvm::Value *baseMetadataCache = nullptr; Explosion lowered; emitWitnessMethodValue(*this, baseTy, &baseMetadataCache, member, conformance, lowered); setLoweredExplosion(i, lowered); } void IRGenSILFunction::setAllocatedAddressForBuffer(SILValue v, const Address &allocedAddress) { overwriteAllocatedAddress(v, allocedAddress); // Emit the debug info for the variable if any. if (auto allocStack = dyn_cast<AllocStackInst>(v)) { emitDebugInfoForAllocStack(allocStack, getTypeInfo(v->getType()), allocedAddress.getAddress()); } } void IRGenSILFunction::visitCopyAddrInst(swift::CopyAddrInst *i) { SILType addrTy = i->getSrc()->getType(); const TypeInfo &addrTI = getTypeInfo(addrTy); Address src = getLoweredAddress(i->getSrc()); // See whether we have a deferred fixed-size buffer initialization. auto &loweredDest = getLoweredValue(i->getDest()); if (loweredDest.isUnallocatedAddressInBuffer()) { // We should never have a deferred initialization with COW existentials. assert(!getSILModule().getOptions().UseCOWExistentials && "Should never have an unallocated buffer and COW existentials"); assert(i->isInitializationOfDest() && "need to initialize an unallocated buffer"); Address cont = loweredDest.getContainerOfAddress(); if (i->isTakeOfSrc()) { Address addr = addrTI.initializeBufferWithTake(*this, cont, src, addrTy); setAllocatedAddressForBuffer(i->getDest(), addr); } else { Address addr = addrTI.initializeBufferWithCopy(*this, cont, src, addrTy); setAllocatedAddressForBuffer(i->getDest(), addr); } } else { Address dest = loweredDest.getAddress(); if (i->isInitializationOfDest()) { if (i->isTakeOfSrc()) { addrTI.initializeWithTake(*this, dest, src, addrTy); } else { addrTI.initializeWithCopy(*this, dest, src, addrTy); } } else { if (i->isTakeOfSrc()) { addrTI.assignWithTake(*this, dest, src, addrTy); } else { addrTI.assignWithCopy(*this, dest, src, addrTy); } } } } // This is a no-op because we do not lower Swift TBAA info to LLVM IR, and it // does not produce any values. void IRGenSILFunction::visitBindMemoryInst(swift::BindMemoryInst *) {} void IRGenSILFunction::visitDestroyAddrInst(swift::DestroyAddrInst *i) { SILType addrTy = i->getOperand()->getType(); const TypeInfo &addrTI = getTypeInfo(addrTy); // Otherwise, do the normal thing. Address base = getLoweredAddress(i->getOperand()); addrTI.destroy(*this, base, addrTy); } void IRGenSILFunction::visitCondFailInst(swift::CondFailInst *i) { Explosion e = getLoweredExplosion(i->getOperand()); llvm::Value *cond = e.claimNext(); // Emit individual fail blocks so that we can map the failure back to a source // line. llvm::BasicBlock *failBB = llvm::BasicBlock::Create(IGM.getLLVMContext()); llvm::BasicBlock *contBB = llvm::BasicBlock::Create(IGM.getLLVMContext()); Builder.CreateCondBr(cond, failBB, contBB); Builder.emitBlock(failBB); if (IGM.IRGen.Opts.Optimize) { // Emit unique side-effecting inline asm calls in order to eliminate // the possibility that an LLVM optimization or code generation pass // will merge these blocks back together again. We emit an empty asm // string with the side-effect flag set, and with a unique integer // argument for each cond_fail we see in the function. llvm::IntegerType *asmArgTy = IGM.Int32Ty; llvm::Type *argTys = { asmArgTy }; llvm::FunctionType *asmFnTy = llvm::FunctionType::get(IGM.VoidTy, argTys, false /* = isVarArg */); llvm::InlineAsm *inlineAsm = llvm::InlineAsm::get(asmFnTy, "", "n", true /* = SideEffects */); Builder.CreateCall(inlineAsm, llvm::ConstantInt::get(asmArgTy, NumCondFails++)); } // Emit the trap instruction. llvm::Function *trapIntrinsic = llvm::Intrinsic::getDeclaration(&IGM.Module, llvm::Intrinsic::ID::trap); Builder.CreateCall(trapIntrinsic, {}); Builder.CreateUnreachable(); Builder.emitBlock(contBB); FailBBs.push_back(failBB); } void IRGenSILFunction::visitSuperMethodInst(swift::SuperMethodInst *i) { if (i->getMember().isForeign) { setLoweredObjCMethodBounded(i, i->getMember(), i->getOperand()->getType(), /*startAtSuper=*/true); return; } auto base = getLoweredExplosion(i->getOperand()); auto baseType = i->getOperand()->getType(); llvm::Value *baseValue = base.claimNext(); auto method = i->getMember(); auto methodType = i->getType().castTo<SILFunctionType>(); llvm::Value *fnValue = emitVirtualMethodValue(*this, baseValue, baseType, method, methodType, /*useSuperVTable*/ true); fnValue = Builder.CreateBitCast(fnValue, IGM.Int8PtrTy); Explosion e; e.add(fnValue); setLoweredExplosion(i, e); } void IRGenSILFunction::visitClassMethodInst(swift::ClassMethodInst *i) { // For Objective-C classes we need to arrange for a msgSend // to happen when the method is called. if (i->getMember().isForeign) { setLoweredObjCMethod(i, i->getMember()); return; } Explosion base = getLoweredExplosion(i->getOperand()); llvm::Value *baseValue = base.claimNext(); SILDeclRef method = i->getMember(); auto methodType = i->getType().castTo<SILFunctionType>(); // For Swift classes, get the method implementation from the vtable. // FIXME: better explosion kind, map as static. llvm::Value *fnValue = emitVirtualMethodValue(*this, baseValue, i->getOperand()->getType(), method, methodType, /*useSuperVTable*/ false); fnValue = Builder.CreateBitCast(fnValue, IGM.Int8PtrTy); Explosion e; e.add(fnValue); setLoweredExplosion(i, e); } void IRGenModule::emitSILStaticInitializers() { SmallVector<SILFunction *, 8> StaticInitializers; for (SILGlobalVariable &Global : getSILModule().getSILGlobals()) { if (!Global.getInitializer()) continue; auto *IRGlobal = Module.getGlobalVariable(Global.getName(), true /* = AllowLocal */); // A check for multi-threaded compilation: Is this the llvm module where the // global is defined and not only referenced (or not referenced at all). if (!IRGlobal || !IRGlobal->hasInitializer()) continue; auto *InitValue = Global.getValueOfStaticInitializer(); // Set the IR global's initializer to the constant for this SIL // struct. if (auto *SI = dyn_cast<StructInst>(InitValue)) { IRGlobal->setInitializer(emitConstantStruct(*this, SI)); continue; } // Set the IR global's initializer to the constant for this SIL // tuple. auto *TI = cast<TupleInst>(InitValue); IRGlobal->setInitializer(emitConstantTuple(*this, TI)); } }
codestergit/swift
lib/IRGen/IRGenSIL.cpp
C++
apache-2.0
187,807
/* * Copyright 2022 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config; import com.thoughtworks.go.config.validation.FilePathTypeValidator; import com.thoughtworks.go.domain.ArtifactType; import com.thoughtworks.go.plugin.access.artifact.ArtifactMetadataStore; import com.thoughtworks.go.plugin.api.info.PluginDescriptor; import com.thoughtworks.go.plugin.domain.artifact.ArtifactPluginInfo; import com.thoughtworks.go.plugin.domain.common.Metadata; import com.thoughtworks.go.plugin.domain.common.PluggableInstanceSettings; import com.thoughtworks.go.plugin.domain.common.PluginConfiguration; import com.thoughtworks.go.security.CryptoException; import com.thoughtworks.go.security.GoCipher; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.thoughtworks.go.config.BuildArtifactConfig.DEST; import static com.thoughtworks.go.config.BuildArtifactConfig.SRC; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ArtifactTypeConfigsTest { @Test public void shouldAddDuplicatedArtifactSoThatValidationKicksIn() throws Exception { final ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(); assertThat(artifactTypeConfigs.size(), is(0)); artifactTypeConfigs.add(new BuildArtifactConfig("src", "dest")); artifactTypeConfigs.add(new BuildArtifactConfig("src", "dest")); assertThat(artifactTypeConfigs.size(), is(2)); } @Test public void shouldLoadArtifactPlans() { HashMap<String, String> artifactPlan1 = new HashMap<>(); artifactPlan1.put(SRC, "blah"); artifactPlan1.put(DEST, "something"); artifactPlan1.put("artifactTypeValue", TestArtifactConfig.TEST_PLAN_DISPLAY_NAME); HashMap<String, String> artifactPlan2 = new HashMap<>(); artifactPlan2.put(SRC, "blah2"); artifactPlan2.put(DEST, "something2"); artifactPlan2.put("artifactTypeValue", BuildArtifactConfig.ARTIFACT_PLAN_DISPLAY_NAME); List<HashMap> artifactPlansList = new ArrayList<>(); artifactPlansList.add(artifactPlan1); artifactPlansList.add(artifactPlan2); ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(); artifactTypeConfigs.setConfigAttributes(artifactPlansList); assertThat(artifactTypeConfigs.size(), is(2)); TestArtifactConfig plan = new TestArtifactConfig(); plan.setSource("blah"); plan.setDestination("something"); assertThat(artifactTypeConfigs.get(0), is(plan)); assertThat(artifactTypeConfigs.get(1), is(new BuildArtifactConfig("blah2", "something2"))); } @Test public void setConfigAttributes_shouldIgnoreEmptySourceAndDest() { HashMap<String, String> artifactPlan1 = new HashMap<>(); artifactPlan1.put(SRC, "blah"); artifactPlan1.put(DEST, "something"); artifactPlan1.put("artifactTypeValue", TestArtifactConfig.TEST_PLAN_DISPLAY_NAME); HashMap<String, String> artifactPlan2 = new HashMap<>(); artifactPlan2.put(SRC, "blah2"); artifactPlan2.put(DEST, "something2"); artifactPlan2.put("artifactTypeValue", BuildArtifactConfig.ARTIFACT_PLAN_DISPLAY_NAME); HashMap<String, String> artifactPlan3 = new HashMap<>(); artifactPlan3.put(SRC, ""); artifactPlan3.put(DEST, ""); artifactPlan3.put("artifactTypeValue", BuildArtifactConfig.ARTIFACT_PLAN_DISPLAY_NAME); List<HashMap> artifactPlansList = new ArrayList<>(); artifactPlansList.add(artifactPlan1); artifactPlansList.add(artifactPlan3); artifactPlansList.add(artifactPlan2); ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(); artifactTypeConfigs.setConfigAttributes(artifactPlansList); assertThat(artifactTypeConfigs.size(), is(2)); TestArtifactConfig plan = new TestArtifactConfig(); plan.setSource("blah"); plan.setDestination("something"); assertThat(artifactTypeConfigs.get(0), is(plan)); assertThat(artifactTypeConfigs.get(1), is(new BuildArtifactConfig("blah2", "something2"))); } @Test public void setConfigAttributes_shouldSetExternalArtifactWithPlainTextValuesIfPluginIdIsProvided() { ArtifactPluginInfo artifactPluginInfo = mock(ArtifactPluginInfo.class); PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); when(artifactPluginInfo.getDescriptor()).thenReturn(pluginDescriptor); when(pluginDescriptor.id()).thenReturn("cd.go.artifact.foo"); PluginConfiguration image = new PluginConfiguration("Image", new Metadata(true, true)); PluginConfiguration tag = new PluginConfiguration("Tag", new Metadata(true, false)); ArrayList<PluginConfiguration> pluginMetadata = new ArrayList<>(); pluginMetadata.add(image); pluginMetadata.add(tag); when(artifactPluginInfo.getArtifactConfigSettings()).thenReturn(new PluggableInstanceSettings(pluginMetadata)); ArtifactMetadataStore.instance().setPluginInfo(artifactPluginInfo); HashMap<Object, Object> configurationMap1 = new HashMap<>(); configurationMap1.put("Image", "gocd/gocd-server"); configurationMap1.put("Tag", "v18.6.0"); HashMap<String, Object> artifactPlan1 = new HashMap<>(); artifactPlan1.put("artifactTypeValue", "Pluggable Artifact"); artifactPlan1.put("id", "artifactId"); artifactPlan1.put("storeId", "storeId"); artifactPlan1.put("pluginId", "cd.go.artifact.foo"); artifactPlan1.put("configuration", configurationMap1); List<Map> artifactPlansList = new ArrayList<>(); artifactPlansList.add(artifactPlan1); ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(); artifactTypeConfigs.setConfigAttributes(artifactPlansList); assertThat(artifactTypeConfigs.size(), is(1)); PluggableArtifactConfig artifactConfig = (PluggableArtifactConfig) artifactTypeConfigs.get(0); assertThat(artifactConfig.getArtifactType(), is(ArtifactType.external)); assertThat(artifactConfig.getId(), is("artifactId")); assertThat(artifactConfig.getStoreId(), is("storeId")); assertThat(artifactConfig.getConfiguration().getProperty("Image").isSecure(), is(false)); } @Test public void setConfigAttributes_shouldSetConfigurationAsIsIfPluginIdIsBlank() throws CryptoException { HashMap<Object, Object> imageMap = new HashMap<>(); imageMap.put("value", new GoCipher().encrypt("some-encrypted-value")); imageMap.put("isSecure", "true"); HashMap<Object, Object> tagMap = new HashMap<>(); tagMap.put("value", "18.6.0"); tagMap.put("isSecure", "false"); HashMap<Object, Object> configurationMap1 = new HashMap<>(); configurationMap1.put("Image", imageMap); configurationMap1.put("Tag", tagMap); HashMap<String, Object> artifactPlan1 = new HashMap<>(); artifactPlan1.put("artifactTypeValue", "Pluggable Artifact"); artifactPlan1.put("id", "artifactId"); artifactPlan1.put("storeId", "storeId"); artifactPlan1.put("pluginId", ""); artifactPlan1.put("configuration", configurationMap1); List<Map> artifactPlansList = new ArrayList<>(); artifactPlansList.add(artifactPlan1); ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(); artifactTypeConfigs.setConfigAttributes(artifactPlansList); assertThat(artifactTypeConfigs.size(), is(1)); PluggableArtifactConfig artifactConfig = (PluggableArtifactConfig) artifactTypeConfigs.get(0); assertThat(artifactConfig.getArtifactType(), is(ArtifactType.external)); assertThat(artifactConfig.getId(), is("artifactId")); assertThat(artifactConfig.getStoreId(), is("storeId")); assertThat(artifactConfig.getConfiguration().getProperty("Image").getValue(), is("some-encrypted-value")); assertThat(artifactConfig.getConfiguration().getProperty("Tag").getValue(), is("18.6.0")); } @Test public void shouldClearAllArtifactsWhenTheMapIsNull() { ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(); artifactTypeConfigs.add(new BuildArtifactConfig("src", "dest")); artifactTypeConfigs.setConfigAttributes(null); assertThat(artifactTypeConfigs.size(), is(0)); } @Test public void shouldValidateTree() { ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(); artifactTypeConfigs.add(new BuildArtifactConfig("src", "dest")); artifactTypeConfigs.add(new BuildArtifactConfig("src", "dest")); artifactTypeConfigs.add(new BuildArtifactConfig("src", "../a")); artifactTypeConfigs.validateTree(null); assertThat(artifactTypeConfigs.get(0).errors().on(BuiltinArtifactConfig.DEST), is("Duplicate artifacts defined.")); assertThat(artifactTypeConfigs.get(0).errors().on(BuiltinArtifactConfig.SRC), is("Duplicate artifacts defined.")); assertThat(artifactTypeConfigs.get(1).errors().on(BuiltinArtifactConfig.DEST), is("Duplicate artifacts defined.")); assertThat(artifactTypeConfigs.get(1).errors().on(BuiltinArtifactConfig.SRC), is("Duplicate artifacts defined.")); assertThat(artifactTypeConfigs.get(2).errors().on(BuiltinArtifactConfig.DEST), is("Invalid destination path. Destination path should match the pattern " + FilePathTypeValidator.PATH_PATTERN)); } @Test public void shouldErrorOutWhenDuplicateArtifactConfigExists() { final ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(new BuildArtifactConfig("src", "dest")); artifactTypeConfigs.add(new BuildArtifactConfig("src", "dest")); artifactTypeConfigs.add(new BuildArtifactConfig("src", "dest")); artifactTypeConfigs.validate(null); assertFalse(artifactTypeConfigs.get(0).errors().isEmpty()); assertThat(artifactTypeConfigs.get(0).errors().on(BuiltinArtifactConfig.SRC), Matchers.is("Duplicate artifacts defined.")); assertThat(artifactTypeConfigs.get(0).errors().on(BuiltinArtifactConfig.DEST), Matchers.is("Duplicate artifacts defined.")); assertFalse(artifactTypeConfigs.get(1).errors().isEmpty()); assertThat(artifactTypeConfigs.get(1).errors().on(BuiltinArtifactConfig.SRC), Matchers.is("Duplicate artifacts defined.")); assertThat(artifactTypeConfigs.get(1).errors().on(BuiltinArtifactConfig.DEST), Matchers.is("Duplicate artifacts defined.")); assertFalse(artifactTypeConfigs.get(2).errors().isEmpty()); assertThat(artifactTypeConfigs.get(2).errors().on(BuiltinArtifactConfig.SRC), Matchers.is("Duplicate artifacts defined.")); assertThat(artifactTypeConfigs.get(2).errors().on(BuiltinArtifactConfig.DEST), Matchers.is("Duplicate artifacts defined.")); } @Test public void getArtifactConfigs_shouldReturnBuiltinArtifactConfigs() { ArtifactTypeConfigs allConfigs = new ArtifactTypeConfigs(); allConfigs.add(new BuildArtifactConfig("src", "dest")); allConfigs.add(new BuildArtifactConfig("java", null)); allConfigs.add(new PluggableArtifactConfig("s3", "cd.go.s3")); allConfigs.add(new PluggableArtifactConfig("docker", "cd.go.docker")); final List<BuiltinArtifactConfig> artifactConfigs = allConfigs.getBuiltInArtifactConfigs(); assertThat(artifactConfigs, hasSize(2)); assertThat(artifactConfigs, containsInAnyOrder( new BuildArtifactConfig("src", "dest"), new BuildArtifactConfig("java", null) )); } @Test public void getPluggableArtifactConfigs_shouldReturnPluggableArtifactConfigs() { ArtifactTypeConfigs allConfigs = new ArtifactTypeConfigs(); allConfigs.add(new BuildArtifactConfig("src", "dest")); allConfigs.add(new BuildArtifactConfig("java", null)); allConfigs.add(new PluggableArtifactConfig("s3", "cd.go.s3")); allConfigs.add(new PluggableArtifactConfig("docker", "cd.go.docker")); final List<PluggableArtifactConfig> artifactConfigs = allConfigs.getPluggableArtifactConfigs(); assertThat(artifactConfigs, hasSize(2)); assertThat(artifactConfigs, containsInAnyOrder( new PluggableArtifactConfig("s3", "cd.go.s3"), new PluggableArtifactConfig("docker", "cd.go.docker") )); } @Test public void findByArtifactId_shouldReturnPluggableArtifactConfigs() { ArtifactTypeConfigs allConfigs = new ArtifactTypeConfigs(); allConfigs.add(new PluggableArtifactConfig("s3", "cd.go.s3")); allConfigs.add(new PluggableArtifactConfig("docker", "cd.go.docker")); final PluggableArtifactConfig s3 = allConfigs.findByArtifactId("s3"); assertThat(s3, is(new PluggableArtifactConfig("s3", "cd.go.s3"))); } @Test public void findByArtifactId_shouldReturnNullWhenPluggableArtifactConfigNotExistWithGivenId() { ArtifactTypeConfigs allConfigs = new ArtifactTypeConfigs(); allConfigs.add(new PluggableArtifactConfig("s3", "cd.go.s3")); allConfigs.add(new PluggableArtifactConfig("docker", "cd.go.docker")); final PluggableArtifactConfig s3 = allConfigs.findByArtifactId("foo"); assertNull(s3); } }
gocd/gocd
config/config-api/src/test/java/com/thoughtworks/go/config/ArtifactTypeConfigsTest.java
Java
apache-2.0
14,363
<?php /* * This file is part of the Doctrine\OrientDB package. * * (c) Alessandro Nadalin <alessandro.nadalin@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Class Updates * * @package Doctrine\OrientDB * @subpackage Formatter * @author Alessandro Nadalin <alessandro.nadalin@gmail.com> */ namespace Doctrine\OrientDB\Query\Formatter\Query; use Doctrine\OrientDB\Query\Formatter\Query; class Updates extends Query implements TokenInterface { public static function format(array $values) { $string = ""; foreach ($values as $key => $value) { if ($key = self::stripNonSQLCharacters($key)) { if ($value === null) { $value = 'NULL'; } else if (is_int($value) || is_float($value)) { // Preserve content of $value as is } else if (is_bool($value)) { $value = $value ? 'TRUE' : 'FALSE'; } elseif(is_array($value)) { $value = '[' . implode(',', $value) . ']'; } else { $value = '"' . addslashes($value) . '"'; } $string .= " $key = $value,"; } } return substr($string, 0, strlen($string) - 1); } }
spartaksun/orientdb-query
src/Formatter/Query/Updates.php
PHP
apache-2.0
1,400
/* * Copyright 2015-2021 The OpenZipkin Authors * * 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. */ /* eslint-disable no-shadow */ import { faPlus } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Box, Button, Theme, createStyles, makeStyles, } from '@material-ui/core'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import { connect } from 'react-redux'; import { ThunkDispatch } from 'redux-thunk'; import Criterion, { newCriterion } from '../Criterion'; import CriterionBox from './CriterionBox'; import { loadAutocompleteValues } from '../../../slices/autocompleteValuesSlice'; import { loadRemoteServices } from '../../../slices/remoteServicesSlice'; import { loadSpans } from '../../../slices/spansSlice'; import { RootState } from '../../../store'; const useStyles = makeStyles((theme: Theme) => createStyles({ addButton: { height: 40, width: 40, minWidth: 40, color: theme.palette.common.white, }, }), ); type SearchBarProps = { searchTraces: () => void; criteria: Criterion[]; onChange: (criteria: Criterion[]) => void; serviceNames: string[]; isLoadingServiceNames: boolean; spanNames: string[]; isLoadingSpanNames: boolean; remoteServiceNames: string[]; isLoadingRemoteServiceNames: boolean; autocompleteKeys: string[]; autocompleteValues: string[]; isLoadingAutocompleteValues: boolean; loadRemoteServices: (serviceName: string) => void; loadSpans: (serviceName: string) => void; loadAutocompleteValues: (autocompleteKey: string) => void; }; export const SearchBarImpl: React.FC<SearchBarProps> = ({ searchTraces, criteria, onChange, serviceNames, isLoadingServiceNames, spanNames, isLoadingSpanNames, remoteServiceNames, isLoadingRemoteServiceNames, autocompleteKeys, autocompleteValues, isLoadingAutocompleteValues, loadRemoteServices, loadSpans, loadAutocompleteValues, }) => { const classes = useStyles(); // criterionIndex is the index of the criterion currently being edited. // If the value is -1, there is no criterion being edited. const [criterionIndex, setCriterionIndex] = useState(-1); const handleCriterionFocus = (index: number) => { setCriterionIndex(index); }; const handleCriterionChange = (index: number, criterion: Criterion) => { const newCriteria = [...criteria]; newCriteria[index] = criterion; onChange(newCriteria); }; const handleCriterionBlur = () => { setCriterionIndex(-1); }; const handleCriterionDelete = (index: number) => { const newCriteria = criteria.filter((_, i) => i !== index); onChange(newCriteria); setCriterionIndex(-1); }; const handleCriterionDecide = (index: number) => { if (index === criteria.length - 1) { const newCriteria = [...criteria]; newCriteria.push(newCriterion('', '')); onChange(newCriteria); const nextCriterionIndex = criteria.length; setCriterionIndex(nextCriterionIndex); } else { setCriterionIndex(-1); } }; const handleAddButtonClick = useCallback(() => { const newCriteria = [...criteria]; newCriteria.push(newCriterion('', '')); onChange(newCriteria); const nextCriterionIndex = criteria.length; setCriterionIndex(nextCriterionIndex); }, [criteria, onChange]); const prevServiceName = useRef(''); useEffect(() => { const criterion = criteria.find( // eslint-disable-next-line no-shadow (criterion) => criterion.key === 'serviceName', ); const serviceName = criterion ? criterion.value : ''; if (serviceName !== prevServiceName.current) { prevServiceName.current = serviceName; loadSpans(serviceName); loadRemoteServices(serviceName); } }, [criteria, loadSpans, loadRemoteServices]); // Search for traces if not all criterions are in focus // and the Enter key is pressed. // Use ref to use the latest criterionIndex state in the callback. const isFocusedRef = useRef(false); isFocusedRef.current = criterionIndex !== -1; const handleKeyDown = useCallback( (event: KeyboardEvent) => { // Use setTimeout to ensure that the callback is called // after the criterionIndex has been updated. setTimeout(() => { if (!document.activeElement) { return; } if ( !isFocusedRef.current && document.activeElement.tagName === 'BODY' && event.key === 'Enter' ) { searchTraces(); } }, 0); // Maybe 0 is enough. }, [searchTraces], ); useEffect(() => { window.addEventListener('keydown', handleKeyDown); return () => { window.removeEventListener('keydown', handleKeyDown); }; }, [handleKeyDown]); return ( <Box minHeight={60} display="flex" alignItems="center" pr={2} pl={2} pt={1} pb={1} borderRadius={3} bgcolor="background.paper" flexWrap="wrap" borderColor="grey.400" border={1} > {criteria.map((criterion, index) => ( <CriterionBox key={criterion.id} criteria={criteria} criterion={criterion} criterionIndex={index} serviceNames={serviceNames} remoteServiceNames={remoteServiceNames} spanNames={spanNames} autocompleteKeys={autocompleteKeys} autocompleteValues={autocompleteValues} isLoadingServiceNames={isLoadingServiceNames} isLoadingRemoteServiceNames={isLoadingRemoteServiceNames} isLoadingSpanNames={isLoadingSpanNames} isLoadingAutocompleteValues={isLoadingAutocompleteValues} isFocused={index === criterionIndex} onFocus={handleCriterionFocus} onBlur={handleCriterionBlur} onDecide={handleCriterionDecide} onChange={handleCriterionChange} onDelete={handleCriterionDelete} loadAutocompleteValues={loadAutocompleteValues} /> ))} <Button color="secondary" variant="contained" onClick={handleAddButtonClick} className={classes.addButton} data-testid="add-button" > <FontAwesomeIcon icon={faPlus} size="lg" /> </Button> </Box> ); }; // For unit testing, `connect` is easier to use than // useSelector or useDispatch hooks. const mapStateToProps = (state: RootState) => ({ serviceNames: state.services.services, isLoadingServiceNames: state.services.isLoading, spanNames: state.spans.spans, isLoadingSpanNames: state.spans.isLoading, remoteServiceNames: state.remoteServices.remoteServices, isLoadingRemoteServiceNames: state.remoteServices.isLoading, autocompleteKeys: state.autocompleteKeys.autocompleteKeys, autocompleteValues: state.autocompleteValues.autocompleteValues, isLoadingAutocompleteValues: state.autocompleteValues.isLoading, }); // TODO: Give the appropriate type to ThunkDispatch after TypeScriptizing all action creators. const mapDispatchToProps = ( dispatch: ThunkDispatch<RootState, undefined, any>, ) => ({ loadRemoteServices: (serviceName: string) => { dispatch(loadRemoteServices(serviceName)); }, loadSpans: (serviceName: string) => { dispatch(loadSpans(serviceName)); }, loadAutocompleteValues: (autocompleteKey: string) => { dispatch(loadAutocompleteValues(autocompleteKey)); }, }); export default connect(mapStateToProps, mapDispatchToProps)(SearchBarImpl);
openzipkin/zipkin
zipkin-lens/src/components/DiscoverPage/SearchBar/SearchBar.tsx
TypeScript
apache-2.0
8,051
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.ml.action; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.HandledTransportAction; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.tasks.Task; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.core.ml.action.GetTrainedModelsAction; import org.elasticsearch.xpack.core.ml.action.GetTrainedModelsAction.Request; import org.elasticsearch.xpack.core.ml.action.GetTrainedModelsAction.Response; import org.elasticsearch.xpack.core.ml.job.messages.Messages; import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper; import org.elasticsearch.xpack.ml.inference.persistence.TrainedModelProvider; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class TransportGetTrainedModelsAction extends HandledTransportAction<Request, Response> { private final TrainedModelProvider provider; @Inject public TransportGetTrainedModelsAction(TransportService transportService, ActionFilters actionFilters, TrainedModelProvider trainedModelProvider) { super(GetTrainedModelsAction.NAME, transportService, actionFilters, GetTrainedModelsAction.Request::new); this.provider = trainedModelProvider; } @Override protected void doExecute(Task task, Request request, ActionListener<Response> listener) { Response.Builder responseBuilder = Response.builder(); ActionListener<Tuple<Long, Set<String>>> idExpansionListener = ActionListener.wrap( totalAndIds -> { responseBuilder.setTotalCount(totalAndIds.v1()); if (totalAndIds.v2().isEmpty()) { listener.onResponse(responseBuilder.build()); return; } if (request.getIncludes().isIncludeModelDefinition() && totalAndIds.v2().size() > 1) { listener.onFailure( ExceptionsHelper.badRequestException(Messages.INFERENCE_TOO_MANY_DEFINITIONS_REQUESTED) ); return; } if (request.getIncludes().isIncludeModelDefinition()) { provider.getTrainedModel( totalAndIds.v2().iterator().next(), request.getIncludes(), ActionListener.wrap( config -> listener.onResponse(responseBuilder.setModels(Collections.singletonList(config)).build()), listener::onFailure ) ); } else { provider.getTrainedModels( totalAndIds.v2(), request.getIncludes(), request.isAllowNoResources(), ActionListener.wrap( configs -> listener.onResponse(responseBuilder.setModels(configs).build()), listener::onFailure ) ); } }, listener::onFailure ); provider.expandIds(request.getResourceId(), request.isAllowNoResources(), request.getPageParams(), new HashSet<>(request.getTags()), idExpansionListener); } }
nknize/elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportGetTrainedModelsAction.java
Java
apache-2.0
3,814
// Copyright 2004, 2005, 2006 The Apache Software Foundation // // 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.apache.tapestry5.ioc.test.internal.services; public interface MiddleFilter { public void execute(int count, char ch, MiddleService service, StringBuilder buffer); }
apache/tapestry-5
tapestry-ioc/src/test/java/org/apache/tapestry5/ioc/test/internal/services/MiddleFilter.java
Java
apache-2.0
802
# # # 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. # # Shell commands module module Shell @@commands = {} def self.commands @@commands end @@command_groups = {} def self.command_groups @@command_groups end def self.load_command(name, group, aliases = []) return if commands[name] # Register command in the group raise ArgumentError, "Unknown group: #{group}" unless command_groups[group] command_groups[group][:commands] << name # Load command begin require "shell/commands/#{name}" klass_name = name.to_s.gsub(/(?:^|_)(.)/) { Regexp.last_match(1).upcase } # camelize commands[name] = eval("Commands::#{klass_name}") aliases.each do |an_alias| commands[an_alias] = commands[name] end rescue => e raise "Can't load hbase shell command: #{name}. Error: #{e}\n#{e.backtrace.join("\n")}" end end def self.load_command_group(group, opts) raise ArgumentError, "No :commands for group #{group}" unless opts[:commands] command_groups[group] = { commands: [], command_names: opts[:commands], full_name: opts[:full_name] || group, comment: opts[:comment] } all_aliases = opts[:aliases] || {} opts[:commands].each do |command| aliases = all_aliases[command] || [] load_command(command, group, aliases) end end #---------------------------------------------------------------------- class Shell attr_accessor :hbase attr_accessor :interactive alias interactive? interactive @debug = false attr_accessor :debug def initialize(hbase, interactive = true) self.hbase = hbase self.interactive = interactive end # Returns Admin class from admin.rb def admin @admin ||= hbase.admin end def hbase_taskmonitor @hbase_taskmonitor ||= hbase.taskmonitor end def hbase_table(name) hbase.table(name, self) end def hbase_replication_admin @hbase_replication_admin ||= hbase.replication_admin end def hbase_security_admin @hbase_security_admin ||= hbase.security_admin end def hbase_visibility_labels_admin @hbase_visibility_labels_admin ||= hbase.visibility_labels_admin end def hbase_quotas_admin @hbase_quotas_admin ||= hbase.quotas_admin end def hbase_rsgroup_admin @rsgroup_admin ||= hbase.rsgroup_admin end def export_commands(where) ::Shell.commands.keys.each do |cmd| # here where is the IRB namespace # this method just adds the call to the specified command # which just references back to 'this' shell object # a decently extensible way to add commands where.send :instance_eval, <<-EOF def #{cmd}(*args) ret = @shell.command('#{cmd}', *args) puts return ret end EOF end end def command_instance(command) ::Shell.commands[command.to_s].new(self) end # call the method 'command' on the specified command # If interactive is enabled, then we suppress the return value. The command should have # printed relevant output. # Return value is only useful in non-interactive mode, for e.g. tests. def command(command, *args) ret = internal_command(command, :command, *args) if interactive return nil else return ret end end # call a specific internal method in the command instance # command - name of the command to call # method_name - name of the method on the command to call. Defaults to just 'command' # args - to be passed to the named method def internal_command(command, method_name = :command, *args) command_instance(command).command_safe(debug, method_name, *args) end def print_banner puts 'HBase Shell' puts 'Use "help" to get list of supported commands.' puts 'Use "exit" to quit this interactive shell.' print 'Version ' command('version') puts end def help_multi_command(command) puts "Command: #{command}" puts command_instance(command).help puts nil end def help_command(command) puts command_instance(command).help nil end def help_group(group_name) group = ::Shell.command_groups[group_name.to_s] group[:commands].sort.each { |cmd| help_multi_command(cmd) } if group[:comment] puts '-' * 80 puts puts group[:comment] puts end nil end def help(command = nil) if command return help_command(command) if ::Shell.commands[command.to_s] return help_group(command) if ::Shell.command_groups[command.to_s] puts "ERROR: Invalid command or command group name: #{command}" puts end puts help_header puts puts 'COMMAND GROUPS:' ::Shell.command_groups.each do |name, group| puts ' Group name: ' + name puts ' Commands: ' + group[:command_names].sort.join(', ') puts end unless command puts 'SHELL USAGE:' help_footer end nil end def help_header "HBase Shell, version #{org.apache.hadoop.hbase.util.VersionInfo.getVersion}, " \ "r#{org.apache.hadoop.hbase.util.VersionInfo.getRevision}, " \ "#{org.apache.hadoop.hbase.util.VersionInfo.getDate}" + "\n" \ "Type 'help \"COMMAND\"', (e.g. 'help \"get\"' -- the quotes are necessary) for help on a specific command.\n" \ "Commands are grouped. Type 'help \"COMMAND_GROUP\"', (e.g. 'help \"general\"') for help on a command group." end def help_footer puts <<-HERE Quote all names in HBase Shell such as table and column names. Commas delimit command parameters. Type <RETURN> after entering a command to run it. Dictionaries of configuration used in the creation and alteration of tables are Ruby Hashes. They look like this: {'key1' => 'value1', 'key2' => 'value2', ...} and are opened and closed with curley-braces. Key/values are delimited by the '=>' character combination. Usually keys are predefined constants such as NAME, VERSIONS, COMPRESSION, etc. Constants do not need to be quoted. Type 'Object.constants' to see a (messy) list of all constants in the environment. If you are using binary keys or values and need to enter them in the shell, use double-quote'd hexadecimal representation. For example: hbase> get 't1', "key\\x03\\x3f\\xcd" hbase> get 't1', "key\\003\\023\\011" hbase> put 't1', "test\\xef\\xff", 'f1:', "\\x01\\x33\\x40" The HBase shell is the (J)Ruby IRB with the above HBase-specific commands added. For more on the HBase Shell, see http://hbase.apache.org/book.html HERE end end end # Load commands base class require 'shell/commands' # Load all commands Shell.load_command_group( 'general', full_name: 'GENERAL HBASE SHELL COMMANDS', commands: %w[ status version table_help whoami processlist ] ) Shell.load_command_group( 'ddl', full_name: 'TABLES MANAGEMENT COMMANDS', commands: %w[ alter create describe disable disable_all is_disabled drop drop_all enable enable_all is_enabled exists list show_filters alter_status alter_async get_table locate_region list_regions ], aliases: { 'describe' => ['desc'] } ) Shell.load_command_group( 'namespace', full_name: 'NAMESPACE MANAGEMENT COMMANDS', commands: %w[ create_namespace drop_namespace alter_namespace describe_namespace list_namespace list_namespace_tables ] ) Shell.load_command_group( 'dml', full_name: 'DATA MANIPULATION COMMANDS', commands: %w[ count delete deleteall get get_counter incr put scan truncate truncate_preserve append get_splits ] ) Shell.load_command_group( 'tools', full_name: 'HBASE SURGERY TOOLS', comment: "WARNING: Above commands are for 'experts'-only as misuse can damage an install", commands: %w[ assign balancer balance_switch balancer_enabled normalize normalizer_switch normalizer_enabled close_region compact flush major_compact move split merge_region unassign zk_dump wal_roll catalogjanitor_run catalogjanitor_switch catalogjanitor_enabled cleaner_chore_run cleaner_chore_switch cleaner_chore_enabled compact_rs compaction_state trace splitormerge_switch splitormerge_enabled clear_compaction_queues list_deadservers clear_deadservers ], # TODO: remove older hlog_roll command aliases: { 'wal_roll' => ['hlog_roll'] } ) Shell.load_command_group( 'replication', full_name: 'CLUSTER REPLICATION TOOLS', commands: %w[ add_peer remove_peer list_peers enable_peer disable_peer set_peer_namespaces append_peer_namespaces remove_peer_namespaces show_peer_tableCFs set_peer_tableCFs set_peer_bandwidth list_replicated_tables append_peer_tableCFs remove_peer_tableCFs enable_table_replication disable_table_replication get_peer_config list_peer_configs update_peer_config ] ) Shell.load_command_group( 'snapshots', full_name: 'CLUSTER SNAPSHOT TOOLS', commands: %w[ snapshot clone_snapshot restore_snapshot delete_snapshot delete_all_snapshot delete_table_snapshots list_snapshots list_table_snapshots ] ) Shell.load_command_group( 'configuration', full_name: 'ONLINE CONFIGURATION TOOLS', commands: %w[ update_config update_all_config ] ) Shell.load_command_group( 'quotas', full_name: 'CLUSTER QUOTAS TOOLS', commands: %w[ set_quota list_quotas list_quota_table_sizes list_quota_snapshots list_snapshot_sizes ] ) Shell.load_command_group( 'security', full_name: 'SECURITY TOOLS', comment: 'NOTE: Above commands are only applicable if running with the AccessController coprocessor', commands: %w[ list_security_capabilities grant revoke user_permission ] ) Shell.load_command_group( 'procedures', full_name: 'PROCEDURES & LOCKS MANAGEMENT', commands: %w[ abort_procedure list_procedures list_locks ] ) Shell.load_command_group( 'visibility labels', full_name: 'VISIBILITY LABEL TOOLS', comment: 'NOTE: Above commands are only applicable if running with the VisibilityController coprocessor', commands: %w[ add_labels list_labels set_auths get_auths clear_auths set_visibility ] ) Shell.load_command_group( 'rsgroup', full_name: 'RSGroups', comment: "NOTE: The rsgroup Coprocessor Endpoint must be enabled on the Master else commands fail with: UnknownProtocolException: No registered Master Coprocessor Endpoint found for RSGroupAdminService", commands: %w[ list_rsgroups get_rsgroup add_rsgroup remove_rsgroup balance_rsgroup move_servers_rsgroup move_tables_rsgroup move_servers_tables_rsgroup get_server_rsgroup get_table_rsgroup ] )
JingchengDu/hbase
hbase-shell/src/main/ruby/shell.rb
Ruby
apache-2.0
11,986
package io.cattle.platform.process.agent; import io.cattle.platform.agent.util.AgentUtils; import io.cattle.platform.core.constants.StoragePoolConstants; import io.cattle.platform.core.model.Account; import io.cattle.platform.core.model.Agent; import io.cattle.platform.core.model.StoragePool; import io.cattle.platform.engine.handler.HandlerResult; import io.cattle.platform.engine.process.ProcessInstance; import io.cattle.platform.engine.process.ProcessState; import io.cattle.platform.process.common.handler.AbstractObjectProcessHandler; import io.github.ibuildthecloud.gdapi.factory.SchemaFactory; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Named public class AgentRemove extends AbstractObjectProcessHandler { private static final Logger log = LoggerFactory.getLogger(AgentRemove.class); @Inject @Named("CoreSchemaFactory") SchemaFactory schemaFactory; @Override public String[] getProcessNames() { return new String[] {"agent.remove"}; } @Override public HandlerResult handle(ProcessState state, ProcessInstance process) { Agent agent = (Agent)state.getResource(); for (String type : AgentUtils.AGENT_RESOURCES.get()) { Class<?> clz = schemaFactory.getSchemaClass(type); if (clz == null) { log.error("Failed to find class for [{}]", type); continue; } for (Object obj : objectManager.children(agent, clz)) { if (obj instanceof StoragePool) { StoragePool sp = (StoragePool)obj; if (StoragePoolConstants.TYPE.equals(sp.getKind())) { // Don't automatically delete shared storage pools continue; } } deactivateThenScheduleRemove(obj, state.getData()); } } deactivateThenScheduleRemove(objectManager.loadResource(Account.class, agent.getAccountId()), state.getData()); return null; } }
wlan0/cattle
code/iaas/logic/src/main/java/io/cattle/platform/process/agent/AgentRemove.java
Java
apache-2.0
2,106
/** * */ package org.hamster.weixinmp.model.menu; import java.util.List; import org.hamster.weixinmp.dao.entity.menu.WxMenuBtnEntity; /** * @author honey.zhao@aliyun.com * @version Aug 4, 2013 * */ public class WxMenuCreateJson { private List<WxMenuBtnEntity> button; public List<WxMenuBtnEntity> getButton() { return button; } public void setButton(List<WxMenuBtnEntity> button) { this.button = button; } public WxMenuCreateJson() { super(); // TODO Auto-generated constructor stub } public WxMenuCreateJson(List<WxMenuBtnEntity> button) { super(); this.button = button; } }
Wingo7239/WeixinMultiPlatform
src/main/java/org/hamster/weixinmp/model/menu/WxMenuCreateJson.java
Java
apache-2.0
617
# # 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. # """TFRecord sources and sinks.""" from __future__ import absolute_import import logging import struct from apache_beam import coders from apache_beam.io import filebasedsource from apache_beam.io import fileio from apache_beam.io.iobase import Read from apache_beam.io.iobase import Write from apache_beam.transforms import PTransform import crcmod __all__ = ['ReadFromTFRecord', 'WriteToTFRecord'] def _default_crc32c_fn(value): """Calculates crc32c by either snappy or crcmod based on installation.""" if not _default_crc32c_fn.fn: try: import snappy # pylint: disable=import-error _default_crc32c_fn.fn = snappy._crc32c # pylint: disable=protected-access except ImportError: logging.warning('Couldn\'t find python-snappy so the implementation of ' '_TFRecordUtil._masked_crc32c is not as fast as it could ' 'be.') _default_crc32c_fn.fn = crcmod.predefined.mkPredefinedCrcFun('crc-32c') return _default_crc32c_fn.fn(value) _default_crc32c_fn.fn = None class _TFRecordUtil(object): """Provides basic TFRecord encoding/decoding with consistency checks. For detailed TFRecord format description see: https://www.tensorflow.org/versions/master/api_docs/python/python_io.html#tfrecords-format-details Note that masks and length are represented in LittleEndian order. """ @classmethod def _masked_crc32c(cls, value, crc32c_fn=_default_crc32c_fn): """Compute a masked crc32c checksum for a value. Args: value: A string for which we compute the crc. crc32c_fn: A function that can compute a crc32c. This is a performance hook that also helps with testing. Callers are not expected to make use of it directly. Returns: Masked crc32c checksum. """ crc = crc32c_fn(value) return (((crc >> 15) | (crc << 17)) + 0xa282ead8) & 0xffffffff @staticmethod def encoded_num_bytes(record): """Return the number of bytes consumed by a record in its encoded form.""" # 16 = 8 (Length) + 4 (crc of length) + 4 (crc of data) return len(record) + 16 @classmethod def write_record(cls, file_handle, value): """Encode a value as a TFRecord. Args: file_handle: The file to write to. value: A string content of the record. """ encoded_length = struct.pack('<Q', len(value)) file_handle.write('{}{}{}{}'.format( encoded_length, struct.pack('<I', cls._masked_crc32c(encoded_length)), # value, struct.pack('<I', cls._masked_crc32c(value)))) @classmethod def read_record(cls, file_handle): """Read a record from a TFRecords file. Args: file_handle: The file to read from. Returns: None if EOF is reached; the paylod of the record otherwise. Raises: ValueError: If file appears to not be a valid TFRecords file. """ buf_length_expected = 12 buf = file_handle.read(buf_length_expected) if not buf: return None # EOF Reached. # Validate all length related payloads. if len(buf) != buf_length_expected: raise ValueError('Not a valid TFRecord. Fewer than %d bytes: %s' % (buf_length_expected, buf.encode('hex'))) length, length_mask_expected = struct.unpack('<QI', buf) length_mask_actual = cls._masked_crc32c(buf[:8]) if length_mask_actual != length_mask_expected: raise ValueError('Not a valid TFRecord. Mismatch of length mask: %s' % buf.encode('hex')) # Validate all data related payloads. buf_length_expected = length + 4 buf = file_handle.read(buf_length_expected) if len(buf) != buf_length_expected: raise ValueError('Not a valid TFRecord. Fewer than %d bytes: %s' % (buf_length_expected, buf.encode('hex'))) data, data_mask_expected = struct.unpack('<%dsI' % length, buf) data_mask_actual = cls._masked_crc32c(data) if data_mask_actual != data_mask_expected: raise ValueError('Not a valid TFRecord. Mismatch of data mask: %s' % buf.encode('hex')) # All validation checks passed. return data class _TFRecordSource(filebasedsource.FileBasedSource): """A File source for reading files of TFRecords. For detailed TFRecords format description see: https://www.tensorflow.org/versions/master/api_docs/python/python_io.html#tfrecords-format-details """ def __init__(self, file_pattern, coder, compression_type, validate): """Initialize a TFRecordSource. See ReadFromTFRecord for details.""" super(_TFRecordSource, self).__init__( file_pattern=file_pattern, compression_type=compression_type, splittable=False, validate=validate) self._coder = coder def read_records(self, file_name, offset_range_tracker): if offset_range_tracker.start_position(): raise ValueError('Start position not 0:%s' % offset_range_tracker.start_position()) current_offset = offset_range_tracker.start_position() with self.open_file(file_name) as file_handle: while True: if not offset_range_tracker.try_claim(current_offset): raise RuntimeError('Unable to claim position: %s' % current_offset) record = _TFRecordUtil.read_record(file_handle) if record is None: return # Reached EOF else: current_offset += _TFRecordUtil.encoded_num_bytes(record) yield self._coder.decode(record) class ReadFromTFRecord(PTransform): """Transform for reading TFRecord sources.""" def __init__(self, file_pattern, coder=coders.BytesCoder(), compression_type=fileio.CompressionTypes.AUTO, validate=True, **kwargs): """Initialize a ReadFromTFRecord transform. Args: file_pattern: A file glob pattern to read TFRecords from. coder: Coder used to decode each record. compression_type: Used to handle compressed input files. Default value is CompressionTypes.AUTO, in which case the file_path's extension will be used to detect the compression. validate: Boolean flag to verify that the files exist during the pipeline creation time. **kwargs: optional args dictionary. These are passed through to parent constructor. Returns: A ReadFromTFRecord transform object. """ super(ReadFromTFRecord, self).__init__(**kwargs) self._args = (file_pattern, coder, compression_type, validate) def expand(self, pvalue): return pvalue.pipeline | Read(_TFRecordSource(*self._args)) class _TFRecordSink(fileio.FileSink): """Sink for writing TFRecords files. For detailed TFRecord format description see: https://www.tensorflow.org/versions/master/api_docs/python/python_io.html#tfrecords-format-details """ def __init__(self, file_path_prefix, coder, file_name_suffix, num_shards, shard_name_template, compression_type): """Initialize a TFRecordSink. See WriteToTFRecord for details.""" super(_TFRecordSink, self).__init__( file_path_prefix=file_path_prefix, coder=coder, file_name_suffix=file_name_suffix, num_shards=num_shards, shard_name_template=shard_name_template, mime_type='application/octet-stream', compression_type=compression_type) def write_encoded_record(self, file_handle, value): _TFRecordUtil.write_record(file_handle, value) class WriteToTFRecord(PTransform): """Transform for writing to TFRecord sinks.""" def __init__(self, file_path_prefix, coder=coders.BytesCoder(), file_name_suffix='', num_shards=0, shard_name_template=fileio.DEFAULT_SHARD_NAME_TEMPLATE, compression_type=fileio.CompressionTypes.AUTO, **kwargs): """Initialize WriteToTFRecord transform. Args: file_path_prefix: The file path to write to. The files written will begin with this prefix, followed by a shard identifier (see num_shards), and end in a common extension, if given by file_name_suffix. coder: Coder used to encode each record. file_name_suffix: Suffix for the files written. num_shards: The number of files (shards) used for output. If not set, the default value will be used. shard_name_template: A template string containing placeholders for the shard number and shard count. Currently only '' and '-SSSSS-of-NNNNN' are patterns allowed. When constructing a filename for a particular shard number, the upper-case letters 'S' and 'N' are replaced with the 0-padded shard number and shard count respectively. This argument can be '' in which case it behaves as if num_shards was set to 1 and only one file will be generated. The default pattern is '-SSSSS-of-NNNNN'. compression_type: Used to handle compressed output files. Typical value is CompressionTypes.AUTO, in which case the file_path's extension will be used to detect the compression. **kwargs: Optional args dictionary. These are passed through to parent constructor. Returns: A WriteToTFRecord transform object. """ super(WriteToTFRecord, self).__init__(**kwargs) self._args = (file_path_prefix, coder, file_name_suffix, num_shards, shard_name_template, compression_type) def expand(self, pcoll): return pcoll | Write(_TFRecordSink(*self._args))
chamikaramj/incubator-beam
sdks/python/apache_beam/io/tfrecordio.py
Python
apache-2.0
10,445
package daemon import ( "fmt" "sync" "time" "github.com/docker/docker/pkg/units" ) type State struct { sync.Mutex Running bool Paused bool Restarting bool Pid int ExitCode int StartedAt time.Time FinishedAt time.Time waitChan chan struct{} } func NewState() *State { return &State{ waitChan: make(chan struct{}), } } // String returns a human-readable description of the state func (s *State) String() string { if s.Running { if s.Paused { return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) } if s.Restarting { return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) } return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) } if s.FinishedAt.IsZero() { return "" } return fmt.Sprintf("Exited (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) } func wait(waitChan <-chan struct{}, timeout time.Duration) error { if timeout < 0 { <-waitChan return nil } select { case <-time.After(timeout): return fmt.Errorf("Timed out: %v", timeout) case <-waitChan: return nil } } // WaitRunning waits until state is running. If state already running it returns // immediatly. If you want wait forever you must supply negative timeout. // Returns pid, that was passed to SetRunning func (s *State) WaitRunning(timeout time.Duration) (int, error) { s.Lock() if s.Running { pid := s.Pid s.Unlock() return pid, nil } waitChan := s.waitChan s.Unlock() if err := wait(waitChan, timeout); err != nil { return -1, err } return s.GetPid(), nil } // WaitStop waits until state is stopped. If state already stopped it returns // immediatly. If you want wait forever you must supply negative timeout. // Returns exit code, that was passed to SetStopped func (s *State) WaitStop(timeout time.Duration) (int, error) { s.Lock() if !s.Running { exitCode := s.ExitCode s.Unlock() return exitCode, nil } waitChan := s.waitChan s.Unlock() if err := wait(waitChan, timeout); err != nil { return -1, err } return s.GetExitCode(), nil } func (s *State) IsRunning() bool { s.Lock() res := s.Running s.Unlock() return res } func (s *State) GetPid() int { s.Lock() res := s.Pid s.Unlock() return res } func (s *State) GetExitCode() int { s.Lock() res := s.ExitCode s.Unlock() return res } func (s *State) SetRunning(pid int) { s.Lock() s.setRunning(pid) s.Unlock() } func (s *State) setRunning(pid int) { s.Running = true s.Paused = false s.Restarting = false s.ExitCode = 0 s.Pid = pid s.StartedAt = time.Now().UTC() close(s.waitChan) // fire waiters for start s.waitChan = make(chan struct{}) } func (s *State) SetStopped(exitCode int) { s.Lock() s.setStopped(exitCode) s.Unlock() } func (s *State) setStopped(exitCode int) { s.Running = false s.Restarting = false s.Pid = 0 s.FinishedAt = time.Now().UTC() s.ExitCode = exitCode close(s.waitChan) // fire waiters for stop s.waitChan = make(chan struct{}) } // SetRestarting is when docker hanldes the auto restart of containers when they are // in the middle of a stop and being restarted again func (s *State) SetRestarting(exitCode int) { s.Lock() // we should consider the container running when it is restarting because of // all the checks in docker around rm/stop/etc s.Running = true s.Restarting = true s.Pid = 0 s.FinishedAt = time.Now().UTC() s.ExitCode = exitCode close(s.waitChan) // fire waiters for stop s.waitChan = make(chan struct{}) s.Unlock() } func (s *State) IsRestarting() bool { s.Lock() res := s.Restarting s.Unlock() return res } func (s *State) SetPaused() { s.Lock() s.Paused = true s.Unlock() } func (s *State) SetUnpaused() { s.Lock() s.Paused = false s.Unlock() } func (s *State) IsPaused() bool { s.Lock() res := s.Paused s.Unlock() return res }
mwhudson/docker
daemon/state.go
GO
apache-2.0
3,937
/* * Copyright 2012-2016 bambooCORE, greenstep of copyright Chen Xin Nien * * 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. * * ----------------------------------------------------------------------- * * author: Chen Xin Nien * contact: chen.xin.nien@gmail.com * */ package com.netsteadfast.greenstep.qcharts.action.utils; import org.apache.commons.lang3.StringUtils; import com.netsteadfast.greenstep.base.Constants; import com.netsteadfast.greenstep.base.exception.ControllerException; import com.netsteadfast.greenstep.base.model.IActionFieldsCheckUtils; public class SelectItemFieldCheckUtils implements IActionFieldsCheckUtils { @Override public boolean check(String value) throws ControllerException { if (StringUtils.isBlank(value) || Constants.HTML_SELECT_NO_SELECT_ID.equals(value)) { return false; } return true; } }
quangnguyen9x/bamboobsc_quangnv
qcharts-web/src/com/netsteadfast/greenstep/qcharts/action/utils/SelectItemFieldCheckUtils.java
Java
apache-2.0
1,369
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.mskcc.shenkers.control.track; /** * * @author sol */ public enum FileType { BAM, WIG, GTF, BED, FASTA }
shenkers/CrossBrowse
src/main/java/org/mskcc/shenkers/control/track/FileType.java
Java
apache-2.0
326
import React from 'react'; import { Box, WorldMap } from 'grommet'; export const SelectPlace = () => { const [places, setPlaces] = React.useState(); const onSelectPlace = (place) => { console.log('Selected', place); setPlaces([{ color: 'graph-1', location: place }]); }; return ( <Box align="center" pad="large"> <WorldMap onSelectPlace={onSelectPlace} places={places} /> </Box> ); }; SelectPlace.storyName = 'Select place'; SelectPlace.parameters = { chromatic: { disable: true }, }; export default { title: 'Visualizations/WorldMap/Select place', };
HewlettPackard/grommet
src/js/components/WorldMap/stories/SelectPlace.js
JavaScript
apache-2.0
595
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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.openregistry.core.domain; import java.io.Serializable; /** * @author Scott Battaglia * @version $Revision$ $Date$ * @since 1.0.0 */ public interface OrganizationalUnit extends Serializable { Long getId(); Type getOrganizationalUnitType(); String getLocalCode(); String getName(); Campus getCampus(); OrganizationalUnit getParentOrganizationalUnit(); String getRBHS(); void setRBHS(String RBHS); String getPHI(); void setPHI(String PHI); }
sheliu/openregistry
openregistry-api/src/main/java/org/openregistry/core/domain/OrganizationalUnit.java
Java
apache-2.0
1,279
package com.github.czyzby.lml.parser.impl.attribute.list; import com.badlogic.gdx.scenes.scene2d.ui.List; import com.github.czyzby.lml.parser.LmlParser; import com.github.czyzby.lml.parser.tag.LmlAttribute; import com.github.czyzby.lml.parser.tag.LmlTag; /** See {@link com.badlogic.gdx.scenes.scene2d.utils.Selection#setRequired(boolean)}. Mapped to "required". * * @author MJ */ public class RequiredLmlAttribute implements LmlAttribute<List<?>> { @Override @SuppressWarnings("unchecked") public Class<List<?>> getHandledType() { // Double cast as there were a problem with generics - SomeClass.class cannot be returned as // <Class<SomeClass<?>>, even though casting never throws ClassCastException in the end. return (Class<List<?>>) (Object) List.class; } @Override public void process(final LmlParser parser, final LmlTag tag, final List<?> actor, final String rawAttributeData) { actor.getSelection().setRequired(parser.parseBoolean(rawAttributeData, actor)); } }
tommyettinger/SquidSetup
src/main/java/com/github/czyzby/lml/parser/impl/attribute/list/RequiredLmlAttribute.java
Java
apache-2.0
1,036
/* * 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.cocoon.portal.acting; import java.util.Map; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Redirector; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.portal.event.Event; import org.apache.cocoon.portal.event.EventManager; import org.apache.cocoon.portal.event.coplet.CopletJXPathEvent; import org.apache.cocoon.portal.sitemap.Constants; /** * Using this action, you can set values in a coplet. * * @version $Id$ */ public class CopletSetDataAction extends AbstractPortalAction { /** * @see org.apache.cocoon.acting.Action#act(org.apache.cocoon.environment.Redirector, org.apache.cocoon.environment.SourceResolver, java.util.Map, java.lang.String, org.apache.avalon.framework.parameters.Parameters) */ public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception { // determine coplet id String copletId = null; Map context = (Map)objectModel.get(ObjectModelHelper.PARENT_CONTEXT); if (context != null) { copletId = (String)context.get(Constants.COPLET_ID_KEY); } else { copletId = (String)objectModel.get(Constants.COPLET_ID_KEY); } if (copletId == null) { throw new ConfigurationException("copletId must be passed in the object model either directly (e.g. by using ObjectModelAction) or within the parent context."); } // now traverse parameters: // parameter name is path // parameter value is value // if the value is null or empty, the value is not set! final String[] names = parameters.getNames(); if ( names != null ) { final EventManager publisher = this.portalService.getEventManager(); for(int i=0; i<names.length; i++) { final String path = names[i]; final String value = parameters.getParameter(path, null ); if ( value != null && value.trim().length() > 0 ) { final Event event = new CopletJXPathEvent(this.portalService.getProfileManager().getCopletInstance(copletId), path, value); publisher.send(event); } } } return EMPTY_MAP; } }
apache/cocoon
blocks/cocoon-portal/cocoon-portal-sitemap/src/main/java/org/apache/cocoon/portal/acting/CopletSetDataAction.java
Java
apache-2.0
3,337
<?php include('dao.php'); global $dbh; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $data = ''; $id = $_POST['id']; $status = $_POST['status']; if($status == "Failed" || $status == "Rejected"){ $failureReason = $_POST['failureReason']; $sql = $dbh->prepare("UPDATE tbl_totalsentmessages SET sent_status = :status, failure_reason=:reason WHERE sent_messageid = :id"); $sql->bindParam(":status", $status ); $sql->bindParam(":reason", $failureReason); $sql->bindParam(":id", $id ); try { $data = $sql->execute(); } catch(PDOException $e) { echo $e->getMessage(); } if ($data) { echo '1'; } else { echo '0'; } } else { $sql = $dbh->prepare("UPDATE tbl_totalsentmessages SET sent_status = :status WHERE sent_messageid = :id"); $sql->bindParam(":status", $status ); $sql->bindParam(":id", $id ); try { $data = $sql->execute(); } catch(PDOException $e) { echo $e->getMessage(); } if ($data) { echo '1'; } else { echo '0'; } } ?>
chebryan/Qsoft-Admin
core/callback_url.php
PHP
apache-2.0
1,383
/*! * ${copyright} */ // Provides the Design Time Metadata for the sap.m.Slider control sap.ui.define([], function () { "use strict"; return { name: { singular: "SLIDER_NAME", plural: "SLIDER_NAME_PLURAL" }, palette: { group: "INPUT", icons: { svg: "sap/m/designtime/Slider.icon.svg" } }, actions: { remove: { changeType: "hideControl" }, reveal: { changeType: "unhideControl" } }, aggregations: { scale: { domRef: ":sap-domref > .sapMSliderTickmarks" }, customTooltips: { ignore: true } }, templates: { create: "sap/m/designtime/Slider.create.fragment.xml" } }; }, /* bExport= */ true);
SAP/openui5
src/sap.m/src/sap/m/designtime/Slider.designtime.js
JavaScript
apache-2.0
709
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using System.Numerics; [assembly: PythonModule("math", typeof(IronPython.Modules.PythonMath))] namespace IronPython.Modules { public static partial class PythonMath { public const string __doc__ = "Provides common mathematical functions."; public const double pi = Math.PI; public const double e = Math.E; private const double degreesToRadians = Math.PI / 180.0; private const int Bias = 0x3FE; public static double degrees(double radians) { return Check(radians, radians / degreesToRadians); } public static double radians(double degrees) { return Check(degrees, degrees * degreesToRadians); } public static double fmod(double v, double w) { return Check(v, w, v % w); } private static double sum(List<double> partials) { // sum the partials the same was as CPython does var n = partials.Count; var hi = 0.0; if (n == 0) return hi; var lo = 0.0; // sum exact while (n > 0) { var x = hi; var y = partials[--n]; hi = x + y; lo = y - (hi - x); if (lo != 0.0) break; } if (n == 0) return hi; // half-even rounding if (lo < 0.0 && partials[n - 1] < 0.0 || lo > 0.0 && partials[n - 1] > 0.0) { var y = lo * 2.0; var x = hi + y; var yr = x - hi; if (y == yr) hi = x; } return hi; } public static double fsum(IEnumerable e) { // msum from https://code.activestate.com/recipes/393090/ var partials = new List<double>(); foreach (var v in e.Cast<object>().Select(o => Converter.ConvertToDouble(o))) { var x = v; var i = 0; for (var j = 0; j < partials.Count; j++) { var y = partials[j]; if (Math.Abs(x) < Math.Abs(y)) { var t = x; x = y; y = t; } var hi = x + y; var lo = y - (hi - x); if (lo != 0) { partials[i++] = lo; } x = hi; } partials.RemoveRange(i, partials.Count - i); partials.Add(x); } return sum(partials); } public static PythonTuple frexp(double v) { if (Double.IsInfinity(v) || Double.IsNaN(v)) { return PythonTuple.MakeTuple(v, 0.0); } int exponent = 0; double mantissa = 0; if (v == 0) { mantissa = 0; exponent = 0; } else { byte[] vb = BitConverter.GetBytes(v); if (BitConverter.IsLittleEndian) { DecomposeLe(vb, out mantissa, out exponent); } else { throw new NotImplementedException(); } } return PythonTuple.MakeTuple(mantissa, exponent); } public static PythonTuple modf(double v) { if (double.IsInfinity(v)) { return PythonTuple.MakeTuple(0.0, v); } double w = v % 1.0; v -= w; return PythonTuple.MakeTuple(w, v); } public static double ldexp(double v, BigInteger w) { if (v == 0.0 || double.IsInfinity(v)) { return v; } return Check(v, v * Math.Pow(2.0, (double)w)); } public static double hypot(double v, double w) { if (double.IsInfinity(v) || double.IsInfinity(w)) { return double.PositiveInfinity; } return Check(v, w, MathUtils.Hypot(v, w)); } public static double pow(double v, double exp) { if (v == 1.0 || exp == 0.0) { return 1.0; } else if (double.IsNaN(v) || double.IsNaN(exp)) { return double.NaN; } else if (v == 0.0) { if (exp > 0.0) { return 0.0; } throw PythonOps.ValueError("math domain error"); } else if (double.IsPositiveInfinity(exp)) { if (v > 1.0 || v < -1.0) { return double.PositiveInfinity; } else if (v == -1.0) { return 1.0; } else { return 0.0; } } else if (double.IsNegativeInfinity(exp)) { if (v > 1.0 || v < -1.0) { return 0.0; } else if (v == -1.0) { return 1.0; } else { return double.PositiveInfinity; } } return Check(v, exp, Math.Pow(v, exp)); } public static double log(double v0) { if (v0 <= 0.0) { throw PythonOps.ValueError("math domain error"); } return Check(v0, Math.Log(v0)); } public static double log(double v0, double v1) { if (v0 <= 0.0 || v1 == 0.0) { throw PythonOps.ValueError("math domain error"); } else if (v1 == 1.0) { throw PythonOps.ZeroDivisionError("float division"); } else if (v1 == Double.PositiveInfinity) { return 0.0; } return Check(Math.Log(v0, v1)); } public static double log(BigInteger value) { if (value.Sign <= 0) { throw PythonOps.ValueError("math domain error"); } return value.Log(); } public static double log(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return log(val); } else { return log(Converter.ConvertToBigInteger(value)); } } public static double log(BigInteger value, double newBase) { if (newBase <= 0.0 || value <= 0) { throw PythonOps.ValueError("math domain error"); } else if (newBase == 1.0) { throw PythonOps.ZeroDivisionError("float division"); } else if (newBase == Double.PositiveInfinity) { return 0.0; } return Check(value.Log(newBase)); } public static double log(object value, double newBase) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return log(val, newBase); } else { return log(Converter.ConvertToBigInteger(value), newBase); } } public static double log10(double v0) { if (v0 <= 0.0) { throw PythonOps.ValueError("math domain error"); } return Check(v0, Math.Log10(v0)); } public static double log10(BigInteger value) { if (value.Sign <= 0) { throw PythonOps.ValueError("math domain error"); } return value.Log10(); } public static double log10(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return log10(val); } else { return log10(Converter.ConvertToBigInteger(value)); } } public static double log1p(double v0) { // Calculate log(1.0 + v0) using William Kahan's algorithm for numerical precision if (double.IsPositiveInfinity(v0)) { return double.PositiveInfinity; } double v1 = v0 + 1.0; // Linear approximation for very small v0 if (v1 == 1.0) { return v0; } // Apply correction factor return log(v1) * v0 / (v1 - 1.0); } public static double log1p(BigInteger value) { return log(value + BigInteger.One); } public static double log1p(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return log1p(val); } else { return log1p(Converter.ConvertToBigInteger(value)); } } public static double expm1(double v0) { return Check(v0, Math.Tanh(v0 / 2.0) * (Math.Exp(v0) + 1.0)); } public static double asinh(double v0) { if (v0 == 0.0 || double.IsInfinity(v0)) { return v0; } // rewrote ln(v0 + sqrt(v0**2 + 1)) for precision if (Math.Abs(v0) > 1.0) { return Math.Sign(v0)*(Math.Log(Math.Abs(v0)) + Math.Log(1.0 + MathUtils.Hypot(1.0, 1.0 / v0))); } else { return Math.Log(v0 + MathUtils.Hypot(1.0, v0)); } } public static double asinh(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return asinh(val); } else { return asinh(Converter.ConvertToBigInteger(value)); } } public static double acosh(double v0) { if (v0 < 1.0) { throw PythonOps.ValueError("math domain error"); } else if (double.IsPositiveInfinity(v0)) { return double.PositiveInfinity; } // rewrote ln(v0 + sqrt(v0**2 - 1)) for precision double c = Math.Sqrt(v0 + 1.0); return Math.Log(c) + Math.Log(v0 / c + Math.Sqrt(v0 - 1.0)); } public static double acosh(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return acosh(val); } else { return acosh(Converter.ConvertToBigInteger(value)); } } public static double atanh(double v0) { if (v0 >= 1.0 || v0 <= -1.0) { throw PythonOps.ValueError("math domain error"); } else if (v0 == 0.0) { // preserve +/-0.0 return v0; } return Math.Log((1.0 + v0) / (1.0 - v0)) * 0.5; } public static double atanh(BigInteger value) { if (value == 0) { return 0; } else { throw PythonOps.ValueError("math domain error"); } } public static double atanh(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return atanh(val); } else { return atanh(Converter.ConvertToBigInteger(value)); } } public static double atan2(double v0, double v1) { if (double.IsNaN(v0) || double.IsNaN(v1)) { return double.NaN; } else if (double.IsInfinity(v0)) { if (double.IsPositiveInfinity(v1)) { return pi * 0.25 * Math.Sign(v0); } else if (double.IsNegativeInfinity(v1)) { return pi * 0.75 * Math.Sign(v0); } else { return pi * 0.5 * Math.Sign(v0); } } else if (double.IsInfinity(v1)) { return v1 > 0.0 ? 0.0 : pi * DoubleOps.Sign(v0); } return Math.Atan2(v0, v1); } /// <summary> /// Error function on real values /// </summary> public static double erf(double v0) { return MathUtils.Erf(v0); } /// <summary> /// Complementary error function on real values: erfc(x) = 1 - erf(x) /// </summary> public static double erfc(double v0) { return MathUtils.ErfComplement(v0); } public static object factorial(double v0) { if (v0 % 1.0 != 0.0) { throw PythonOps.ValueError("factorial() only accepts integral values"); } if (v0 < 0.0) { throw PythonOps.ValueError("factorial() not defined for negative values"); } BigInteger val = 1; for (BigInteger mul = (BigInteger)v0; mul > BigInteger.One; mul -= BigInteger.One) { val *= mul; } if (val > SysModule.maxint) { return val; } return (int)val; } public static object factorial(BigInteger value) { if (value < 0) { throw PythonOps.ValueError("factorial() not defined for negative values"); } BigInteger val = 1; for (BigInteger mul = value; mul > BigInteger.One; mul -= BigInteger.One) { val *= mul; } if (val > SysModule.maxint) { return val; } return (int)val; } public static object factorial(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return factorial(val); } else { return factorial(Converter.ConvertToBigInteger(value)); } } /// <summary> /// Gamma function on real values /// </summary> public static double gamma(double v0) { return Check(v0, MathUtils.Gamma(v0)); } /// <summary> /// Natural log of absolute value of Gamma function /// </summary> public static double lgamma(double v0) { return Check(v0, MathUtils.LogGamma(v0)); } public static object trunc(CodeContext/*!*/ context, object value) { object func; if (PythonOps.TryGetBoundAttr(value, "__trunc__", out func)) { return PythonOps.CallWithContext(context, func); } else { throw PythonOps.AttributeError("__trunc__"); } } public static bool isinf(double v0) { return double.IsInfinity(v0); } public static bool isinf(BigInteger value) { return false; } public static bool isinf(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return isinf(val); } return false; } public static bool isnan(double v0) { return double.IsNaN(v0); } public static bool isnan(BigInteger value) { return false; } public static bool isnan(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return isnan(val); } return false; } public static double copysign(double x, double y) { return DoubleOps.CopySign(x, y); } public static double copysign(object x, object y) { double val, sign; if (!Converter.TryConvertToDouble(x, out val) || !Converter.TryConvertToDouble(y, out sign)) { throw PythonOps.TypeError("TypeError: a float is required"); } return DoubleOps.CopySign(val, sign); } #region Private Implementation Details private static void SetExponentLe(byte[] v, int exp) { exp += Bias; ushort oldExp = LdExponentLe(v); ushort newExp = (ushort)(oldExp & 0x800f | (exp << 4)); StExponentLe(v, newExp); } private static int IntExponentLe(byte[] v) { ushort exp = LdExponentLe(v); return ((int)((exp & 0x7FF0) >> 4) - Bias); } private static ushort LdExponentLe(byte[] v) { return (ushort)(v[6] | ((ushort)v[7] << 8)); } private static long LdMantissaLe(byte[] v) { int i1 = (v[0] | (v[1] << 8) | (v[2] << 16) | (v[3] << 24)); int i2 = (v[4] | (v[5] << 8) | ((v[6] & 0xF) << 16)); return i1 | (i2 << 32); } private static void StExponentLe(byte[] v, ushort e) { v[6] = (byte)e; v[7] = (byte)(e >> 8); } private static bool IsDenormalizedLe(byte[] v) { ushort exp = LdExponentLe(v); long man = LdMantissaLe(v); return ((exp & 0x7FF0) == 0 && (man != 0)); } private static void DecomposeLe(byte[] v, out double m, out int e) { if (IsDenormalizedLe(v)) { m = BitConverter.ToDouble(v, 0); m *= Math.Pow(2.0, 1022); v = BitConverter.GetBytes(m); e = IntExponentLe(v) - 1022; } else { e = IntExponentLe(v); } SetExponentLe(v, 0); m = BitConverter.ToDouble(v, 0); } private static double Check(double v) { return PythonOps.CheckMath(v); } private static double Check(double input, double output) { return PythonOps.CheckMath(input, output); } private static double Check(double in0, double in1, double output) { return PythonOps.CheckMath(in0, in1, output); } #endregion } }
slozier/ironpython2
Src/IronPython.Modules/math.cs
C#
apache-2.0
19,692
package org.jrivets.transaction; /** * The interface defines an action which can be executed in * {@link SimpleTransaction} context. * * @author Dmitry Spasibenko * */ public interface Action { /** * Executes the action itself. In case of fail should throw an exception * * @throws Throwable * describes the fail cause */ void doAction() throws Throwable; /** * Rolls back the action executed by <tt>doAction()</tt>. It will be invoked * ONLY if the action method <tt>doAction()</tt> for the object has been * executed successfully (did not throw an exception). The cause of calling * this method can be one of the following: an action after this one is * failed or transaction was cancelled explicitly ( * <tt>SimpleTransaction.cancel()</tt> method is called). */ void rollbackAction(); }
obattalov/jrivets-common
src/main/java/org/jrivets/transaction/Action.java
Java
apache-2.0
891
/* * 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.wicket.security.examples.pages; import org.apache.wicket.IPageMap; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.model.IModel; /** * Base page for all pages that do not require a login. * * @author marrink * */ public class MyUnSecurePage extends WebPage { private static final long serialVersionUID = 1L; /** * */ public MyUnSecurePage() { } /** * @param model */ public MyUnSecurePage(IModel< ? > model) { super(model); } /** * @param pageMap */ public MyUnSecurePage(IPageMap pageMap) { super(pageMap); } /** * @param parameters */ public MyUnSecurePage(PageParameters parameters) { super(parameters); } /** * @param pageMap * @param model */ public MyUnSecurePage(IPageMap pageMap, IModel< ? > model) { super(pageMap, model); } }
duesenklipper/wicket-security-1.4
examples/all_in_one/src/main/java/org/apache/wicket/security/examples/pages/MyUnSecurePage.java
Java
apache-2.0
1,765
/* * Copyright 2019, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.admin.model; import io.fabric8.kubernetes.api.model.HasMetadata; import java.util.List; import java.util.Map; public interface AddressSpacePlan extends HasMetadata { Map<String, Double> getResourceLimits(); List<String> getAddressPlans(); String getShortDescription(); String getDisplayName(); int getDisplayOrder(); String getAddressSpaceType(); String getInfraConfigRef(); }
EnMasseProject/enmasse
api-model/src/main/java/io/enmasse/admin/model/AddressSpacePlan.java
Java
apache-2.0
572
################################################################################ # Copyright (c) 2015-2019 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://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. # # SPDX-License-Identifier: Apache-2.0 ################################################################################ from .progressbar import ProgressBar import requests import math import os import hashlib def download(url, file_name): r = requests.get(url, stream=True) file_size = int(r.headers['Content-length']) ''' if py3: file_size = int(u.getheader("Content-Length")[0]) else: file_size = int(u.info().getheaders("Content-Length")[0]) ''' file_exists = False if os.path.isfile(file_name): local_file_size = os.path.getsize(file_name) if local_file_size == file_size: sha1_file = file_name + '.sha1' if os.path.isfile(sha1_file): print('sha1 found') with open(sha1_file) as f: expected_sha1 = f.read() BLOCKSIZE = 65536 sha1 = hashlib.sha1() with open(file_name) as f: buff = f.read(BLOCKSIZE) while len(buff) > 0: sha1.update(buff) buff = f.read(BLOCKSIZE) if expected_sha1 == sha1: file_exists = True else: print("File corrupt. Downloading again.") os.remove(file_name) else: file_exists = True else: print("File corrupt. Downloading again.") os.remove(file_name) if not file_exists: factor = int(math.floor(math.log(file_size) / math.log(1024))) display_file_size = str(file_size / 1024 ** factor) + \ ['B', 'KB', 'MB', 'GB', 'TB', 'PB'][factor] print("Source: " + url) print("Destination " + file_name) print("Size: " + display_file_size) file_size_dl = 0 block_sz = 8192 f = open(file_name, 'wb') pbar = ProgressBar(file_size) for chunk in r.iter_content(chunk_size=block_sz): if not chunk: continue chunk_size = len(chunk) file_size_dl += chunk_size f.write(chunk) pbar.update(chunk_size) # status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) # status = status + chr(8)*(len(status)+1) # print(status) f.close() else: print("File already exists - " + file_name) return True
RobAltena/deeplearning4j
pydl4j/pydl4j/downloader.py
Python
apache-2.0
3,179
package org.carlspring.strongbox.xml.parsers; import org.carlspring.strongbox.url.ClasspathURLStreamHandler; import org.carlspring.strongbox.url.ClasspathURLStreamHandlerFactory; import org.carlspring.strongbox.xml.CustomTagService; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.*; import java.net.URL; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author mtodorov */ public class GenericParser<T> { public final static boolean IS_OUTPUT_FORMATTED = true; private static final Logger logger = LoggerFactory.getLogger(GenericParser.class); private ReentrantLock lock = new ReentrantLock(); private Set<Class> classes = new LinkedHashSet<>(); private JAXBContext context; static { final ClasspathURLStreamHandler handler = new ClasspathURLStreamHandler(ClassLoader.getSystemClassLoader()); ClasspathURLStreamHandlerFactory factory = new ClasspathURLStreamHandlerFactory("classpath", handler); try { URL.setURLStreamHandlerFactory(factory); } catch (Error e) { // You can safely disregard this, as a second attempt to register a an already // registered URLStreamHandlerFactory will throw an error. Since there's no // apparent way to check if it's registered, just catch and ignore the error. } } public GenericParser() { this.classes.addAll(CustomTagService.getInstance().getImplementations()); } public GenericParser(boolean useServiceLoader) { if (useServiceLoader) { this.classes.addAll(CustomTagService.getInstance().getImplementations()); } } public GenericParser(boolean useServiceLoader, Class... classes) { Collections.addAll(this.classes, classes); if (useServiceLoader) { this.classes.addAll(CustomTagService.getInstance().getImplementations()); } } public GenericParser(Class... classes) { Collections.addAll(this.classes, classes); this.classes.addAll(CustomTagService.getInstance().getImplementations()); } public T parse(File file) throws JAXBException, IOException { T object = null; try (FileInputStream is = new FileInputStream(file)) { object = parse(is); } return object; } public T parse(URL url) throws IOException, JAXBException { try (InputStream is = url.openStream()) { return parse(is); } } public T parse(InputStream is) throws JAXBException { T object = null; try { lock.lock(); Unmarshaller unmarshaller = getContext().createUnmarshaller(); //noinspection unchecked object = (T) unmarshaller.unmarshal(is); } finally { lock.unlock(); } return object; } public void store(T object, String path) throws JAXBException, IOException { store(object, new File(path).getAbsoluteFile()); } public void store(T object, File file) throws JAXBException, IOException { try (FileOutputStream os = new FileOutputStream(file)) { store(object, os); } } public void store(T object, OutputStream os) throws JAXBException { try { lock.lock(); JAXBContext context = getContext(); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, IS_OUTPUT_FORMATTED); marshaller.marshal(object, os); } finally { lock.unlock(); } } /** * Serialize #object to String using JAXB marshaller. * * @param object the object to be serialized * @return String representation of object */ public String serialize(T object) throws JAXBException { StringWriter writer = new StringWriter(); try { lock.lock(); JAXBContext context = getContext(); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, IS_OUTPUT_FORMATTED); marshaller.marshal(object, writer); return writer.getBuffer().toString(); } finally { lock.unlock(); } } @SuppressWarnings("unchecked") public T deserialize(String input) throws JAXBException { try { lock.lock(); JAXBContext context = getContext(); Unmarshaller m = context.createUnmarshaller(); return (T) m.unmarshal(new StringReader(input)); } finally { lock.unlock(); } } public void setContext(Class<?> classType) throws JAXBException { context = JAXBContext.newInstance(classType); } public JAXBContext getContext() throws JAXBException { if (context == null) { try { context = JAXBContext.newInstance(classes.toArray(new Class[classes.size()])); } catch (Exception e) { logger.error(e.getMessage(), e); return null; } } return context; } }
AlexOreshkevich/strongbox
strongbox-configuration/src/main/java/org/carlspring/strongbox/xml/parsers/GenericParser.java
Java
apache-2.0
5,887
var zkUtil = require('../util'); var zkConstants = require('../constants'); var ZK = require('zookeeper').ZooKeeper; /** * @constructor * encapsulate the lock algorithm. I didn't want it exposed in the client. * @param {ZkClient} client client doing the locking. * @param {String} node name of lock. * @param {Function} callback gets executed when the lock is acquired or reaches an error. expects (error). */ function LockAlgorithm(client, node, callback) { this.client = client; this.node = node; this.callback = callback; } /** * given a sorted list of child paths, finds the one that precedes myPath. * @param {Array} children list of children nodes. * @param {String} myPath path to compare against. * @return {String} valid child path (doesn't contain parent) or null if none exists. */ LockAlgorithm.prototype.pathBeforeMe = function(children, myPath) { var i; for (i = 0; i < children.length - 1; i++) { if (children[i + 1] === myPath) { return children[i]; } } return null; }; /** * checks for the presence of path. it doesn't exist, it gets created. * @param {String} path node to ensure existence of. * @param {Function} callback expects (error, pathName). */ LockAlgorithm.prototype.ensureNode = function(path, callback) { var self = this; this.client.createPaths(path, 'lock node', 0, function(err, pathCreated) { if (err) { callback(err); return; } self.client.options.log.tracef('successful parent node creation: ${path}', {'path': pathCreated}); // assert path === pathCreated callback(null, pathCreated); }); }; /** * creates an child node. * @param {String} path ephemeral child node (specified by path). * @param {String} txnId The transaction ID. * @param {Function} callback expects (error, pathName). */ LockAlgorithm.prototype.createChild = function(path, txnId, callback) { var self = this, lockValue = JSON.stringify([txnId, Date.now()]); self.client.create(path, lockValue, ZK.ZOO_SEQUENCE | ZK.ZOO_EPHEMERAL, function(err, pathCreated) { if (err) { self.client.options.log.error('node creation error', {err: err, pathCreated: pathCreated}); callback(err); return; } // assert pathCreated === path. callback(null, pathCreated); }); }; /** * gets children of a particular node. errors if there are no children. * @param {String} path the parent of the children. * @param {Function} callback expects (error, sorted list of children). the children are not full paths, but names only. */ LockAlgorithm.prototype.getSortedChildren = function(path, callback) { // false because we don't want to watch. this.client._getChildren(path, false, '', function(err, children) { if (err) { callback(err); return; } if (children.length < 1) { // there should *always* be children since this method always gets called after the lock node is created. callback(new Error('Could not create lock node for ' + path), null); return; } children.sort(function(a, b) { // each child name is formatted like this: lock-00000000. so peel of chars before creating a number. return parseInt(a.substr(zkConstants.LOCK_PREFIX.length), 10) - parseInt(b.substr(zkConstants.LOCK_PREFIX.length), 10); }); callback(null, children); }); }; /** * watches watchPath for deletion. parentPath is roughly equal to the name of the lock, lockPath is the child node * name for the lock that is to be acquired (e.g. '/this_lock/-lock000000121'). * it is perfectly reasonable for this watch to execute without executing a callback (in the event we need to wait * for watchPath to be deleted). * @param {String} parentPath basically the name of the lock (which is the parent node). * @param {String} lockPath child lock that is basically a place in line. * @param {String} watchPath the child node that we are waiting on to go away. when that happens it is our turn (we * have the lock). * @param {Function} callback expects (error). only purposes is to catch and report problems. */ LockAlgorithm.prototype.watch = function(parentPath, lockPath, watchPath, callback) { var self = this; self.client.options.log.trace1('watching: ' + watchPath); self.client._exists(watchPath, true, function(err, exists) { self.client.options.log.trace('exists', {err: err, exists: exists}); if (err) { callback(err); return; } if (!exists) { self.lockAlgorithm(parentPath, lockPath); return; } // wait for it to be deleted, then execute the callback. if (self.client.waitCallbacks[watchPath]) { callback(new Error('Already waiting on ' + watchPath)); return; } // set a callback that gets invoked when watchPath is deleted. self.client.waitCallbacks[watchPath] = function() { self.client.options.log.trace('Invoked wait callback'); self.lockAlgorithm(parentPath, lockPath); }; }); }; /** * implements the lock algorithm. * @param {String} parentPath a decorated form of the lock name. * @param {String} lockPath a child of parentPath. */ LockAlgorithm.prototype.lockAlgorithm = function(parentPath, lockPath) { var self = this, absolutePath; self.getSortedChildren(parentPath, function(err, children) { if (err) { self.callback(err); } else { //log.trace1('PARENT:%s, LOCK:%s, CHILDREN: %j', parentPath, lockPath, children); if (zkUtil.lte(zkUtil.last(lockPath), children[0])) { // we've got the lock!!!! self.client.options.log.tracef('lock acquired on ${parentPath} by ${lockPath}', {parentPath: parentPath, lockPath: lockPath}); self.client.locks[self.node] = lockPath; self.callback(null); } else { // watch the child path immediately preceeding lockPath. When it is deleted or no longer exists, // this process owns the lock. absolutePath = parentPath + '/' + self.pathBeforeMe(children, zkUtil.last(lockPath)); self.watch(parentPath, lockPath, absolutePath, function(err) { if (err) { self.callback(err); } // else, a watch was set. }); } } }); }; /** LockAlgorithm */ exports.LockAlgorithm = LockAlgorithm;
racker/service-registry
node_modules/zookeeper-client/lib/algorithms/lock.js
JavaScript
apache-2.0
6,297
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config'; interface Blob {} declare class IoT1ClickProjects extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: IoT1ClickProjects.Types.ClientConfiguration) config: Config & IoT1ClickProjects.Types.ClientConfiguration; /** * Associates a physical device with a placement. */ associateDeviceWithPlacement(params: IoT1ClickProjects.Types.AssociateDeviceWithPlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.AssociateDeviceWithPlacementResponse) => void): Request<IoT1ClickProjects.Types.AssociateDeviceWithPlacementResponse, AWSError>; /** * Associates a physical device with a placement. */ associateDeviceWithPlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.AssociateDeviceWithPlacementResponse) => void): Request<IoT1ClickProjects.Types.AssociateDeviceWithPlacementResponse, AWSError>; /** * Creates an empty placement. */ createPlacement(params: IoT1ClickProjects.Types.CreatePlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.CreatePlacementResponse) => void): Request<IoT1ClickProjects.Types.CreatePlacementResponse, AWSError>; /** * Creates an empty placement. */ createPlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.CreatePlacementResponse) => void): Request<IoT1ClickProjects.Types.CreatePlacementResponse, AWSError>; /** * Creates an empty project with a placement template. A project contains zero or more placements that adhere to the placement template defined in the project. */ createProject(params: IoT1ClickProjects.Types.CreateProjectRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.CreateProjectResponse) => void): Request<IoT1ClickProjects.Types.CreateProjectResponse, AWSError>; /** * Creates an empty project with a placement template. A project contains zero or more placements that adhere to the placement template defined in the project. */ createProject(callback?: (err: AWSError, data: IoT1ClickProjects.Types.CreateProjectResponse) => void): Request<IoT1ClickProjects.Types.CreateProjectResponse, AWSError>; /** * Deletes a placement. To delete a placement, it must not have any devices associated with it. When you delete a placement, all associated data becomes irretrievable. */ deletePlacement(params: IoT1ClickProjects.Types.DeletePlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DeletePlacementResponse) => void): Request<IoT1ClickProjects.Types.DeletePlacementResponse, AWSError>; /** * Deletes a placement. To delete a placement, it must not have any devices associated with it. When you delete a placement, all associated data becomes irretrievable. */ deletePlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DeletePlacementResponse) => void): Request<IoT1ClickProjects.Types.DeletePlacementResponse, AWSError>; /** * Deletes a project. To delete a project, it must not have any placements associated with it. When you delete a project, all associated data becomes irretrievable. */ deleteProject(params: IoT1ClickProjects.Types.DeleteProjectRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DeleteProjectResponse) => void): Request<IoT1ClickProjects.Types.DeleteProjectResponse, AWSError>; /** * Deletes a project. To delete a project, it must not have any placements associated with it. When you delete a project, all associated data becomes irretrievable. */ deleteProject(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DeleteProjectResponse) => void): Request<IoT1ClickProjects.Types.DeleteProjectResponse, AWSError>; /** * Describes a placement in a project. */ describePlacement(params: IoT1ClickProjects.Types.DescribePlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DescribePlacementResponse) => void): Request<IoT1ClickProjects.Types.DescribePlacementResponse, AWSError>; /** * Describes a placement in a project. */ describePlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DescribePlacementResponse) => void): Request<IoT1ClickProjects.Types.DescribePlacementResponse, AWSError>; /** * Returns an object describing a project. */ describeProject(params: IoT1ClickProjects.Types.DescribeProjectRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DescribeProjectResponse) => void): Request<IoT1ClickProjects.Types.DescribeProjectResponse, AWSError>; /** * Returns an object describing a project. */ describeProject(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DescribeProjectResponse) => void): Request<IoT1ClickProjects.Types.DescribeProjectResponse, AWSError>; /** * Removes a physical device from a placement. */ disassociateDeviceFromPlacement(params: IoT1ClickProjects.Types.DisassociateDeviceFromPlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DisassociateDeviceFromPlacementResponse) => void): Request<IoT1ClickProjects.Types.DisassociateDeviceFromPlacementResponse, AWSError>; /** * Removes a physical device from a placement. */ disassociateDeviceFromPlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DisassociateDeviceFromPlacementResponse) => void): Request<IoT1ClickProjects.Types.DisassociateDeviceFromPlacementResponse, AWSError>; /** * Returns an object enumerating the devices in a placement. */ getDevicesInPlacement(params: IoT1ClickProjects.Types.GetDevicesInPlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.GetDevicesInPlacementResponse) => void): Request<IoT1ClickProjects.Types.GetDevicesInPlacementResponse, AWSError>; /** * Returns an object enumerating the devices in a placement. */ getDevicesInPlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.GetDevicesInPlacementResponse) => void): Request<IoT1ClickProjects.Types.GetDevicesInPlacementResponse, AWSError>; /** * Lists the placement(s) of a project. */ listPlacements(params: IoT1ClickProjects.Types.ListPlacementsRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListPlacementsResponse) => void): Request<IoT1ClickProjects.Types.ListPlacementsResponse, AWSError>; /** * Lists the placement(s) of a project. */ listPlacements(callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListPlacementsResponse) => void): Request<IoT1ClickProjects.Types.ListPlacementsResponse, AWSError>; /** * Lists the AWS IoT 1-Click project(s) associated with your AWS account and region. */ listProjects(params: IoT1ClickProjects.Types.ListProjectsRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListProjectsResponse) => void): Request<IoT1ClickProjects.Types.ListProjectsResponse, AWSError>; /** * Lists the AWS IoT 1-Click project(s) associated with your AWS account and region. */ listProjects(callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListProjectsResponse) => void): Request<IoT1ClickProjects.Types.ListProjectsResponse, AWSError>; /** * Updates a placement with the given attributes. To clear an attribute, pass an empty value (i.e., ""). */ updatePlacement(params: IoT1ClickProjects.Types.UpdatePlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.UpdatePlacementResponse) => void): Request<IoT1ClickProjects.Types.UpdatePlacementResponse, AWSError>; /** * Updates a placement with the given attributes. To clear an attribute, pass an empty value (i.e., ""). */ updatePlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.UpdatePlacementResponse) => void): Request<IoT1ClickProjects.Types.UpdatePlacementResponse, AWSError>; /** * Updates a project associated with your AWS account and region. With the exception of device template names, you can pass just the values that need to be updated because the update request will change only the values that are provided. To clear a value, pass the empty string (i.e., ""). */ updateProject(params: IoT1ClickProjects.Types.UpdateProjectRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.UpdateProjectResponse) => void): Request<IoT1ClickProjects.Types.UpdateProjectResponse, AWSError>; /** * Updates a project associated with your AWS account and region. With the exception of device template names, you can pass just the values that need to be updated because the update request will change only the values that are provided. To clear a value, pass the empty string (i.e., ""). */ updateProject(callback?: (err: AWSError, data: IoT1ClickProjects.Types.UpdateProjectResponse) => void): Request<IoT1ClickProjects.Types.UpdateProjectResponse, AWSError>; } declare namespace IoT1ClickProjects { export interface AssociateDeviceWithPlacementRequest { /** * The name of the project containing the placement in which to associate the device. */ projectName: ProjectName; /** * The name of the placement in which to associate the device. */ placementName: PlacementName; /** * The ID of the physical device to be associated with the given placement in the project. Note that a mandatory 4 character prefix is required for all deviceId values. */ deviceId: DeviceId; /** * The device template name to associate with the device ID. */ deviceTemplateName: DeviceTemplateName; } export interface AssociateDeviceWithPlacementResponse { } export type AttributeDefaultValue = string; export type AttributeName = string; export type AttributeValue = string; export interface CreatePlacementRequest { /** * The name of the placement to be created. */ placementName: PlacementName; /** * The name of the project in which to create the placement. */ projectName: ProjectName; /** * Optional user-defined key/value pairs providing contextual data (such as location or function) for the placement. */ attributes?: PlacementAttributeMap; } export interface CreatePlacementResponse { } export interface CreateProjectRequest { /** * The name of the project to create. */ projectName: ProjectName; /** * An optional description for the project. */ description?: Description; /** * The schema defining the placement to be created. A placement template defines placement default attributes and device templates. You cannot add or remove device templates after the project has been created. However, you can update callbackOverrides for the device templates using the UpdateProject API. */ placementTemplate?: PlacementTemplate; } export interface CreateProjectResponse { } export type DefaultPlacementAttributeMap = {[key: string]: AttributeDefaultValue}; export interface DeletePlacementRequest { /** * The name of the empty placement to delete. */ placementName: PlacementName; /** * The project containing the empty placement to delete. */ projectName: ProjectName; } export interface DeletePlacementResponse { } export interface DeleteProjectRequest { /** * The name of the empty project to delete. */ projectName: ProjectName; } export interface DeleteProjectResponse { } export interface DescribePlacementRequest { /** * The name of the placement within a project. */ placementName: PlacementName; /** * The project containing the placement to be described. */ projectName: ProjectName; } export interface DescribePlacementResponse { /** * An object describing the placement. */ placement: PlacementDescription; } export interface DescribeProjectRequest { /** * The name of the project to be described. */ projectName: ProjectName; } export interface DescribeProjectResponse { /** * An object describing the project. */ project: ProjectDescription; } export type Description = string; export type DeviceCallbackKey = string; export type DeviceCallbackOverrideMap = {[key: string]: DeviceCallbackValue}; export type DeviceCallbackValue = string; export type DeviceId = string; export type DeviceMap = {[key: string]: DeviceId}; export interface DeviceTemplate { /** * The device type, which currently must be "button". */ deviceType?: DeviceType; /** * An optional Lambda function to invoke instead of the default Lambda function provided by the placement template. */ callbackOverrides?: DeviceCallbackOverrideMap; } export type DeviceTemplateMap = {[key: string]: DeviceTemplate}; export type DeviceTemplateName = string; export type DeviceType = string; export interface DisassociateDeviceFromPlacementRequest { /** * The name of the project that contains the placement. */ projectName: ProjectName; /** * The name of the placement that the device should be removed from. */ placementName: PlacementName; /** * The device ID that should be removed from the placement. */ deviceTemplateName: DeviceTemplateName; } export interface DisassociateDeviceFromPlacementResponse { } export interface GetDevicesInPlacementRequest { /** * The name of the project containing the placement. */ projectName: ProjectName; /** * The name of the placement to get the devices from. */ placementName: PlacementName; } export interface GetDevicesInPlacementResponse { /** * An object containing the devices (zero or more) within the placement. */ devices: DeviceMap; } export interface ListPlacementsRequest { /** * The project containing the placements to be listed. */ projectName: ProjectName; /** * The token to retrieve the next set of results. */ nextToken?: NextToken; /** * The maximum number of results to return per request. If not set, a default value of 100 is used. */ maxResults?: MaxResults; } export interface ListPlacementsResponse { /** * An object listing the requested placements. */ placements: PlacementSummaryList; /** * The token used to retrieve the next set of results - will be effectively empty if there are no further results. */ nextToken?: NextToken; } export interface ListProjectsRequest { /** * The token to retrieve the next set of results. */ nextToken?: NextToken; /** * The maximum number of results to return per request. If not set, a default value of 100 is used. */ maxResults?: MaxResults; } export interface ListProjectsResponse { /** * An object containing the list of projects. */ projects: ProjectSummaryList; /** * The token used to retrieve the next set of results - will be effectively empty if there are no further results. */ nextToken?: NextToken; } export type MaxResults = number; export type NextToken = string; export type PlacementAttributeMap = {[key: string]: AttributeValue}; export interface PlacementDescription { /** * The name of the project containing the placement. */ projectName: ProjectName; /** * The name of the placement. */ placementName: PlacementName; /** * The user-defined attributes associated with the placement. */ attributes: PlacementAttributeMap; /** * The date when the placement was initially created, in UNIX epoch time format. */ createdDate: Time; /** * The date when the placement was last updated, in UNIX epoch time format. If the placement was not updated, then createdDate and updatedDate are the same. */ updatedDate: Time; } export type PlacementName = string; export interface PlacementSummary { /** * The name of the project containing the placement. */ projectName: ProjectName; /** * The name of the placement being summarized. */ placementName: PlacementName; /** * The date when the placement was originally created, in UNIX epoch time format. */ createdDate: Time; /** * The date when the placement was last updated, in UNIX epoch time format. If the placement was not updated, then createdDate and updatedDate are the same. */ updatedDate: Time; } export type PlacementSummaryList = PlacementSummary[]; export interface PlacementTemplate { /** * The default attributes (key/value pairs) to be applied to all placements using this template. */ defaultAttributes?: DefaultPlacementAttributeMap; /** * An object specifying the DeviceTemplate for all placements using this (PlacementTemplate) template. */ deviceTemplates?: DeviceTemplateMap; } export interface ProjectDescription { /** * The name of the project for which to obtain information from. */ projectName: ProjectName; /** * The description of the project. */ description?: Description; /** * The date when the project was originally created, in UNIX epoch time format. */ createdDate: Time; /** * The date when the project was last updated, in UNIX epoch time format. If the project was not updated, then createdDate and updatedDate are the same. */ updatedDate: Time; /** * An object describing the project's placement specifications. */ placementTemplate?: PlacementTemplate; } export type ProjectName = string; export interface ProjectSummary { /** * The name of the project being summarized. */ projectName: ProjectName; /** * The date when the project was originally created, in UNIX epoch time format. */ createdDate: Time; /** * The date when the project was last updated, in UNIX epoch time format. If the project was not updated, then createdDate and updatedDate are the same. */ updatedDate: Time; } export type ProjectSummaryList = ProjectSummary[]; export type Time = Date; export interface UpdatePlacementRequest { /** * The name of the placement to update. */ placementName: PlacementName; /** * The name of the project containing the placement to be updated. */ projectName: ProjectName; /** * The user-defined object of attributes used to update the placement. The maximum number of key/value pairs is 50. */ attributes?: PlacementAttributeMap; } export interface UpdatePlacementResponse { } export interface UpdateProjectRequest { /** * The name of the project to be updated. */ projectName: ProjectName; /** * An optional user-defined description for the project. */ description?: Description; /** * An object defining the project update. Once a project has been created, you cannot add device template names to the project. However, for a given placementTemplate, you can update the associated callbackOverrides for the device definition using this API. */ placementTemplate?: PlacementTemplate; } export interface UpdateProjectResponse { } /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2018-05-14"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the IoT1ClickProjects client. */ export import Types = IoT1ClickProjects; } export = IoT1ClickProjects;
chrisradek/aws-sdk-js
clients/iot1clickprojects.d.ts
TypeScript
apache-2.0
20,275
using System.Collections.Generic; using System.Globalization; using System.Linq; using soothsayer.Infrastructure; using soothsayer.Infrastructure.IO; using soothsayer.Migrations; using soothsayer.Scanners; using soothsayer.Scripts; namespace soothsayer { public class OracleMigrator : IMigrator { private readonly IConnectionFactory _connectionFactory; private readonly IVersionRespositoryFactory _versionRespositoryFactory; private readonly IAppliedScriptsRepositoryFactory _appliedScriptsRepositoryFactory; private readonly IDatabaseMetadataProviderFactory _databaseMetadataProviderFactory; private readonly IScriptScannerFactory _scriptScannerFactory; private readonly IScriptRunnerFactory _scriptRunnerFactory; public OracleMigrator( IConnectionFactory connectionFactory, IVersionRespositoryFactory versionRespositoryFactory, IAppliedScriptsRepositoryFactory appliedScriptsRepositoryFactory, IDatabaseMetadataProviderFactory databaseMetadataProviderFactory, IScriptScannerFactory scriptScannerFactory, IScriptRunnerFactory scriptRunnerFactory) { _connectionFactory = connectionFactory; _versionRespositoryFactory = versionRespositoryFactory; _databaseMetadataProviderFactory = databaseMetadataProviderFactory; _scriptScannerFactory = scriptScannerFactory; _scriptRunnerFactory = scriptRunnerFactory; _appliedScriptsRepositoryFactory = appliedScriptsRepositoryFactory; } public void Migrate(DatabaseConnectionInfo databaseConnectionInfo, MigrationInfo migrationInfo) { using (var connection = _connectionFactory.Create(databaseConnectionInfo)) { Output.Text("Connected to oracle database on connection string '{0}'.".FormatWith(databaseConnectionInfo.ConnectionString)); Output.EmptyLine(); Output.Text("Checking for the current database version."); var oracleMetadataProvider = _databaseMetadataProviderFactory.Create(connection); var oracleVersioning = _versionRespositoryFactory.Create(connection); var oracleAppliedScriptsRepository = _appliedScriptsRepositoryFactory.Create(connection); var currentVersion = oracleMetadataProvider.SchemaExists(migrationInfo.TargetSchema) ? oracleVersioning.GetCurrentVersion(migrationInfo.TargetSchema) : null; Output.Info("The current database version is: {0}".FormatWith(currentVersion.IsNotNull() ? currentVersion.Version.ToString(CultureInfo.InvariantCulture) : "<empty>")); Output.EmptyLine(); Output.Info("Scanning input folder '{0}' for scripts...".FormatWith(migrationInfo.ScriptFolder)); var initScripts = ScanForScripts(migrationInfo, ScriptFolders.Init, _scriptScannerFactory.Create(ScriptFolders.Init)).ToArray(); var upScripts = ScanForScripts(migrationInfo, ScriptFolders.Up, _scriptScannerFactory.Create(ScriptFolders.Up)).ToArray(); var downScripts = ScanForScripts(migrationInfo, ScriptFolders.Down, _scriptScannerFactory.Create(ScriptFolders.Down)).ToArray(); var termScripts = ScanForScripts(migrationInfo, ScriptFolders.Term, _scriptScannerFactory.Create(ScriptFolders.Term)).ToArray(); Output.EmptyLine(); if (migrationInfo.TargetVersion.HasValue) { Output.Info("Target database version was provided, will target migrating the database to version {0}".FormatWith(migrationInfo.TargetVersion.Value)); } VerifyDownScripts(upScripts, downScripts); var storedMigrationSteps = new List<IStep>(); if (migrationInfo.UseStored) { Output.Info("--usestored was specified, fetching set of applied scripts stored in the target database...".FormatWith()); storedMigrationSteps = oracleAppliedScriptsRepository.GetAppliedScripts(migrationInfo.TargetSchema).ToList(); Output.Text(" {0} stored applied scripts found.".FormatWith(storedMigrationSteps.Count)); Output.EmptyLine(); } var scriptRunner = _scriptRunnerFactory.Create(databaseConnectionInfo); RunMigration(migrationInfo, currentVersion, initScripts, upScripts, downScripts, termScripts, storedMigrationSteps, scriptRunner, oracleMetadataProvider, oracleVersioning, oracleAppliedScriptsRepository); if (oracleMetadataProvider.SchemaExists(migrationInfo.TargetSchema)) { var newVersion = oracleVersioning.GetCurrentVersion(migrationInfo.TargetSchema); Output.Info("Database version is now: {0}".FormatWith(newVersion.IsNotNull() ? newVersion.Version.ToString(CultureInfo.InvariantCulture) : "<empty>")); } else { Output.Info("Target schema '{0}' no longer exists.".FormatWith(migrationInfo.TargetSchema)); } } } private static IEnumerable<Script> ScanForScripts(MigrationInfo migrationInfo, string migrationFolder, IScriptScanner scanner) { var environments = (migrationInfo.TargetEnvironment ?? Enumerable.Empty<string>()).ToArray(); var scripts = (scanner.Scan(migrationInfo.ScriptFolder.Whack(migrationFolder), environments) ?? Enumerable.Empty<Script>()).ToArray(); Output.Text("Found {0} '{1}' scripts.".FormatWith(scripts.Length, migrationFolder)); foreach (var script in scripts) { Output.Verbose(script.Name, 1); } return scripts; } private static void VerifyDownScripts(IEnumerable<Script> upScripts, IEnumerable<Script> downScripts) { var withoutRollback = upScripts.Where(u => downScripts.All(d => d.Version != u.Version)).ToArray(); if (withoutRollback.Any()) { Output.Warn("The following 'up' scripts do not have a corresponding 'down' script, any rollback may not work as expected:"); foreach (var script in withoutRollback) { Output.Warn(script.Name, 1); } Output.EmptyLine(); } } private static void RunMigration(MigrationInfo migrationInfo, DatabaseVersion currentVersion, IEnumerable<Script> initScripts, IEnumerable<Script> upScripts, IEnumerable<Script> downScripts, IEnumerable<Script> termScripts, IList<IStep> storedSteps, IScriptRunner scriptRunner, IDatabaseMetadataProvider databaseMetadataProvider, IVersionRespository versionRespository, IAppliedScriptsRepository appliedScriptsRepository) { var upDownSteps = upScripts.Select(u => new DatabaseStep(u, downScripts.FirstOrDefault(d => d.Version == u.Version))).ToList(); var initTermSteps = initScripts.Select(i => new DatabaseStep(i, termScripts.FirstOrDefault(t => t.Version == i.Version))).ToList(); if (migrationInfo.Direction == MigrationDirection.Down) { var downMigration = new DownMigration(databaseMetadataProvider, versionRespository, appliedScriptsRepository, migrationInfo.Forced); if (storedSteps.Any()) { Output.Warn("NOTE: Using stored applied scripts to perform downgrade instead of local 'down' scripts."); downMigration.Migrate(storedSteps, currentVersion, migrationInfo.TargetVersion, scriptRunner, migrationInfo.TargetSchema, migrationInfo.TargetTablespace); } else { downMigration.Migrate(upDownSteps, currentVersion, migrationInfo.TargetVersion, scriptRunner, migrationInfo.TargetSchema, migrationInfo.TargetTablespace); } if (!migrationInfo.TargetVersion.HasValue) { var termMigration = new TermMigration(databaseMetadataProvider, migrationInfo.Forced); termMigration.Migrate(initTermSteps, currentVersion, migrationInfo.TargetVersion, scriptRunner, migrationInfo.TargetSchema, migrationInfo.TargetTablespace); } else { Output.Info("A target version was provided, termination scripts will not be executed."); } } else { var initMigration = new InitMigration(databaseMetadataProvider, migrationInfo.Forced); initMigration.Migrate(initTermSteps, currentVersion, migrationInfo.TargetVersion, scriptRunner, migrationInfo.TargetSchema, migrationInfo.TargetTablespace); EnsureVersioningTableIsInitialised(versionRespository, migrationInfo.TargetSchema, migrationInfo.TargetTablespace); EnsureAppliedScriptsTableIsInitialised(appliedScriptsRepository, migrationInfo.TargetSchema, migrationInfo.TargetTablespace); var upMigration = new UpMigration(versionRespository, appliedScriptsRepository, migrationInfo.Forced); upMigration.Migrate(upDownSteps, currentVersion, migrationInfo.TargetVersion, scriptRunner, migrationInfo.TargetSchema, migrationInfo.TargetTablespace); } } private static void EnsureAppliedScriptsTableIsInitialised(IAppliedScriptsRepository appliedScriptsRepository, string targetSchema, string targetTablespace) { bool alreadyInitialised = appliedScriptsRepository.AppliedScriptsTableExists(targetSchema); if (!alreadyInitialised) { appliedScriptsRepository.InitialiseAppliedScriptsTable(targetSchema, targetTablespace); } } private static void EnsureVersioningTableIsInitialised(IVersionRespository versionRespository, string targetSchema, string targetTablespace) { bool alreadyInitialised = versionRespository.VersionTableExists(targetSchema); if (!alreadyInitialised) { versionRespository.InitialiseVersioningTable(targetSchema, targetTablespace); } } } }
paybyphone/soothsayer
soothsayer/OracleMigrator.cs
C#
apache-2.0
10,677
package org.apache.uima.casviewer.core.internal; import java.util.List; /** * A node that contains a list of AnnotationObject(s) * */ public class AnnotationObjectsNode { protected List<AnnotationObject> annotationList; public AnnotationObjectsNode () { } public AnnotationObjectsNode(List<AnnotationObject> list) { annotationList = list; } /** * @return the annotationList */ public List<AnnotationObject> getAnnotationList() { return annotationList; } /** * @param annotationList the annotationList to set */ public void setAnnotationList(List<AnnotationObject> list) { this.annotationList = list; } }
apache/uima-sandbox
CasViewerEclipsePlugin/uimaj-ep-casviewer-core/src/main/java/org/apache/uima/casviewer/core/internal/AnnotationObjectsNode.java
Java
apache-2.0
717
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.weld.injection.producer; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.security.AccessController; import java.security.PrivilegedActionException; import java.util.Set; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.event.Observes; import javax.enterprise.event.ObservesAsync; import javax.enterprise.inject.CreationException; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.spi.AnnotatedMember; import javax.enterprise.inject.spi.InjectionPoint; import javax.enterprise.inject.spi.Producer; import org.jboss.weld.annotated.enhanced.EnhancedAnnotatedMethod; import org.jboss.weld.bean.DisposalMethod; import org.jboss.weld.bean.SessionBean; import org.jboss.weld.exceptions.DefinitionException; import org.jboss.weld.injection.InjectionPointFactory; import org.jboss.weld.injection.MethodInjectionPoint; import org.jboss.weld.injection.MethodInjectionPoint.MethodInjectionPointType; import org.jboss.weld.logging.BeanLogger; import org.jboss.weld.security.GetMethodAction; import org.jboss.weld.util.reflection.Formats; import org.jboss.weld.util.reflection.Reflections; /** * {@link Producer} implementation for producer methods. * * @author Jozef Hartinger * */ public abstract class ProducerMethodProducer<X, T> extends AbstractMemberProducer<X, T> { private static final String PRODUCER_ANNOTATION = "@Produces"; // The underlying method private final MethodInjectionPoint<T, ? super X> method; public ProducerMethodProducer(EnhancedAnnotatedMethod<T, ? super X> enhancedAnnotatedMethod, DisposalMethod<?, ?> disposalMethod) { super(enhancedAnnotatedMethod, disposalMethod); // Note that for producer method injection points the declaring bean is the producer method itself this.method = InjectionPointFactory.instance().createMethodInjectionPoint(MethodInjectionPointType.PRODUCER, enhancedAnnotatedMethod, getBean(), enhancedAnnotatedMethod.getDeclaringType().getJavaClass(), null, getBeanManager()); checkProducerMethod(enhancedAnnotatedMethod); checkDelegateInjectionPoints(); } /** * Validates the producer method */ protected void checkProducerMethod(EnhancedAnnotatedMethod<T, ? super X> method) { if (method.getEnhancedParameters(Observes.class).size() > 0) { throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@Observes", this.method, Formats.formatAsStackTraceElement(method.getJavaMember())); } else if (method.getEnhancedParameters(ObservesAsync.class).size() > 0) { throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@ObservesAsync", this.method, Formats.formatAsStackTraceElement(method.getJavaMember())); } else if (method.getEnhancedParameters(Disposes.class).size() > 0) { throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@Disposes", this.method, Formats.formatAsStackTraceElement(method.getJavaMember())); } else if (getDeclaringBean() instanceof SessionBean<?> && !Modifier.isStatic(method.slim().getJavaMember().getModifiers())) { boolean methodDeclaredOnTypes = false; for (Type type : getDeclaringBean().getTypes()) { Class<?> clazz = Reflections.getRawType(type); try { AccessController.doPrivileged(new GetMethodAction(clazz, method.getName(), method.getParameterTypesAsArray())); methodDeclaredOnTypes = true; break; } catch (PrivilegedActionException ignored) { } } if (!methodDeclaredOnTypes) { throw BeanLogger.LOG.methodNotBusinessMethod("Producer", this, getDeclaringBean(), Formats.formatAsStackTraceElement(method.getJavaMember())); } } } @Override public Set<InjectionPoint> getInjectionPoints() { return method.getInjectionPoints(); } @Override protected T produce(Object receiver, CreationalContext<T> ctx) { return method.invoke(receiver, null, getBeanManager(), ctx, CreationException.class); } @Override public AnnotatedMember<? super X> getAnnotated() { return method.getAnnotated(); } @Override protected DefinitionException producerWithInvalidTypeVariable(AnnotatedMember<?> member) { return BeanLogger.LOG.producerMethodReturnTypeInvalidTypeVariable(member, Formats.formatAsStackTraceElement(member.getJavaMember())); } @Override protected DefinitionException producerWithInvalidWildcard(AnnotatedMember<?> member) { return BeanLogger.LOG.producerMethodCannotHaveAWildcardReturnType(member, Formats.formatAsStackTraceElement(member.getJavaMember())); } @Override protected DefinitionException producerWithParameterizedTypeWithTypeVariableBeanTypeMustBeDependent(AnnotatedMember<?> member) { return BeanLogger.LOG.producerMethodWithTypeVariableReturnTypeMustBeDependent(member, Formats.formatAsStackTraceElement(member.getJavaMember())); } }
antoinesd/weld-core
impl/src/main/java/org/jboss/weld/injection/producer/ProducerMethodProducer.java
Java
apache-2.0
5,998
package controllers; import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient; import play.shaded.ahc.org.asynchttpclient.BoundRequestBuilder; import play.shaded.ahc.org.asynchttpclient.ListenableFuture; import play.shaded.ahc.org.asynchttpclient.ws.WebSocket; import play.shaded.ahc.org.asynchttpclient.ws.WebSocketListener; import play.shaded.ahc.org.asynchttpclient.ws.WebSocketTextListener; import play.shaded.ahc.org.asynchttpclient.ws.WebSocketUpgradeHandler; import org.slf4j.Logger; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; /** * A quick wrapper around AHC WebSocket * * https://github.com/AsyncHttpClient/async-http-client/blob/2.0/client/src/main/java/org/asynchttpclient/ws/WebSocket.java */ public class WebSocketClient { private AsyncHttpClient client; public WebSocketClient(AsyncHttpClient c) { this.client = c; } public CompletableFuture<WebSocket> call(String url, WebSocketTextListener listener) throws ExecutionException, InterruptedException { final BoundRequestBuilder requestBuilder = client.prepareGet(url); final WebSocketUpgradeHandler handler = new WebSocketUpgradeHandler.Builder().addWebSocketListener(listener).build(); final ListenableFuture<WebSocket> future = requestBuilder.execute(handler); return future.toCompletableFuture(); } static class LoggingListener implements WebSocketTextListener { private final Consumer<String> onMessageCallback; public LoggingListener(Consumer<String> onMessageCallback) { this.onMessageCallback = onMessageCallback; } private Logger logger = org.slf4j.LoggerFactory.getLogger(LoggingListener.class); private Throwable throwableFound = null; public Throwable getThrowable() { return throwableFound; } public void onOpen(WebSocket websocket) { //logger.info("onClose: "); //websocket.sendMessage("hello"); } public void onClose(WebSocket websocket) { //logger.info("onClose: "); } public void onError(Throwable t) { //logger.error("onError: ", t); throwableFound = t; } @Override public void onMessage(String s) { //logger.info("onMessage: s = " + s); onMessageCallback.accept(s); } } }
play2-maven-plugin/play2-maven-test-projects
play26/java/websocket-example-using-webjars-assets/test/controllers/WebSocketClient.java
Java
apache-2.0
2,469
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. # COM interop utility module import sys import nt from iptest.assert_util import * from iptest.file_util import * from iptest.process_util import * if is_cli: import clr from System import Type from System import Activator from System import Exception as System_dot_Exception remove_ironpython_dlls(testpath.public_testdir) load_iron_python_dll() import IronPython load_iron_python_test() import IronPythonTest #--For asserts in IP/DLR assemblies---------------------------------------- from System.Diagnostics import Debug, DefaultTraceListener class MyTraceListener(DefaultTraceListener): def Fail(self, msg, detailMsg=''): print "ASSERT FAILED:", msg if detailMsg!='': print " ", detailMsg sys.exit(1) if is_snap: Debug.Listeners.Clear() Debug.Listeners.Add(MyTraceListener()) is_pywin32 = False if sys.platform=="win32": try: import win32com.client is_pywin32 = True if sys.prefix not in nt.environ["Path"]: nt.environ["Path"] += ";" + sys.prefix except: pass #------------------------------------------------------------------------------ #--GLOBALS windir = get_environ_variable("windir") agentsvr_path = path_combine(windir, r"msagent\agentsvr.exe") scriptpw_path = path_combine(windir, r"system32\scriptpw.dll") STRING_VALUES = [ "", "a", "ab", "abc", "aa", "a" * 100000, "1", "1.0", "1L", "object", "str", "object()", " ", "_", "abc ", " abc", " abc ", "ab c", "ab c", "\ta", "a\t", "\n", "\t", "\na", "a\n"] STRING_VALUES = [unicode(x) for x in STRING_VALUES] + STRING_VALUES def aFunc(): pass class KNew(object): pass class KOld: pass NON_NUMBER_VALUES = [ object, KNew, KOld, Exception, object(), KNew(), KOld(), aFunc, str, eval, type, [], [3.14], ["abc"], (), (3,), (u"xyz",), xrange(5), {}, {'a':1}, __builtins__, ] FPN_VALUES = [ -1.23, -1.0, -0.123, -0.0, 0.123, 1.0, 1.23, 0.0000001, 3.14159265, 1E10, 1.0E10 ] UINT_VALUES = [ 0, 1, 2, 7, 10, 32] INT_VALUES = [ -x for x in UINT_VALUES ] + UINT_VALUES LONG_VALUES = [long(x) for x in INT_VALUES] COMPLEX_VALUES = [ 3j] #--Subclasses of Python/.NET types class Py_Str(str): pass if is_cli: class Py_System_String(System.String): pass class Py_Float(float): pass class Py_Double(float): pass if is_cli: class Py_System_Double(System.Double): pass class Py_UShort(int): pass class Py_ULong(long): pass class Py_ULongLong(long): pass class Py_Short(int): pass class Py_Long(int): pass if is_cli: class Py_System_Int32(System.Int32): pass class Py_LongLong(long): pass #-------Helpers---------------- def shallow_copy(in_list): ''' We do not necessarily have access to the copy module. ''' return [x for x in in_list] def pos_num_helper(clr_type): return [ clr_type.MinValue, clr_type.MinValue + 1, clr_type.MinValue + 2, clr_type.MinValue + 10, clr_type.MaxValue/2, clr_type.MaxValue - 10, clr_type.MaxValue - 2, clr_type.MaxValue - 1, clr_type.MaxValue, ] def overflow_num_helper(clr_type): return [ clr_type.MinValue - 1, clr_type.MinValue - 2, clr_type.MinValue - 3, clr_type.MinValue - 10, clr_type.MaxValue + 10, clr_type.MaxValue + 3, clr_type.MaxValue + 2, clr_type.MaxValue + 1, ] def valueErrorTrigger(in_type): ret_val = {} ############################################################ #Is there anything in Python not being able to evaluate to a bool? ret_val["VARIANT_BOOL"] = [ ] ############################################################ ret_val["BYTE"] = shallow_copy(NON_NUMBER_VALUES) ret_val["BYTE"] += COMPLEX_VALUES if sys.platform=="win32": ret_val["BYTE"] += FPN_VALUES #Merlin 323751 ret_val["BYTE"] = [x for x in ret_val["BYTE"] if type(x) not in [unicode, str]] #INCOMPAT BUG - should be ValueError ret_val["BYTE"] = [x for x in ret_val["BYTE"] if not isinstance(x, KOld)] #INCOMPAT BUG - should be AttributeError ############################################################ ret_val["BSTR"] = shallow_copy(NON_NUMBER_VALUES) ret_val["BSTR"] += COMPLEX_VALUES if sys.platform=="win32": ret_val["BSTR"] = [] #INCOMPAT BUG #strip out string values ret_val["BSTR"] = [x for x in ret_val["BSTR"] if type(x) is not str and type(x) is not KNew and type(x) is not KOld and type(x) is not object] ############################################################ ret_val["CHAR"] = shallow_copy(NON_NUMBER_VALUES) ret_val["CHAR"] += COMPLEX_VALUES if sys.platform=="win32": ret_val["CHAR"] += FPN_VALUES #Merlin 323751 ############################################################ ret_val["FLOAT"] = shallow_copy(NON_NUMBER_VALUES) ret_val["FLOAT"] += COMPLEX_VALUES if sys.platform=="win32": ret_val["FLOAT"] += UINT_VALUES + INT_VALUES #COMPAT BUG ############################################################ ret_val["DOUBLE"] = shallow_copy(ret_val["FLOAT"]) ############################################################ ret_val["USHORT"] = shallow_copy(NON_NUMBER_VALUES) ret_val["USHORT"] += COMPLEX_VALUES if sys.platform=="win32": ret_val["USHORT"] += FPN_VALUES #Merlin 323751 ############################################################ ret_val["ULONG"] = shallow_copy(ret_val["USHORT"]) ############################################################ ret_val["ULONGLONG"] = shallow_copy(ret_val["ULONG"]) ############################################################ ret_val["SHORT"] = shallow_copy(NON_NUMBER_VALUES) ret_val["SHORT"] += COMPLEX_VALUES if sys.platform=="win32": ret_val["SHORT"] += FPN_VALUES #Merlin 323751 ############################################################ ret_val["LONG"] = shallow_copy(ret_val["SHORT"]) ############################################################ ret_val["LONGLONG"] = shallow_copy(ret_val["LONG"]) ############################################################ return ret_val[in_type] def typeErrorTrigger(in_type): ret_val = {} ############################################################ #Is there anything in Python not being able to evaluate to a bool? ret_val["VARIANT_BOOL"] = [ ] ############################################################ ret_val["BYTE"] = [] ############################################################ ret_val["BSTR"] = [] #strip out string values ret_val["BSTR"] = [x for x in ret_val["BSTR"] if type(x) is not str] ############################################################ ret_val["CHAR"] = [] ############################################################ ret_val["FLOAT"] = [] ############################################################ ret_val["DOUBLE"] = [] ############################################################ ret_val["USHORT"] = [] ############################################################ ret_val["ULONG"] = [] ############################################################ ret_val["ULONGLONG"] = [] ############################################################ ret_val["SHORT"] = [] ############################################################ ret_val["LONG"] = [] ############################################################ ret_val["LONGLONG"] = [] ############################################################ return ret_val[in_type] def overflowErrorTrigger(in_type): ret_val = {} ############################################################ ret_val["VARIANT_BOOL"] = [] ############################################################ ret_val["BYTE"] = [] ret_val["BYTE"] += overflow_num_helper(System.Byte) ############################################################ #Doesn't seem possible to create a value (w/o 1st overflowing #in Python) to pass to the COM method which will overflow. ret_val["BSTR"] = [] #["0123456789" * 1234567890] ############################################################ ret_val["CHAR"] = [] ret_val["CHAR"] += overflow_num_helper(System.SByte) ############################################################ ret_val["FLOAT"] = [] ret_val["FLOAT"] += overflow_num_helper(System.Double) #Shouldn't be possible to overflow a double. ret_val["DOUBLE"] = [] ############################################################ ret_val["USHORT"] = [] ret_val["USHORT"] += overflow_num_helper(System.UInt16) ret_val["ULONG"] = [] ret_val["ULONG"] += overflow_num_helper(System.UInt32) ret_val["ULONGLONG"] = [] # Dev10 475426 #ret_val["ULONGLONG"] += overflow_num_helper(System.UInt64) ret_val["SHORT"] = [] ret_val["SHORT"] += overflow_num_helper(System.Int16) ret_val["LONG"] = [] # Dev10 475426 #ret_val["LONG"] += overflow_num_helper(System.Int32) ret_val["LONGLONG"] = [] # Dev10 475426 #ret_val["LONGLONG"] += overflow_num_helper(System.Int64) ############################################################ return ret_val[in_type] def pythonToCOM(in_type): ''' Given a COM type (in string format), this helper function returns a list of lists where each sublists contains 1-N elements. Each of these elements in turn are of different types (compatible with in_type), but equivalent to one another. ''' ret_val = {} ############################################################ temp_funcs = [int, bool, System.Boolean] # long, Dev10 475426 temp_values = [ 0, 1, True, False] ret_val["VARIANT_BOOL"] = [ [y(x) for y in temp_funcs] for x in temp_values] ############################################################ temp_funcs = [System.Byte] temp_values = pos_num_helper(System.Byte) ret_val["BYTE"] = [ [y(x) for y in temp_funcs] for x in temp_values] ############################################################ temp_funcs = [ str, unicode, # Py_Str, Py_System_String, System.String ] temp_values = shallow_copy(STRING_VALUES) ret_val["BSTR"] = [ [y(x) for y in temp_funcs] for x in temp_values] ############################################################ temp_funcs = [System.SByte] temp_values = pos_num_helper(System.SByte) ret_val["CHAR"] = [ [y(x) for y in temp_funcs] for x in temp_values] ############################################################ temp_funcs = [ float, # Py_Float, System.Single] ret_val["FLOAT"] = [ [y(x) for y in temp_funcs] for x in FPN_VALUES] ############################################################ temp_funcs = [ float, System.Double] # Py_Double, Py_System_Double, temp_values = [-1.0e+308, 1.0e308] + FPN_VALUES ret_val["DOUBLE"] = [ [y(x) for y in temp_funcs] for x in temp_values] ret_val["DOUBLE"] += ret_val["FLOAT"] ############################################################ temp_funcs = [int, System.UInt16] # Py_UShort, temp_values = pos_num_helper(System.UInt16) ret_val["USHORT"] = [ [y(x) for y in temp_funcs] for x in temp_values] ############################################################ temp_funcs = [int, System.UInt32] # Py_ULong, temp_values = pos_num_helper(System.UInt32) + pos_num_helper(System.UInt16) ret_val["ULONG"] = [ [y(x) for y in temp_funcs] for x in temp_values] ret_val["ULONG"] += ret_val["USHORT"] ############################################################ temp_funcs = [int, long, System.UInt64] # Py_ULongLong, temp_values = pos_num_helper(System.UInt64) + pos_num_helper(System.UInt32) + pos_num_helper(System.UInt16) ret_val["ULONGLONG"] = [ [y(x) for y in temp_funcs] for x in temp_values] ret_val["ULONGLONG"] += ret_val["ULONG"] ############################################################ temp_funcs = [int, System.Int16] # Py_Short, temp_values = pos_num_helper(System.Int16) ret_val["SHORT"] = [ [y(x) for y in temp_funcs] for x in temp_values] ############################################################ temp_funcs = [int, System.Int32] # Py_Long, Dev10 475426 temp_values = pos_num_helper(System.Int32) + pos_num_helper(System.Int16) ret_val["LONG"] = [ [y(x) for y in temp_funcs] for x in temp_values] ret_val["LONG"] += ret_val["SHORT"] ############################################################ temp_funcs = [int, long, System.Int64] # Py_LongLong, Dev10 475426 temp_values = pos_num_helper(System.Int64) + pos_num_helper(System.Int32) + pos_num_helper(System.Int16) ret_val["LONGLONG"] = [ [y(x) for y in temp_funcs] for x in temp_values] ret_val["LONGLONG"] += ret_val["LONG"] ############################################################ return ret_val[in_type] #------------------------------------------------------------------------------ #--Override a couple of definitions from assert_util from iptest import assert_util DEBUG = 1 def assert_helper(in_dict): #add the keys if they're not there if not in_dict.has_key("runonly"): in_dict["runonly"] = True if not in_dict.has_key("skip"): in_dict["skip"] = False #determine whether this test will be run or not run = in_dict["runonly"] and not in_dict["skip"] #strip out the keys for x in ["runonly", "skip"]: in_dict.pop(x) if not run: if in_dict.has_key("bugid"): print "...skipped an assert due to bug", str(in_dict["bugid"]) elif DEBUG: print "...skipped an assert on", sys.platform if in_dict.has_key("bugid"): in_dict.pop("bugid") return run def Assert(*args, **kwargs): if assert_helper(kwargs): assert_util.Assert(*args, **kwargs) def AreEqual(*args, **kwargs): if assert_helper(kwargs): assert_util.AreEqual(*args, **kwargs) def AssertError(*args, **kwargs): try: if assert_helper(kwargs): assert_util.AssertError(*args, **kwargs) except Exception, e: print "AssertError(" + str(args) + ", " + str(kwargs) + ") failed!" raise e def AssertErrorWithMessage(*args, **kwargs): try: if assert_helper(kwargs): assert_util.AssertErrorWithMessage(*args, **kwargs) except Exception, e: print "AssertErrorWithMessage(" + str(args) + ", " + str(kwargs) + ") failed!" raise e def AssertErrorWithPartialMessage(*args, **kwargs): try: if assert_helper(kwargs): assert_util.AssertErrorWithPartialMessage(*args, **kwargs) except Exception, e: print "AssertErrorWithPartialMessage(" + str(args) + ", " + str(kwargs) + ") failed!" raise e def AlmostEqual(*args, **kwargs): if assert_helper(kwargs): assert_util.AlmostEqual(*args, **kwargs) #------------------------------------------------------------------------------ #--HELPERS def TryLoadExcelInteropAssembly(): try: clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c') except: try: clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c') except: pass #------------------------------------------------------------------------------ def TryLoadWordInteropAssembly(): try: clr.AddReferenceByName('Microsoft.Office.Interop.Word, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c') except: try: clr.AddReferenceByName('Microsoft.Office.Interop.Word, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c') except: pass #------------------------------------------------------------------------------ def IsExcelInstalled(): from Microsoft.Win32 import Registry from System.IO import File excel = None #Office 11 or 12 are both OK for this test. Office 12 is preferred. excel = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\12.0\\Excel\\InstallRoot") if excel==None: excel = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\11.0\\Excel\\InstallRoot") #sanity check if excel==None: return False #make sure it's really installed on disk excel_path = excel.GetValue("Path") + "excel.exe" return File.Exists(excel_path) #------------------------------------------------------------------------------ def IsWordInstalled(): from Microsoft.Win32 import Registry from System.IO import File word = None #Office 11 or 12 are both OK for this test. Office 12 is preferred. word = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\12.0\\Word\\InstallRoot") if word==None: word= Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\11.0\\Word\\InstallRoot") #sanity check if word==None: return False #make sure it's really installed on disk word_path = word.GetValue("Path") + "winword.exe" return File.Exists(word_path) #------------------------------------------------------------------------------ def CreateExcelApplication(): #TODO: why is there use of the GUID here? #import clr #typelib = clr.LoadTypeLibrary(System.Guid("00020813-0000-0000-C000-000000000046")) #return typelib.Excel.Application() import System type = System.Type.GetTypeFromProgID("Excel.Application") return System.Activator.CreateInstance(type) #------------------------------------------------------------------------------ def CreateWordApplication(): import System #import clr #typelib = clr.LoadTypeLibrary(System.Guid("00020905-0000-0000-C000-000000000046")) #return typelib.Word.Application() type = System.Type.GetTypeFromProgID("Word.Application") return System.Activator.CreateInstance(type) #------------------------------------------------------------------------------ def CreateAgentServer(): import clr from System import Guid typelib = clr.LoadTypeLibrary(Guid("A7B93C73-7B81-11D0-AC5F-00C04FD97575")) return typelib.AgentServerObjects.AgentServer() #------------------------------------------------------------------------------ def CreateDlrComServer(): com_type_name = "DlrComLibrary.DlrComServer" if is_cli: com_obj = getRCWFromProgID(com_type_name) else: com_obj = win32com.client.Dispatch(com_type_name) return com_obj #------------------------------------------------------------------------------ def getTypeFromProgID(prog_id): ''' Returns the Type object for prog_id. ''' return Type.GetTypeFromProgID(prog_id) #------------------------------------------------------------------------------ def getRCWFromProgID(prog_id): ''' Returns an instance of prog_id. ''' if is_cli: return Activator.CreateInstance(getTypeFromProgID(prog_id)) else: return win32com.client.Dispatch(prog_id) #------------------------------------------------------------------------------ def genPeverifyInteropAsm(file): #if this isn't a test run that will invoke peverify there's no point in #continuing if not is_peverify_run: return else: mod_name = file.rsplit("\\", 1)[1].split(".py")[0] print "Generating interop assemblies for the", mod_name, "test module which are needed in %TEMP% by peverify..." from System.IO import Path tempDir = Path.GetTempPath() cwd = nt.getcwd() #maps COM interop test module names to a list of DLLs module_dll_dict = { "excel" : [], "msagent" : [agentsvr_path], "scriptpw" : [scriptpw_path], "word" : [], } dlrcomlib_list = [ "dlrcomserver", "paramsinretval", "method", "obj", "prop", ] if is_cli32: temp_name = testpath.rowan_root + "\\Test\\DlrComLibrary\\Debug\\DlrComLibrary.dll" else: temp_name = testpath.rowan_root + "\\Test\\DlrComLibrary\\x64\\Release\\DlrComLibrary.dll" for mod_name in dlrcomlib_list: module_dll_dict[mod_name] = [ temp_name ] if not file_exists_in_path("tlbimp.exe"): print "ERROR: tlbimp.exe is not in the path!" sys.exit(1) try: if not module_dll_dict.has_key(mod_name): print "WARNING: cannot determine which interop assemblies to install!" print " This may affect peverify runs adversely." print return else: nt.chdir(tempDir) for com_dll in module_dll_dict[mod_name]: if not file_exists(com_dll): print "\tERROR: %s does not exist!" % (com_dll) continue print "\trunning tlbimp on", com_dll run_tlbimp(com_dll) finally: nt.chdir(cwd) #------------------------------------------------------------------------------ #--Fake parts of System for compat tests if sys.platform=="win32": class System: class Byte(int): MinValue = 0 MaxValue = 255 class SByte(int): MinValue = -128 MaxValue = 127 class Int16(int): MinValue = -32768 MaxValue = 32767 class UInt16(int): MinValue = 0 MaxValue = 65535 class Int32(int): MinValue = -2147483648 MaxValue = 2147483647 class UInt32(long): MinValue = 0 MaxValue = 4294967295 class Int64(long): MinValue = -9223372036854775808L MaxValue = 9223372036854775807L class UInt64(long): MinValue = 0L MaxValue = 18446744073709551615 class Single(float): MinValue = -3.40282e+038 MaxValue = 3.40282e+038 class Double(float): MinValue = -1.79769313486e+308 MaxValue = 1.79769313486e+308 class String(str): pass class Boolean(int): pass #------------------------------------------------------------------------------ def run_com_test(name, file): run_test(name) genPeverifyInteropAsm(file)
slozier/ironpython2
Src/IronPython/Lib/iptest/cominterop_util.py
Python
apache-2.0
24,101
package com.badlogic.gdx.backends.jglfw; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Graphics.DisplayMode; import com.badlogic.gdx.backends.jglfw.JglfwGraphics.JglfwDisplayMode; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.utils.Array; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; /** @author Nathan Sweet */ public class JglfwApplicationConfiguration { /** Title of application window. **/ public String title = ""; /** Initial width of the application window. **/ public int width = 640; /** Initial height of the application window. **/ public int height = 480; /** Intial x coordinate of the application window, -1 for center. **/ public int x = -1; /** Intial x coordinate of the application window, -1 for center. **/ public int y = -1; /** True to start in fullscreen. **/ public boolean fullscreen; /** Monitor index to use for fullscreen. **/ public int fullscreenMonitorIndex = -1; /** Number of bits per color channel. **/ public int r = 8, g = 8, b = 8, a = 8; /** Number of bits for the depth buffer. **/ public int depth = 16; /** Number of bits for the stencil buffer. **/ public int stencil = 0; /** Number of samples for MSAA **/ public int samples = 0; /** True to enable vsync. **/ public boolean vSync = true; /** True if the window is resizable. **/ public boolean resizable = true; /** True to attempt to use OpenGL ES 2.0. Note {@link Gdx#gl20} may be null even when this is true. **/ public boolean useGL20; /** True to call System.exit() when the main loop is complete. **/ public boolean forceExit = true; /** True to have a title and border around the window. **/ public boolean undecorated; /** Causes the main loop to run on the EDT instead of a new thread, for easier interoperability with AWT/Swing. Broken on Linux. **/ public boolean runOnEDT; /** The color to clear the window immediately after creation. **/ public Color initialBackgroundColor = Color.BLACK; /** True to hide the window when it is created. The window must be shown with {@link JglfwGraphics#show()}. **/ public boolean hidden; /** Target framerate when the window is in the foreground. The CPU sleeps as needed. Use 0 to never sleep. **/ public int foregroundFPS; /** Target framerate when the window is in the background. The CPU sleeps as needed. Use 0 to never sleep, -1 to not render. **/ public int backgroundFPS; /** Target framerate when the window is hidden or minimized. The CPU sleeps as needed. Use 0 to never sleep, -1 to not render. **/ public int hiddenFPS = -1; static public DisplayMode[] getDisplayModes () { GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); java.awt.DisplayMode desktopMode = device.getDisplayMode(); java.awt.DisplayMode[] displayModes = device.getDisplayModes(); Array<DisplayMode> modes = new Array(); outer: for (java.awt.DisplayMode mode : displayModes) { for (DisplayMode other : modes) if (other.width == mode.getWidth() && other.height == mode.getHeight() && other.bitsPerPixel == mode.getBitDepth()) continue outer; // Duplicate. if (mode.getBitDepth() != desktopMode.getBitDepth()) continue; modes.add(new JglfwDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getBitDepth())); } return modes.toArray(DisplayMode.class); } static public DisplayMode getDesktopDisplayMode () { java.awt.DisplayMode mode = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode(); return new JglfwDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getBitDepth()); } }
domix/libgdx
backends/gdx-backend-jglfw/src/com/badlogic/gdx/backends/jglfw/JglfwApplicationConfiguration.java
Java
apache-2.0
3,674
package com.xnx3.j2ee.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * FriendLog entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "friend_log") public class FriendLog implements java.io.Serializable { // Fields private Integer id; private Integer self; private Integer other; private Integer time; private Short state; private String ip; // Constructors /** default constructor */ public FriendLog() { } /** full constructor */ public FriendLog(Integer self, Integer other, Integer time, Short state, String ip) { this.self = self; this.other = other; this.time = time; this.state = state; this.ip = ip; } // Property accessors @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "self", nullable = false) public Integer getSelf() { return this.self; } public void setSelf(Integer self) { this.self = self; } @Column(name = "other", nullable = false) public Integer getOther() { return this.other; } public void setOther(Integer other) { this.other = other; } @Column(name = "time", nullable = false) public Integer getTime() { return this.time; } public void setTime(Integer time) { this.time = time; } @Column(name = "state", nullable = false) public Short getState() { return this.state; } public void setState(Short state) { this.state = state; } @Column(name = "ip", nullable = false, length = 15) public String getIp() { return this.ip; } public void setIp(String ip) { this.ip = ip; } }
xnx3/iw_demo
src/com/xnx3/j2ee/entity/FriendLog.java
Java
apache-2.0
1,858