max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
687
package io.kestra.core.endpoints; import io.micronaut.context.ApplicationContext; import io.micronaut.context.env.Environment; import io.micronaut.context.env.MapPropertySource; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.HttpStatus; import io.micronaut.http.MutableHttpRequest; import io.micronaut.http.client.RxHttpClient; import io.micronaut.http.client.exceptions.HttpClientResponseException; import io.micronaut.runtime.server.EmbeddedServer; import org.junit.jupiter.api.Test; import java.util.Map; import java.util.function.BiConsumer; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows; class BasicAuthEndpointsFilterTest { void test(boolean password, BiConsumer<RxHttpClient, MutableHttpRequest<String>> consumer) { MapPropertySource mapPropertySource = new MapPropertySource( "unittest", password ? Map.of( "endpoints.all.enabled", true, "endpoints.all.sensitive", false, "endpoints.all.basic-auth.username", "foo", "endpoints.all.basic-auth.password", "<PASSWORD>" ) : Map.of( "endpoints.all.enabled", true, "endpoints.all.sensitive", false ) ); try (ApplicationContext ctx = ApplicationContext.run(mapPropertySource, Environment.CLI, Environment.TEST)) { EmbeddedServer embeddedServer = ctx.getBean(EmbeddedServer.class); embeddedServer.start(); RxHttpClient client = ctx.getBean(RxHttpClient.class); consumer.accept(client, HttpRequest.GET("http://localhost:" + embeddedServer.getPort() +"/health")); } } @Test void withPasswordOk() { test(true, (client, httpRequest) -> { HttpResponse<String> response = client.toBlocking().exchange(httpRequest.basicAuth("foo", "bar")); assertThat(response.getStatus(), is(HttpStatus.OK)); }); } @Test void withPasswordKo() { test(true, (client, httpRequest) -> { HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () -> { client.toBlocking().exchange(httpRequest.basicAuth("foo", "bar2")); }); assertThat(e.getStatus(), is(HttpStatus.UNAUTHORIZED)); }); test(true, (client, httpRequest) -> { HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () -> { client.toBlocking().exchange(httpRequest); }); assertThat(e.getStatus(), is(HttpStatus.UNAUTHORIZED)); }); } @Test void withoutPasswordOk() { test(false, (client, httpRequest) -> { HttpResponse<String> response = client.toBlocking().exchange(httpRequest); assertThat(response.getStatus(), is(HttpStatus.OK)); }); } }
1,310
575
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.android.webview.chromium; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.net.Uri; import android.os.Build; import android.os.SystemClock; import android.provider.Settings; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.GeolocationPermissions; import android.webkit.PacProcessor; import android.webkit.ServiceWorkerController; import android.webkit.TokenBindingService; import android.webkit.TracingController; import android.webkit.ValueCallback; import android.webkit.WebStorage; import android.webkit.WebView; import android.webkit.WebViewDatabase; import android.webkit.WebViewFactory; import android.webkit.WebViewFactoryProvider; import android.webkit.WebViewProvider; import com.android.webview.chromium.WebViewDelegateFactory.WebViewDelegate; import org.chromium.android_webview.ApkType; import org.chromium.android_webview.AwBrowserContext; import org.chromium.android_webview.AwBrowserProcess; import org.chromium.android_webview.AwContentsStatics; import org.chromium.android_webview.AwSettings; import org.chromium.android_webview.ProductConfig; import org.chromium.android_webview.WebViewChromiumRunQueue; import org.chromium.android_webview.common.AwSwitches; import org.chromium.android_webview.common.CommandLineUtil; import org.chromium.android_webview.common.DeveloperModeUtils; import org.chromium.android_webview.common.FlagOverrideHelper; import org.chromium.android_webview.common.ProductionSupportedFlagList; import org.chromium.base.BuildInfo; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.PackageUtils; import org.chromium.base.PathUtils; import org.chromium.base.StrictModeContext; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.VerifiesOnN; import org.chromium.base.annotations.VerifiesOnP; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.build.NativeLibraries; import org.chromium.components.autofill.AutofillProvider; import org.chromium.components.embedder_support.application.ClassLoaderContextWrapperFactory; import org.chromium.components.embedder_support.application.FirebaseConfig; import org.chromium.content_public.browser.LGEmailActionModeWorkaround; import java.io.File; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; /** * Entry point to the WebView. The system framework talks to this class to get instances of the * implementation classes. */ @SuppressWarnings("deprecation") public class WebViewChromiumFactoryProvider implements WebViewFactoryProvider { private static final String TAG = "WVCFactoryProvider"; private static final String CHROMIUM_PREFS_NAME = "WebViewChromiumPrefs"; private static final String VERSION_CODE_PREF = "lastVersionCodeUsed"; private static final String SUPPORT_LIB_GLUE_AND_BOUNDARY_INTERFACE_PREFIX = "org.chromium.support_lib_"; // This is an ID hardcoded by WebLayer for resources stored in locale splits. See // WebLayerImpl.java for more info. private static final int SHARED_LIBRARY_MAX_ID = 36; /** * This holds objects of classes that are defined in N and above to ensure that run-time class * verification does not occur until it is actually used for N and above. */ @TargetApi(Build.VERSION_CODES.N) @VerifiesOnN private static class ObjectHolderForN { public ServiceWorkerController mServiceWorkerController; } /** * This holds objects of classes that are defined in P and above to ensure that run-time class * verification does not occur until it is actually used for P and above. */ @TargetApi(Build.VERSION_CODES.P) @VerifiesOnP private static class ObjectHolderForP { public TracingController mTracingController; } private static final Object sSingletonLock = new Object(); private static WebViewChromiumFactoryProvider sSingleton; // Used to indicate if WebLayer and WebView are running in the same process. private static boolean sWebLayerRunningInSameProcess; private final WebViewChromiumRunQueue mRunQueue = new WebViewChromiumRunQueue( () -> { return WebViewChromiumFactoryProvider.this.mAwInit.hasStarted(); }); /* package */ WebViewChromiumRunQueue getRunQueue() { return mRunQueue; } // We have a 4 second timeout to try to detect deadlocks to detect and aid in debuggin // deadlocks. // Do not call this method while on the UI thread! /* package */ void runVoidTaskOnUiThreadBlocking(Runnable r) { mRunQueue.runVoidTaskOnUiThreadBlocking(r); } /* package */ <T> T runOnUiThreadBlocking(Callable<T> c) { return mRunQueue.runBlockingFuture(new FutureTask<T>(c)); } /* package */ void addTask(Runnable task) { mRunQueue.addTask(task); } /** * Class that takes care of chromium lazy initialization. * This is package-public so that a downstream subclass can access it. */ /* package */ WebViewChromiumAwInit mAwInit; private SharedPreferences mWebViewPrefs; private WebViewDelegate mWebViewDelegate; protected boolean mShouldDisableThreadChecking; // Initialization guarded by mAwInit.getLock() private Statics mStaticsAdapter; @TargetApi(Build.VERSION_CODES.N) private ObjectHolderForN mObjectHolderForN = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new ObjectHolderForN() : null; @TargetApi(Build.VERSION_CODES.P) private ObjectHolderForP mObjectHolderForP = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ? new ObjectHolderForP() : null; /** * Thread-safe way to set the one and only WebViewChromiumFactoryProvider. */ private static void setSingleton(WebViewChromiumFactoryProvider provider) { synchronized (sSingletonLock) { if (sSingleton != null) { throw new RuntimeException( "WebViewChromiumFactoryProvider should only be set once!"); } sSingleton = provider; } } /** * Thread-safe way to get the one and only WebViewChromiumFactoryProvider. */ static WebViewChromiumFactoryProvider getSingleton() { synchronized (sSingletonLock) { if (sSingleton == null) { throw new RuntimeException("WebViewChromiumFactoryProvider has not been set!"); } return sSingleton; } } /** * Entry point for newer versions of Android. */ public static WebViewChromiumFactoryProvider create(android.webkit.WebViewDelegate delegate) { return new WebViewChromiumFactoryProvider(delegate); } /** * Constructor called by the API 21 version of {@link WebViewFactory} and earlier. */ public WebViewChromiumFactoryProvider() { initialize(WebViewDelegateFactory.createApi21CompatibilityDelegate()); } /** * Constructor called by the API 22 version of {@link WebViewFactory} and later. */ public WebViewChromiumFactoryProvider(android.webkit.WebViewDelegate delegate) { initialize(WebViewDelegateFactory.createProxyDelegate(delegate)); } /** * Constructor for internal use when a proxy delegate has already been created. */ WebViewChromiumFactoryProvider(WebViewDelegate delegate) { initialize(delegate); } // Protected to allow downstream to override. protected WebViewChromiumAwInit createAwInit() { try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped("WebViewChromiumFactoryProvider.createAwInit")) { return new WebViewChromiumAwInit(this); } } // Protected to allow downstream to override. protected ContentSettingsAdapter createContentSettingsAdapter(AwSettings settings) { return new ContentSettingsAdapter(settings); } private void deleteContentsOnPackageDowngrade(PackageInfo packageInfo) { try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped( "WebViewChromiumFactoryProvider.deleteContentsOnPackageDowngrade")) { // Use shared preference to check for package downgrade. // Since N, getSharedPreferences creates the preference dir if it doesn't exist, // causing a disk write. mWebViewPrefs = ContextUtils.getApplicationContext().getSharedPreferences( CHROMIUM_PREFS_NAME, Context.MODE_PRIVATE); int lastVersion = mWebViewPrefs.getInt(VERSION_CODE_PREF, 0); int currentVersion = packageInfo.versionCode; if (!versionCodeGE(currentVersion, lastVersion)) { // The WebView package has been downgraded since we last ran in this // application. Delete the WebView data directory's contents. String dataDir = PathUtils.getDataDirectory(); Log.i(TAG, "WebView package downgraded from " + lastVersion + " to " + currentVersion + "; deleting contents of " + dataDir); deleteContents(new File(dataDir)); } if (lastVersion != currentVersion) { mWebViewPrefs.edit().putInt(VERSION_CODE_PREF, currentVersion).apply(); } } } @SuppressWarnings("NoContextGetApplicationContext") private void initialize(WebViewDelegate webViewDelegate) { long startTime = SystemClock.uptimeMillis(); try (ScopedSysTraceEvent e1 = ScopedSysTraceEvent.scoped("WebViewChromiumFactoryProvider.initialize")) { PackageInfo packageInfo; try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped( "WebViewChromiumFactoryProvider.getLoadedPackageInfo")) { // The package is used to locate the services for copying crash minidumps and // requesting variations seeds. So it must be set before initializing variations and // before a renderer has a chance to crash. packageInfo = WebViewFactory.getLoadedPackageInfo(); } AwBrowserProcess.setWebViewPackageName(packageInfo.packageName); AwBrowserProcess.initializeApkType(packageInfo.applicationInfo); mAwInit = createAwInit(); mWebViewDelegate = webViewDelegate; Context ctx = webViewDelegate.getApplication().getApplicationContext(); // If the application context is DE, but we have credentials, use a CE context instead try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped( "WebViewChromiumFactoryProvider.checkStorage")) { checkStorageIsNotDeviceProtected(webViewDelegate.getApplication()); } catch (IllegalArgumentException e) { assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.N; if (!GlueApiHelperForN.isUserUnlocked(ctx)) { throw e; } ctx = GlueApiHelperForN.createCredentialProtectedStorageContext(ctx); } // WebView needs to make sure to always use the wrapped application context. ctx = ClassLoaderContextWrapperFactory.get(ctx); ContextUtils.initApplicationContext(ctx); // Find the package ID for the package that WebView's resources come from. // This will be the donor package if there is one, not our main package. String resourcePackage = packageInfo.packageName; if (packageInfo.applicationInfo.metaData != null) { resourcePackage = packageInfo.applicationInfo.metaData.getString( "com.android.webview.WebViewDonorPackage", resourcePackage); } int packageId = webViewDelegate.getPackageId(ctx.getResources(), resourcePackage); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && AwBrowserProcess.getApkType() != ApkType.TRICHROME && packageId > SHARED_LIBRARY_MAX_ID) { throw new RuntimeException("Package ID too high for WebView: " + packageId); } mAwInit.setUpResourcesOnBackgroundThread(packageId, ctx); try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped( "WebViewChromiumFactoryProvider.initCommandLine")) { // This may take ~20 ms only on userdebug devices. CommandLineUtil.initCommandLine(); } boolean multiProcess = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Ask the system if multiprocess should be enabled on O+. multiProcess = webViewDelegate.isMultiProcessEnabled(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // Check the multiprocess developer setting directly on N. multiProcess = Settings.Global.getInt(ctx.getContentResolver(), Settings.Global.WEBVIEW_MULTIPROCESS, 0) == 1; } if (multiProcess) { CommandLine cl = CommandLine.getInstance(); cl.appendSwitch(AwSwitches.WEBVIEW_SANDBOXED_RENDERER); } // Enable modern SameSite cookie behavior if the app targets at least S. if (BuildInfo.targetsAtLeastS()) { CommandLine cl = CommandLine.getInstance(); cl.appendSwitch(AwSwitches.WEBVIEW_ENABLE_MODERN_COOKIE_SAME_SITE); } int applicationFlags = ctx.getApplicationInfo().flags; boolean isAppDebuggable = (applicationFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; boolean isOsDebuggable = BuildInfo.isDebugAndroid(); // Enable logging JS console messages in system logs only if the app is debuggable or // it's a debugable android build. if (isAppDebuggable || isOsDebuggable) { CommandLine cl = CommandLine.getInstance(); cl.appendSwitch(AwSwitches.WEBVIEW_LOG_JS_CONSOLE_MESSAGES); } String webViewPackageName = AwBrowserProcess.getWebViewPackageName(); long developerModeStart = SystemClock.elapsedRealtime(); boolean isDeveloperModeEnabled = DeveloperModeUtils.isDeveloperModeEnabled(webViewPackageName); long developerModeEnd = SystemClock.elapsedRealtime(); RecordHistogram.recordTimesHistogram("Android.WebView.DevUi.DeveloperModeBlockingTime", developerModeEnd - developerModeStart); RecordHistogram.recordBooleanHistogram( "Android.WebView.DevUi.DeveloperModeEnabled", isDeveloperModeEnabled); Map<String, Boolean> flagOverrides = null; if (isDeveloperModeEnabled) { long start = SystemClock.elapsedRealtime(); try { FlagOverrideHelper helper = new FlagOverrideHelper(ProductionSupportedFlagList.sFlagList); flagOverrides = DeveloperModeUtils.getFlagOverrides(webViewPackageName); helper.applyFlagOverrides(flagOverrides); RecordHistogram.recordCount100Histogram( "Android.WebView.DevUi.ToggledFlagCount", flagOverrides.size()); } finally { long end = SystemClock.elapsedRealtime(); RecordHistogram.recordTimesHistogram( "Android.WebView.DevUi.FlagLoadingBlockingTime", end - start); } } ThreadUtils.setWillOverrideUiThread(true); BuildInfo.setBrowserPackageInfo(packageInfo); BuildInfo.setFirebaseAppId( FirebaseConfig.getFirebaseAppIdForPackage(packageInfo.packageName)); try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) { try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped( "WebViewChromiumFactoryProvider.loadChromiumLibrary")) { String dataDirectorySuffix = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { dataDirectorySuffix = webViewDelegate.getDataDirectorySuffix(); } AwBrowserProcess.loadLibrary(dataDirectorySuffix); } try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped( "WebViewChromiumFactoryProvider.loadGlueLayerPlatSupportLibrary")) { System.loadLibrary("webviewchromium_plat_support"); } deleteContentsOnPackageDowngrade(packageInfo); } // Now safe to use WebView data directory. if (flagOverrides != null) { AwContentsStatics.logFlagOverridesWithNative(flagOverrides); } mAwInit.startVariationsInit(); mShouldDisableThreadChecking = shouldDisableThreadChecking(ctx); setSingleton(this); // sWebLayerRunningInSameProcess may have been set before initialize(). if (sWebLayerRunningInSameProcess) { addTask(() -> { getBrowserContextOnUiThread().setWebLayerRunningInSameProcess(); }); } } RecordHistogram.recordTimesHistogram( "Android.WebView.Startup.CreationTime.Stage1.FactoryInit", SystemClock.uptimeMillis() - startTime); /* TODO(torne): re-enable this once the API change is sorted out if (BuildInfo.isAtLeastS()) { // TODO: Use the framework constants as indices in timestamps array. startTime = mWebViewDelegate.getTimestamps()[0]; RecordHistogram.recordTimesHistogram( "Android.WebView.Startup.CreationTime.TotalFactoryInitTime", SystemClock.uptimeMillis() - startTime); } */ } /* package */ static void checkStorageIsNotDeviceProtected(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && GlueApiHelperForN.isDeviceProtectedStorage(context)) { throw new IllegalArgumentException( "WebView cannot be used with device protected storage"); } } /** * Both versionCodes should be from a WebView provider package implemented by Chromium. * VersionCodes from other kinds of packages won't make any sense in this method. * * An introduction to Chromium versionCode scheme: * "BBBBPPPAX" * BBBB: 4 digit branch number. It monotonically increases over time. * PPP: patch number in the branch. It is padded with zeroes to the left. These three digits may * change their meaning in the future. * A: architecture digit. * X: A digit to differentiate APKs for other reasons. * * This method takes the "BBBB" of versionCodes and compare them. * * @return true if versionCode1 is higher than or equal to versionCode2. */ private static boolean versionCodeGE(int versionCode1, int versionCode2) { int v1 = versionCode1 / 100000; int v2 = versionCode2 / 100000; return v1 >= v2; } private static void deleteContents(File dir) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { deleteContents(file); } if (!file.delete()) { Log.w(TAG, "Failed to delete " + file); } } } } public static boolean preloadInZygote() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.P && ProductConfig.IS_BUNDLE) { // Apply workaround if we're a bundle on O, where the split APK handling bug exists. SplitApkWorkaround.apply(); } for (String library : NativeLibraries.LIBRARIES) { System.loadLibrary(library); } return true; } SharedPreferences getWebViewPrefs() { return mWebViewPrefs; } @Override public Statics getStatics() { synchronized (mAwInit.getLock()) { SharedStatics sharedStatics = mAwInit.getStatics(); if (mStaticsAdapter == null) { mStaticsAdapter = new WebViewChromiumFactoryProvider.Statics() { @Override public String findAddress(String addr) { return sharedStatics.findAddress(addr); } @Override public String getDefaultUserAgent(Context context) { return sharedStatics.getDefaultUserAgent(context); } @Override public void setWebContentsDebuggingEnabled(boolean enable) { sharedStatics.setWebContentsDebuggingEnabled(enable); } @Override public void clearClientCertPreferences(Runnable onCleared) { sharedStatics.clearClientCertPreferences(onCleared); } @Override public void freeMemoryForTests() { sharedStatics.freeMemoryForTests(); } @Override public void enableSlowWholeDocumentDraw() { sharedStatics.enableSlowWholeDocumentDraw(); } @Override public Uri[] parseFileChooserResult(int resultCode, Intent intent) { return sharedStatics.parseFileChooserResult(resultCode, intent); } @Override public void initSafeBrowsing(Context context, ValueCallback<Boolean> callback) { sharedStatics.initSafeBrowsing( context, CallbackConverter.fromValueCallback(callback)); } @Override public void setSafeBrowsingWhitelist( List<String> urls, ValueCallback<Boolean> callback) { sharedStatics.setSafeBrowsingAllowlist( urls, CallbackConverter.fromValueCallback(callback)); } @Override public Uri getSafeBrowsingPrivacyPolicyUrl() { return sharedStatics.getSafeBrowsingPrivacyPolicyUrl(); } public boolean isMultiProcessEnabled() { return sharedStatics.isMultiProcessEnabled(); } }; } } return mStaticsAdapter; } @Override public WebViewProvider createWebView(WebView webView, WebView.PrivateAccess privateAccess) { return new WebViewChromium(this, webView, privateAccess, mShouldDisableThreadChecking); } // Workaround for IME thread crashes on legacy OEM apps. private boolean shouldDisableThreadChecking(Context context) { String appName = context.getPackageName(); int versionCode = PackageUtils.getPackageVersion(context, appName); int appTargetSdkVersion = context.getApplicationInfo().targetSdkVersion; if (versionCode == -1) return false; boolean shouldDisable = false; // crbug.com/651706 final String lgeMailPackageId = "com.lge.email"; if (lgeMailPackageId.equals(appName)) { if (appTargetSdkVersion > Build.VERSION_CODES.N) return false; if (LGEmailActionModeWorkaround.isSafeVersion(versionCode)) return false; shouldDisable = true; } // crbug.com/655759 // Also want to cover ".att" variant suffix package name. final String yahooMailPackageId = "com.yahoo.mobile.client.android.mail"; if (appName.startsWith(yahooMailPackageId)) { if (appTargetSdkVersion > Build.VERSION_CODES.M) return false; if (versionCode > 1315850) return false; shouldDisable = true; } // crbug.com/622151 final String htcMailPackageId = "com.htc.android.mail"; if (htcMailPackageId.equals(appName)) { if (appTargetSdkVersion > Build.VERSION_CODES.M) return false; // This value is provided by HTC. if (versionCode >= 866001861) return false; shouldDisable = true; } if (shouldDisable) { Log.w(TAG, "Disabling thread check in WebView. " + "APK name: " + appName + ", versionCode: " + versionCode + ", targetSdkVersion: " + appTargetSdkVersion); } return shouldDisable; } @Override public GeolocationPermissions getGeolocationPermissions() { return mAwInit.getGeolocationPermissions(); } @Override public CookieManager getCookieManager() { return mAwInit.getCookieManager(); } @Override public ServiceWorkerController getServiceWorkerController() { synchronized (mAwInit.getLock()) { if (mObjectHolderForN.mServiceWorkerController == null) { mObjectHolderForN.mServiceWorkerController = GlueApiHelperForN.createServiceWorkerControllerAdapter(mAwInit); } } return mObjectHolderForN.mServiceWorkerController; } @Override public TokenBindingService getTokenBindingService() { return null; } @Override public android.webkit.WebIconDatabase getWebIconDatabase() { return mAwInit.getWebIconDatabase(); } @Override public WebStorage getWebStorage() { return mAwInit.getWebStorage(); } @Override public WebViewDatabase getWebViewDatabase(final Context context) { return mAwInit.getWebViewDatabase(context); } WebViewDelegate getWebViewDelegate() { return mWebViewDelegate; } WebViewContentsClientAdapter createWebViewContentsClientAdapter(WebView webView, Context context) { try (ScopedSysTraceEvent e = ScopedSysTraceEvent.scoped( "WebViewChromiumFactoryProvider.insideCreateWebViewContentsClientAdapter")) { return new WebViewContentsClientAdapter(webView, context, mWebViewDelegate); } } AutofillProvider createAutofillProvider(Context context, ViewGroup containerView) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return null; return new AutofillProvider(context, containerView, "Android WebView"); } void startYourEngines(boolean onMainThread) { try (ScopedSysTraceEvent e1 = ScopedSysTraceEvent.scoped( "WebViewChromiumFactoryProvider.startYourEngines")) { mAwInit.startYourEngines(onMainThread); } } boolean hasStarted() { return mAwInit.hasStarted(); } // Only on UI thread. AwBrowserContext getBrowserContextOnUiThread() { return mAwInit.getBrowserContextOnUiThread(); } WebViewChromiumAwInit getAwInit() { return mAwInit; } @Override public TracingController getTracingController() { synchronized (mAwInit.getLock()) { mAwInit.ensureChromiumStartedLocked(true); // ensureChromiumStartedLocked() can release the lock on first call while // waiting for startup. Hence check the mTracingController here to ensure // the singleton property. if (mObjectHolderForP.mTracingController == null) { mObjectHolderForP.mTracingController = GlueApiHelperForP.createTracingControllerAdapter(this, mAwInit); } } return mObjectHolderForP.mTracingController; } private static class FilteredClassLoader extends ClassLoader { FilteredClassLoader(ClassLoader delegate) { super(delegate); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { final String message = "This ClassLoader should only be used for the androidx.webkit support library"; if (name == null) { throw new ClassNotFoundException(message); } // We only permit this ClassLoader to load classes required for support library // reflection, as applications should not use this for any other purpose. So, we permit // anything in the support_lib_glue and support_lib_boundary packages (and their // subpackages). if (name.startsWith(SUPPORT_LIB_GLUE_AND_BOUNDARY_INTERFACE_PREFIX)) { return super.findClass(name); } throw new ClassNotFoundException(message); } } @Override public ClassLoader getWebViewClassLoader() { return new FilteredClassLoader(WebViewChromiumFactoryProvider.class.getClassLoader()); } // This is called from WebLayer when WebView and WebLayer are run in the same process. It's // used to set a crash key to help attribute crashes. It's entirely possible WebView has not // been initialized when this is called. public static void setWebLayerRunningInSameProcess() { // This may be called before initialize(). synchronized (sSingletonLock) { sWebLayerRunningInSameProcess = true; if (sSingleton == null) { // initialize() hasn't been called yet. When initialize() is called // |sWebLayerRunningInSameProcess| will be checked. return; } } getSingleton().addTask(() -> { getSingleton().getBrowserContextOnUiThread().setWebLayerRunningInSameProcess(); }); } @Override public PacProcessor getPacProcessor() { return GlueApiHelperForR.getPacProcessor(); } }
12,946
462
<reponame>cable5881/pmq<gh_stars>100-1000 package com.ppdai.infrastructure.mq.biz.dto.response; /** * @Author:wanghe02 * @Date:2019/7/5 14:36 */ public class ConsumerGroupCreateResponse extends BaseUiResponse<Void> { public ConsumerGroupCreateResponse() { super(); } public ConsumerGroupCreateResponse(String code, String msg) { super(code,msg); } }
154
739
import DOM class FocusWidget: def __init__(self, element): self.clickListeners = [] def addClickListener(self, listener): self.clickListeners.append(listener) def onBrowserEvent(self, event): if DOM.eventGetType(event) == Event.ONCLICK: for listener in self.clickListeners: listener(self)
147
2,180
package com.xiaojukeji.kafka.manager.common.entity.vo.common; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @author zengqiao * @date 20/8/26 */ @ApiModel(description = "账号角色信息") public class AccountRoleVO { @ApiModelProperty(value = "账号") private String username; @ApiModelProperty(value = "角色, 0:Normal, 1:RD, 2:OP") private Integer role; public AccountRoleVO(String username, Integer role) { this.username = username; this.role = role; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getRole() { return role; } public void setRole(Integer role) { this.role = role; } @Override public String toString() { return "AccountRoleVO{" + "username='" + username + '\'' + ", role=" + role + '}'; } }
447
1,374
<filename>core-lib/es6/src/main/java/def/dom/CharacterData.java package def.dom; @jsweet.lang.Extends({ChildNode.class}) public class CharacterData extends Node { public java.lang.String data; public double length; native public void appendData(java.lang.String arg); native public void deleteData(double offset, double count); native public void insertData(double offset, java.lang.String arg); native public void replaceData(double offset, double count, java.lang.String arg); native public java.lang.String substringData(double offset, double count); native public void addEventListener(java.lang.String type, EventListener listener, java.lang.Boolean useCapture); public static CharacterData prototype; public CharacterData(){} native public void remove(); native public void addEventListener(java.lang.String type, EventListener listener); native public void addEventListener(java.lang.String type, EventListenerObject listener, java.lang.Boolean useCapture); native public void addEventListener(java.lang.String type, EventListenerObject listener); }
310
589
package rocks.inspectit.server.dao.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import rocks.inspectit.server.dao.HttpTimerDataDao; import rocks.inspectit.shared.all.communication.data.HttpTimerData; import rocks.inspectit.shared.all.indexing.IIndexQuery; import rocks.inspectit.shared.cs.indexing.aggregation.impl.HttpTimerDataAggregator; import rocks.inspectit.shared.cs.indexing.query.factory.impl.HttpTimerDataQueryFactory; /** * Provides <code>HttpTimerData</code> information from the CMR internal in memory buffer. Fork&join * isn't used, because only one HTTP data per invocation is expected. * * @author <NAME> * */ @Repository public class BufferHttpTimerDataDaoImpl extends AbstractBufferDataDao<HttpTimerData> implements HttpTimerDataDao { /** * Index query factory. */ @Autowired private HttpTimerDataQueryFactory<IIndexQuery> httpDataQueryFactory; /** * {@inheritDoc} */ @Override public List<HttpTimerData> getAggregatedHttpTimerData(HttpTimerData httpData, boolean includeRequestMethod) { IIndexQuery query = httpDataQueryFactory.getFindAllHttpTimersQuery(httpData, null, null); return super.executeQuery(query, new HttpTimerDataAggregator(true, includeRequestMethod), false); } /** * {@inheritDoc} */ @Override public List<HttpTimerData> getAggregatedHttpTimerData(HttpTimerData httpData, boolean includeRequestMethod, Date fromDate, Date toDate) { IIndexQuery query = httpDataQueryFactory.getFindAllHttpTimersQuery(httpData, fromDate, toDate); return super.executeQuery(query, new HttpTimerDataAggregator(true, includeRequestMethod), false); } /** * {@inheritDoc} */ @Override public List<HttpTimerData> getTaggedAggregatedHttpTimerData(HttpTimerData httpData, boolean includeRequestMethod) { IIndexQuery query = httpDataQueryFactory.getFindAllTaggedHttpTimersQuery(httpData, null, null); return super.executeQuery(query, new HttpTimerDataAggregator(false, includeRequestMethod), false); } /** * {@inheritDoc} */ @Override public List<HttpTimerData> getTaggedAggregatedHttpTimerData(HttpTimerData httpData, boolean includeRequestMethod, Date fromDate, Date toDate) { IIndexQuery query = httpDataQueryFactory.getFindAllTaggedHttpTimersQuery(httpData, fromDate, toDate); return super.executeQuery(query, new HttpTimerDataAggregator(false, includeRequestMethod), false); } }
777
316
/* * Copyright 2014 Frakbot (<NAME> and <NAME>) * * 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 net.frakbot.creditsrolldemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.SeekBar; import android.widget.Toast; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.animation.ValueAnimator; import net.frakbot.creditsroll.CreditsRollView; public class MainActivity extends Activity implements SeekBar.OnSeekBarChangeListener { private static final float SCROLL_ANIM_DURATION = 30000; // [ms] = 30 s private CreditsRollView mCreditsRollView; private boolean mScrolling; private SeekBar mSeekBar; private ValueAnimator mScrollAnimator; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSeekBar = (SeekBar) findViewById(R.id.seekbar); mSeekBar.setOnSeekBarChangeListener(this); mCreditsRollView = (CreditsRollView) findViewById(R.id.creditsroll); mCreditsRollView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mScrolling) { animateScroll(); } else { stopScrollAnimation(); } } }); Toast.makeText(this, "Tap the empty space to animate the credits roll, or use the scrollbar", Toast.LENGTH_SHORT) .show(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mCreditsRollView.setScrollPosition(progress / 100000f); // We have increments of 1/100000 % } @Override public void onStartTrackingTouch(SeekBar seekBar) { if (mScrolling) { stopScrollAnimation(); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { // Don't care } private void animateScroll() { mScrolling = true; mScrollAnimator = ObjectAnimator.ofInt(mSeekBar, "progress", mSeekBar.getProgress(), mSeekBar.getMax()); mScrollAnimator.setDuration( (long) (SCROLL_ANIM_DURATION * (1 - (float) mSeekBar.getProgress() / mSeekBar.getMax()))); mScrollAnimator.setInterpolator(new LinearInterpolator()); mScrollAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { // Don't care } @Override public void onAnimationEnd(Animator animation) { mScrolling = false; } @Override public void onAnimationCancel(Animator animation) { // Don't care } @Override public void onAnimationRepeat(Animator animation) { // Don't care } }); mScrollAnimator.start(); } private void stopScrollAnimation() { if (mScrollAnimator != null) { mScrollAnimator.cancel(); mScrollAnimator = null; } } }
1,583
312
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "c-interface/c-interface.h" //-------------------------------------- Console functions ConsoleMethod(GuiMessageVectorCtrl, attach, bool, 3, 3, "( aVector ) Make this gui control display messages from the specified MessageVector.\n" "@param aVector A previously created messageVector instance.\n" "@return No return value") { MessageVector* pMV = NULL; Sim::findObject(argv[2], pMV); if (pMV == NULL) { Con::errorf(ConsoleLogEntry::General, "Could not find MessageVector: %s", argv[2]); return false; } return object->attach(pMV); } ConsoleMethod(GuiMessageVectorCtrl, detach, void, 2, 2, "() Stop listening to messages from the MessageVector this control was previously attached to.\n" "@return No return value") { if (object->isAttached() == false) { Con::warnf(ConsoleLogEntry::General, "GuiMessageVectorCtrl: double detach"); return; } object->detach(); } extern "C"{ DLL_PUBLIC GuiMessageVectorCtrl* GuiMessageVectorCtrlCreateInstance() { return new GuiMessageVectorCtrl(); } DLL_PUBLIC S32 GuiMessageVectorCtrlGetLineSpacing(GuiMessageVectorCtrl* ctrl) { return ctrl->getLineSpacingPixels(); } DLL_PUBLIC void GuiMessageVectorCtrlSetLineSpacing(GuiMessageVectorCtrl* ctrl, S32 spacing) { ctrl->setLineSpacingPixels(spacing); } DLL_PUBLIC S32 GuiMessageVectorCtrlGetLineContinuedIndex(GuiMessageVectorCtrl* ctrl) { return ctrl->getLineContinuationIndent(); } DLL_PUBLIC void GuiMessageVectorCtrlSetLineContinuedIndex(GuiMessageVectorCtrl* ctrl, S32 index) { ctrl->setLineContinuationIndent(index); } DLL_PUBLIC const char* GuiMessageVectorCtrlGetAllowedMatches(GuiMessageVectorCtrl* ctrl, S32 index) { return ctrl->getAllowedMatches(index); } DLL_PUBLIC void GuiMessageVectorCtrlSetAllowedMatches(GuiMessageVectorCtrl* ctrl, S32 index, const char* match) { ctrl->setAllowedMatches(index, match); } DLL_PUBLIC void GuiMessageVectorCtrlGetMatchColor(GuiMessageVectorCtrl* ctrl, CInterface::ColorParam* outColor) { *outColor = ctrl->getMatchColor(); } DLL_PUBLIC void GuiMessageVectorCtrlSetMatchColor(GuiMessageVectorCtrl* ctrl, CInterface::ColorParam color) { ctrl->setMatchColor(color); } DLL_PUBLIC S32 GuiMessageVectorCtrlGetMaxColorIndex(GuiMessageVectorCtrl* ctrl) { return ctrl->getMaxColorIndex(); } DLL_PUBLIC void GuiMessageVectorCtrlSetMaxColorIndex(GuiMessageVectorCtrl* ctrl, S32 index) { ctrl->setMaxColorIndex(index); } DLL_PUBLIC bool GuiMessageVectorCtrlAttach(GuiMessageVectorCtrl* ctrl, MessageVector* MV) { return ctrl->attach(MV); } DLL_PUBLIC void GuiMessageVectorCtrlDetach(GuiMessageVectorCtrl* ctrl) { ctrl->detach(); } }
1,319
937
package com.oath.cyclops.types.futurestream; import static com.oath.cyclops.types.futurestream.NullValue.NULL; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.BiFunction; import java.util.function.Predicate; import java.util.stream.Stream; import cyclops.reactive.ReactiveSeq; import cyclops.data.tuple.Tuple; import cyclops.data.tuple.Tuple2; import com.oath.cyclops.internal.react.stream.CloseableIterator; public class LazyFutureStreamFunctions { /** * Zip two streams into one. * <p> * <code> * // (tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) * Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")) * </code> */ public static <T1, T2> ReactiveSeq<Tuple2<T1, T2>> zip(final Stream<T1> left, final Stream<? extends T2> right) { return zip(left, right, Tuple::tuple); } /** * Zip two streams into one using a {@link BiFunction} to produce resulting * values. * <p> * <code> * // ("1:a", "2:b", "3:c") * Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (i, s) -&gt; i + ":" + s) * </code> */ public static <T1, T2, R> ReactiveSeq<R> zip(final Stream<T1> left, final Stream<T2> right, final BiFunction<? super T1, ? super T2, ? extends R> zipper) { final Iterator<T1> it1 = left.iterator(); final Iterator<T2> it2 = right.iterator(); class Zip implements Iterator<R> { @Override public boolean hasNext() { if (!it1.hasNext()) { close(it2); } if (!it2.hasNext()) { close(it1); } return it1.hasNext() && it2.hasNext(); } @Override public R next() { return zipper.apply(it1.next(), it2.next()); } } return ReactiveSeq.fromIterator(new Zip()) .onClose(() -> { left.close(); right.close(); }); } static void close(final Iterator it) { if (it instanceof CloseableIterator) { ((CloseableIterator) it).close(); } } /** * Returns a stream limited to all elements for which a predicate evaluates * to <code>true</code>. * <p> * <code> * // (1, 2) * Seq.of(1, 2, 3, 4, 5).limitWhile(i -&gt; i &lt; 3) * </code> */ public static <T> ReactiveSeq<T> takeWhile(final Stream<T> stream, final Predicate<? super T> predicate) { return takeUntil(stream, predicate.negate()); } /** * Returns a stream ed to all elements for which a predicate evaluates to * <code>true</code>. * <p> * <code> * // (1, 2) * Seq.of(1, 2, 3, 4, 5).limitUntil(i -&gt; i == 3) * </code> */ @SuppressWarnings("unchecked") public static <T> ReactiveSeq<T> takeUntil(final Stream<T> stream, final Predicate<? super T> predicate) { final Iterator<T> it = stream.iterator(); class LimitUntil implements Iterator<T> { T next = (T) NULL; boolean test = false; void test() { if (!test && next == NULL && it.hasNext()) { next = it.next(); if (test = predicate.test(next)) { next = (T) NULL; close(it); // need to close any open queues } } } @Override public boolean hasNext() { test(); return next != NULL; } @Override public T next() { if (next == NULL) throw new NoSuchElementException(); try { return next; } finally { next = (T) NULL; } } } return ReactiveSeq.fromIterator(new LimitUntil()) .onClose(() -> { stream.close(); }); } }
2,114
349
<gh_stars>100-1000 /* Copyright 2018 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. */ package com.amazon.ask.response; import com.amazon.ask.model.interfaces.display.PlainText; import com.amazon.ask.model.interfaces.display.TextContent; /** * A helper to assist in building {@link PlainText} content. */ public class PlainTextContentContentHelper extends TextContentHelper { /** * In place to prevent instantiation. */ PlainTextContentContentHelper() { } /** * Builds an instance of TextContent. * @return {@link TextContent}. */ public TextContent build() { return TextContent.builder() .withPrimaryText(primaryText != null ? PlainText.builder().withText(primaryText).build() : null) .withSecondaryText(secondaryText != null ? PlainText.builder().withText(secondaryText).build() : null) .withTertiaryText(tertiaryText != null ? PlainText.builder().withText(tertiaryText).build() : null) .build(); } }
509
1,514
#include "global.h" #include "ScreenMiniMenu.h" #include "ScreenManager.h" #include "GameConstantsAndTypes.h" #include "ThemeManager.h" #include "ScreenDimensions.h" #include "GameState.h" #include "FontCharAliases.h" #include "OptionRowHandler.h" #include "PrefsManager.h" void PrepareToLoadScreen( const RString &sScreenName ); void FinishedLoadingScreen(); AutoScreenMessage( SM_GoToOK ); AutoScreenMessage( SM_GoToCancel ); bool ScreenMiniMenu::s_bCancelled = false; int ScreenMiniMenu::s_iLastRowCode = -1; vector<int> ScreenMiniMenu::s_viLastAnswers; // Hooks for profiling void PrepareToLoadScreen( const RString &sScreenName ) {} void FinishedLoadingScreen() {} // Settings: namespace { const MenuDef* g_pMenuDef = nullptr; ScreenMessage g_SendOnOK; ScreenMessage g_SendOnCancel; }; void ScreenMiniMenu::MiniMenu( const MenuDef* pDef, ScreenMessage SM_SendOnOK, ScreenMessage SM_SendOnCancel, float fX, float fY ) { PrepareToLoadScreen( pDef->sClassName ); g_pMenuDef = pDef; g_SendOnOK = SM_SendOnOK; g_SendOnCancel = SM_SendOnCancel; SCREENMAN->AddNewScreenToTop( pDef->sClassName ); Screen *pNewScreen = SCREENMAN->GetTopScreen(); pNewScreen->SetXY( fX, fY ); FinishedLoadingScreen(); } REGISTER_SCREEN_CLASS( ScreenMiniMenu ); void ScreenMiniMenu::Init() { if( PREFSMAN->m_iArcadeOptionsNavigation ) SetNavigation( NAV_THREE_KEY_MENU ); ScreenOptions::Init(); } void ScreenMiniMenu::BeginScreen() { ASSERT( g_pMenuDef != nullptr ); LoadMenu( g_pMenuDef ); m_SMSendOnOK = g_SendOnOK; m_SMSendOnCancel = g_SendOnCancel; g_pMenuDef = nullptr; ScreenOptions::BeginScreen(); /* HACK: An OptionRow exits if a screen is set. ScreenMiniMenu is always * pushed, so we don't set screens to load. Set a dummy screen, so * ScreenOptions::GetNextScreenForSelection will know to move on. */ m_sNextScreen = "xxx"; } void ScreenMiniMenu::LoadMenu( const MenuDef* pDef ) { m_vMenuRows = pDef->rows; s_viLastAnswers.resize( m_vMenuRows.size() ); // Convert from m_vMenuRows to vector<OptionRowDefinition> vector<OptionRowHandler*> vHands; for( unsigned r=0; r<m_vMenuRows.size(); r++ ) { const MenuRowDef &mr = m_vMenuRows[r]; OptionRowHandler *pHand = OptionRowHandlerUtil::MakeSimple( mr ); vHands.push_back( pHand ); } ScreenOptions::InitMenu( vHands ); } void ScreenMiniMenu::AfterChangeValueOrRow( PlayerNumber pn ) { ScreenOptions::AfterChangeValueOrRow( pn ); vector<PlayerNumber> vpns; FOREACH_PlayerNumber( p ) vpns.push_back( p ); for( unsigned i=0; i<m_pRows.size(); i++ ) ExportOptions( i, vpns ); // Changing one option can affect whether other options are available. for( unsigned i=0; i<m_pRows.size(); i++ ) { const MenuRowDef &mr = m_vMenuRows[i]; if( mr.pfnEnabled ) { OptionRow &optrow = *m_pRows[i]; optrow.GetRowDef().m_vEnabledForPlayers.clear(); if( mr.pfnEnabled() ) optrow.GetRowDef().m_vEnabledForPlayers.insert( GAMESTATE->GetMasterPlayerNumber() ); } m_pRows[i]->UpdateEnabledDisabled(); } } void ScreenMiniMenu::ImportOptions( int r, const vector<PlayerNumber> &vpns ) { OptionRow &optrow = *m_pRows[r]; const MenuRowDef &mr = m_vMenuRows[r]; if( !mr.choices.empty() ) optrow.SetOneSharedSelection( mr.iDefaultChoice ); } void ScreenMiniMenu::ExportOptions( int r, const vector<PlayerNumber> &vpns ) { if( r == GetCurrentRow() ) s_iLastRowCode = m_vMenuRows[r].iRowCode; s_viLastAnswers.resize( m_vMenuRows.size() ); s_viLastAnswers[r] = m_pRows[r]->GetOneSharedSelection( true ); } void ScreenMiniMenu::HandleScreenMessage( const ScreenMessage SM ) { if( SM == SM_GoToNextScreen ) { s_bCancelled = false; SCREENMAN->PopTopScreen( m_SMSendOnOK ); return; } else if( SM == SM_GoToPrevScreen ) { s_bCancelled = true; SCREENMAN->PopTopScreen( m_SMSendOnCancel ); return; } ScreenOptions::HandleScreenMessage( SM ); } bool ScreenMiniMenu::FocusedItemEndsScreen( PlayerNumber pn ) const { return true; } /* * (c) 2003-2004 <NAME> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
1,869
1,444
<reponame>amc8391/mage<gh_stars>1000+ package mage.cards.n; import mage.MageInt; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import java.util.UUID; /** * @author TheElk801 */ public final class NyxbornMarauder extends CardImpl { public NyxbornMarauder(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT, CardType.CREATURE}, "{2}{B}{B}"); this.subtype.add(SubType.MINOTAUR); this.power = new MageInt(4); this.toughness = new MageInt(3); } private NyxbornMarauder(final NyxbornMarauder card) { super(card); } @Override public NyxbornMarauder copy() { return new NyxbornMarauder(this); } }
329
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Chavanatte","dpt":"Territoire de Belfort","inscrits":136,"abs":34,"votants":102,"blancs":6,"nuls":1,"exp":95,"res":[{"panneau":"2","voix":64},{"panneau":"1","voix":31}]}
91
335
<reponame>Safal08/Hacktoberfest-1<filename>J/Jab_noun.json { "word": "Jab", "definitions": [ "A quick, sharp blow, especially with the fist.", "A hypodermic injection, especially a vaccination.", "A sharp, painful sensation or feeling." ], "parts-of-speech": "Noun" }
129
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-pm2q-hpwc-7mr9", "modified": "2022-05-01T18:21:36Z", "published": "2022-05-01T18:21:36Z", "aliases": [ "CVE-2007-4234" ], "details": "Unspecified vulnerability in Camera Life before 2.6 allows remote attackers to download private photos via unspecified vectors associated with the names of the photos. NOTE: some of these details are obtained from third party information.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2007-4234" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/35839" }, { "type": "WEB", "url": "http://fdcl.svn.sourceforge.net/viewvc/*checkout*/fdcl/trunk/Changelog" }, { "type": "WEB", "url": "http://secunia.com/advisories/26319" }, { "type": "WEB", "url": "http://sourceforge.net/forum/forum.php?forum_id=721006" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
511
9,701
from typing import Dict, Text, Any import pytest from rasa.graph_components.providers.training_tracker_provider import ( TrainingTrackerProvider, ) from rasa.engine.graph import ExecutionContext from rasa.engine.storage.resource import Resource from rasa.engine.storage.storage import ModelStorage from rasa.shared.core.domain import Domain from rasa.shared.core.generator import TrackerWithCachedStates from rasa.shared.core.training_data.story_reader.yaml_story_reader import ( YAMLStoryReader, ) from rasa.shared.core.training_data.structures import StoryGraph @pytest.mark.parametrize( "config, expected_trackers", [ ({}, 507), ({"augmentation_factor": 0}, 7), ({"use_story_concatenation": False}, 7), ( { "remove_duplicates": True, "unique_last_num_states": None, "augmentation_factor": 50, "tracker_limit": None, "use_story_concatenation": True, "debug_plots": False, }, 507, ), ], ) def test_generating_trackers( default_model_storage: ModelStorage, default_execution_context: ExecutionContext, config: Dict[Text, Any], expected_trackers: int, ): reader = YAMLStoryReader() steps = reader.read_from_file("data/test_yaml_stories/stories.yml") component = TrainingTrackerProvider.create( {**TrainingTrackerProvider.get_default_config(), **config}, default_model_storage, Resource("xy"), default_execution_context, ) trackers = component.provide(story_graph=StoryGraph(steps), domain=Domain.empty()) assert len(trackers) == expected_trackers assert all(isinstance(t, TrackerWithCachedStates) for t in trackers)
722
386
#include "util/tc_common.h" #include <thread> #include "gtest/gtest.h" #include "test_server.h" using namespace tars; static TC_Endpoint TEST_HOST_EP("tcp -h 127.0.0.1 -p 19089 -t 10000"); static TC_Endpoint LINE_HOST_EP("tcp -h 127.0.0.1 -p 19099 -t 10000"); static TC_Endpoint QUEUE_HOST_EP("tcp -h 127.0.0.1 -p 19019 -t 10000"); static TC_Endpoint UDP_HOST_EP("udp -h 127.0.0.1 -p 18085 -t 10000"); class UtilEpollServerTest : public testing::Test { public: //添加日志 static void SetUpTestCase() { } static void TearDownTestCase() { } virtual void SetUp() { } virtual void TearDown() //TEST跑完之后会执行TearDown { } void startServer(MyTcpServer &server, TC_EpollServer::SERVER_OPEN_COROUTINE openCoroutine) { server.initialize(); server._epollServer->setOpenCoroutine(openCoroutine); server.bindUdp(UDP_HOST_EP.toString()); server.bindTcp(TEST_HOST_EP.toString(), 10); server.bindTcpLine(LINE_HOST_EP.toString(), 10); server.bindTcpQueue(QUEUE_HOST_EP.toString()); server.waitForShutdown(); } void startManualServer(MyTcpServer &server, TC_EpollServer::SERVER_OPEN_COROUTINE openCoroutine) { server.initialize(); server._epollServer->setOpenCoroutine(openCoroutine); server.bindManualTcp(TEST_HOST_EP.toString(), 10); server.waitForShutdown(); } void stopServer(MyTcpServer &server) { server.terminate(); } protected: }; TEST_F(UtilEpollServerTest, RunUdp) { for(int i = 0; i <= TC_EpollServer::NET_THREAD_MERGE_HANDLES_CO; i++) { MyTcpServer server; startServer(server, (TC_EpollServer::SERVER_OPEN_COROUTINE)i); TC_UDPClient client(UDP_HOST_EP.getHost(), UDP_HOST_EP.getPort(), UDP_HOST_EP.getTimeout()); int iRet = 0; char recvBuffer[1024]; size_t recvLenth = 1024; for (int i = 0; i < 10; i++) { iRet = client.sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet == 0); ASSERT_TRUE(string(recvBuffer, recvLenth) == "abc"); } stopServer(server); } } TEST_F(UtilEpollServerTest, RunTcp) { for(int i = 0; i <= TC_EpollServer::NET_THREAD_MERGE_HANDLES_CO; i++) { MyTcpServer server; startServer(server, (TC_EpollServer::SERVER_OPEN_COROUTINE)i); TC_TCPClient client(TEST_HOST_EP.getHost(), TEST_HOST_EP.getPort(), TEST_HOST_EP.getTimeout()); int iRet = 0; char recvBuffer[1024]; size_t recvLenth = 1024; for (int i = 0; i < 10; i++) { iRet = client.sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet == 0); ASSERT_TRUE(string(recvBuffer, recvLenth) == "abc"); } stopServer(server); } } TEST_F(UtilEpollServerTest, RunEnableManualListen) { int i = 0; for(int i = 0; i <= TC_EpollServer::NET_THREAD_MERGE_HANDLES_CO; i++) { MyTcpServer server; startManualServer(server, (TC_EpollServer::SERVER_OPEN_COROUTINE)i); TC_TCPClient client(TEST_HOST_EP.getHost(), TEST_HOST_EP.getPort(), TEST_HOST_EP.getTimeout()); int iRet = 0; char recvBuffer[1024]; size_t recvLenth = 1024; iRet = client.sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet == -6); server.startManualListen(); iRet = client.sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet == 0); ASSERT_TRUE(string(recvBuffer, recvLenth) == "abc"); server.cancelManualListen(); iRet = client.sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet != TC_ClientSocket::EM_SUCCESS); server.startManualListen(); iRet = client.sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet == 0); ASSERT_TRUE(string(recvBuffer, recvLenth) == "abc"); stopServer(server); } } TEST_F(UtilEpollServerTest, RunLine) { for(int i = 0; i <= TC_EpollServer::NET_THREAD_MERGE_HANDLES_CO; i++) { MyTcpServer server; startServer(server, (TC_EpollServer::SERVER_OPEN_COROUTINE) i); TC_TCPClient client(LINE_HOST_EP.getHost(), LINE_HOST_EP.getPort(), LINE_HOST_EP.getTimeout()); int iRet = 0; string sendBuffer(1024 * 1024 * 2, 'a'); string recvBuffer; iRet = client.sendRecvLine((sendBuffer + "\r\n").c_str(), sendBuffer.size() + 2, recvBuffer); ASSERT_TRUE(iRet == 0); ASSERT_TRUE(recvBuffer == sendBuffer + "\r\n"); stopServer(server); } } TEST_F(UtilEpollServerTest, AcceptCallback) { for(int i = 0; i <= TC_EpollServer::NET_THREAD_MERGE_HANDLES_CO; i++) { MyTcpServer server; startServer(server, (TC_EpollServer::SERVER_OPEN_COROUTINE)i); bool accept = false; server._epollServer->setOnAccept([&](TC_EpollServer::Connection *conn) { accept = true; }); TC_TCPClient client(TEST_HOST_EP.getHost(), TEST_HOST_EP.getPort(), TEST_HOST_EP.getTimeout()); int iRet = 0; char recvBuffer[1024]; size_t recvLenth = 1024; iRet = client.sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet == 0); ASSERT_TRUE(string(recvBuffer, recvLenth) == "abc"); TC_Common::msleep(50); ASSERT_TRUE(accept); stopServer(server); } } TEST_F(UtilEpollServerTest, ConnectionMax) { for(int i = 0; i <= TC_EpollServer::NET_THREAD_MERGE_HANDLES_CO; i++) { MyTcpServer server; startServer(server, (TC_EpollServer::SERVER_OPEN_COROUTINE) i); vector<TC_TCPClient *> conns; //注意服务连接数是10个 for (int i = 0; i < 10; i++) { TC_TCPClient *client = new TC_TCPClient(TEST_HOST_EP.getHost(), TEST_HOST_EP.getPort(), TEST_HOST_EP.getTimeout()); int iRet = 0; char recvBuffer[1024]; size_t recvLenth = 1024; iRet = client->sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet == 0); ASSERT_TRUE(string(recvBuffer, recvLenth) == "abc"); conns.push_back(client); } TC_TCPClient client(TEST_HOST_EP.getHost(), TEST_HOST_EP.getPort(), TEST_HOST_EP.getTimeout()); int iRet = 0; char recvBuffer[1024]; size_t recvLenth = 1024; iRet = client.sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet != 0); for (size_t i = 0; i < conns.size(); i++) { delete conns[i]; } stopServer(server); } } TEST_F(UtilEpollServerTest, QueueMode) { for(int i = 0; i <= TC_EpollServer::NET_THREAD_MERGE_HANDLES_CO; i++) { MyTcpServer server; startServer(server, (TC_EpollServer::SERVER_OPEN_COROUTINE) i); vector<TC_TCPClient *> conns; //注意服务连接数是10个 for (int i = 0; i < 10; i++) { TC_TCPClient *client = new TC_TCPClient(QUEUE_HOST_EP.getHost(), QUEUE_HOST_EP.getPort(), QUEUE_HOST_EP.getTimeout()); conns.push_back(client); } for (auto client : conns) { string lastBuff; for (int i = 0; i < 10; i++) { int iRet = 0; char recvBuffer[1024] = {0}; size_t recvLenth = 1024; iRet = client->sendRecv("abc", 3, recvBuffer, recvLenth); ASSERT_TRUE(iRet == 0); if (!lastBuff.empty()) { ASSERT_TRUE(lastBuff == string(recvBuffer, recvLenth)); } lastBuff = string(recvBuffer, recvLenth); } } for (size_t i = 0; i < conns.size(); i++) { delete conns[i]; } stopServer(server); } }
3,502
23,439
<gh_stars>1000+ /* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * 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.alibaba.nacos.naming.core.v2.upgrade; import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteDelayTaskEngine; /** * Upgrade checker for self-node to judge whether current node is ready to upgrade. * * @author xiweng.yy */ public interface SelfUpgradeChecker { /** * Get the check type of this self upgrade checker. * * @return type */ String checkType(); /** * Judge whether current node is ready to upgrade. * * @param serviceManager service manager for v1 mode. * @param taskEngine double write task engine * @return {@code true} if current node is ready to upgrade, otherwise {@code false} */ boolean isReadyToUpgrade(ServiceManager serviceManager, DoubleWriteDelayTaskEngine taskEngine); }
463
1,016
<reponame>peter-ls/kylo<gh_stars>1000+ package com.thinkbiganalytics.kylo.nifi.teradata.tdch.core.controllerservice; /*- * #%L * kylo-nifi-teradata-tdch-core * %% * Copyright (C) 2017 - 2018 ThinkBig Analytics, a Teradata Company * %% * 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. * #L% */ import com.thinkbiganalytics.kylo.nifi.teradata.tdch.api.TdchConnectionService; import org.apache.nifi.controller.AbstractControllerService; /** * A connection service (for testing) that implements {@link TdchConnectionService}<br> * This configuration would be similar to a normal deployment */ public class DevTdchConnectionService extends AbstractControllerService implements TdchConnectionService { @Override public String getJdbcDriverClassName() { return "com.teradata.jdbc.TeraDriver"; } @Override public String getJdbcConnectionUrl() { return "jdbc:teradata://localhost"; } @Override public String getUserName() { return "dbc"; } @Override public String getPassword() { return "<PASSWORD>"; } @Override public String getTdchJarPath() { return "/usr/lib/tdch/1.5/lib/teradata-connector-1.5.4.jar"; } @Override public String getTdchLibraryJarsPath() { return "/usr/hdp/current/hive-client/conf"; } @Override public String getTdchHadoopClassPath() { return "/usr/hdp/current/hive-client/lib"; } }
681
5,278
<gh_stars>1000+ { "name": "granim", "description": "Create fluid and interactive gradients animations with this small js library.", "main": "index.js", "authors": [ "<NAME>", "<NAME> <<EMAIL>> (http://pranay.gp)" ], "license": "MIT", "keywords": [ "gradient", "animation" ], "homepage": "https://sarcadass.github.io/granim.js/", "moduleType": [ "globals", "node" ], "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ] }
222
539
<filename>java/core/src/main/java/org/bondlib/FloatingPointHelper.java // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package org.bondlib; /** * Provides implementations of floating-point equality and hashing that take * primitives and are compatible with those in {@link Float} and * {@link Double}. These functions are used by generated and library code. */ public final class FloatingPointHelper { // prevent instantiation private FloatingPointHelper() { } /** * Implements the semantics of {@link Float#equals(Object)} for two * primitive floats. * * @param a single-precision value * @param b single-precision value * @return true if equal, false if not */ public static boolean floatEquals(float a, float b) { return Float.floatToIntBits(a) == Float.floatToIntBits(b); } /** * Implements the semantics of {@link Double#equals(Object)} for two * primitive doubles. * * @param a double-precision value * @param b double-precision value * @return true if equal, false if not */ public static boolean doubleEquals(double a, double b) { return Double.doubleToLongBits(a) == Double.doubleToLongBits(b); } /** * Computes a hash code of a single-precision floating point value. * Identical to {@link Float#hashCode(float)}, which was introduced in Java * 8. Once Bond targets Java 8, this function should be replaced with that * one. * * @param v single-precision value * @return hash code */ public static int floatHashCode(float v) { return Float.floatToIntBits(v); } /** * Computes a hash code of a double-precision floating point value. * Identical to {@link Double#hashCode(double)}, which was introduced in * Java 8. Once Bond targets Java 8, this function should be replaced with * that one. * * @param v double-precision value * @return hash code */ public static int doubleHashCode(double v) { long bits = Double.doubleToLongBits(v); return (int) (bits ^ (bits >>> 32)); } }
776
696
<reponame>hwang-pku/Strata /* * Copyright (C) 2021 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.loader.csv; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.BUY_SELL_FIELD; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.CONTRACT_SIZE_FIELD; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.CURRENCY_FIELD; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.PRICE_FIELD; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.QUANTITY_FIELD; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.SECURITY_ID_FIELD; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.SECURITY_ID_SCHEME_FIELD; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.TICK_SIZE_FIELD; import static com.opengamma.strata.loader.csv.CsvLoaderColumns.TICK_VALUE_FIELD; import java.util.List; import java.util.Set; import com.google.common.collect.ImmutableSet; import com.opengamma.strata.collect.io.CsvOutput; import com.opengamma.strata.product.GenericSecurityTrade; import com.opengamma.strata.product.SecurityPriceInfo; /** * Handles the CSV file format for Generic Security trades. */ public class GenericSecurityTradeCsvPlugin implements TradeCsvWriterPlugin<GenericSecurityTrade> { /** * The singleton instance of the plugin. */ public static final GenericSecurityTradeCsvPlugin INSTANCE = new GenericSecurityTradeCsvPlugin(); /** The headers. */ private static final ImmutableSet<String> HEADERS = ImmutableSet.of( SECURITY_ID_SCHEME_FIELD, SECURITY_ID_FIELD, BUY_SELL_FIELD, QUANTITY_FIELD, PRICE_FIELD, TICK_SIZE_FIELD, CURRENCY_FIELD, TICK_VALUE_FIELD, CONTRACT_SIZE_FIELD); @Override public Set<String> headers(List<GenericSecurityTrade> trades) { return HEADERS; } @Override public void writeCsv(CsvOutput.CsvRowOutputWithHeaders csv, GenericSecurityTrade trade) { CsvWriterUtils.writeSecurityQuantityTrade(csv, trade); SecurityPriceInfo securityPriceInfo = trade.getProduct().getInfo().getPriceInfo(); csv.writeCell(TICK_SIZE_FIELD, securityPriceInfo.getTickSize()); csv.writeCell(CURRENCY_FIELD, securityPriceInfo.getTickValue().getCurrency()); csv.writeCell(TICK_VALUE_FIELD, securityPriceInfo.getTickValue().getAmount()); csv.writeCell(CONTRACT_SIZE_FIELD, securityPriceInfo.getContractSize()); csv.writeNewLine(); } @Override public String getName() { return GenericSecurityTrade.class.getSimpleName(); } @Override public Set<Class<?>> supportedTradeTypes() { return ImmutableSet.of(GenericSecurityTrade.class); } }
959
488
#include <stdio.h> #include <omp.h> int main() { int i,j; // int innerreps = 100; #pragma omp parallel private(j) { // for (j=0; j<innerreps; j++) { #pragma omp for schedule(static,2) for (i=0; i<32; i++) { printf ("thread %d is executing %d \n",omp_get_thread_num(),i); // delay(500); } } } return 0; }
199
5,250
/* 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.activiti.engine.test.api.repository; import java.util.HashSet; import java.util.List; import java.util.Set; import org.activiti.engine.impl.test.PluggableFlowableTestCase; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.DeploymentProperties; import org.flowable.engine.repository.DeploymentQuery; /** * @author <NAME> */ public class DeploymentCategoryTest extends PluggableFlowableTestCase { public void testDeploymentCategory() { String noCategoryDeploymentId = null; String deploymentOneId = null; String deploymentTwoV1Id = null; String deploymentTwoV2Id = null; String deploymentTwoNoCategory = null; try { noCategoryDeploymentId = repositoryService .createDeployment() .name("0") .addClasspathResource("org/activiti/engine/test/service/oneTaskProcess.bpmn20.xml") .deploymentProperty(DeploymentProperties.DEPLOY_AS_FLOWABLE5_PROCESS_DEFINITION, Boolean.TRUE) .deploy() .getId(); deploymentOneId = repositoryService .createDeployment() .name("1") .category("one") .addClasspathResource("org/activiti/engine/test/repository/one.bpmn20.xml") .deploymentProperty(DeploymentProperties.DEPLOY_AS_FLOWABLE5_PROCESS_DEFINITION, Boolean.TRUE) .deploy() .getId(); deploymentTwoV1Id = repositoryService .createDeployment() .name("2v1") .category("two") .addClasspathResource("org/activiti/engine/test/repository/two.bpmn20.xml") .deploymentProperty(DeploymentProperties.DEPLOY_AS_FLOWABLE5_PROCESS_DEFINITION, Boolean.TRUE) .deploy() .getId(); deploymentTwoV2Id = repositoryService .createDeployment() .name("2v2") .category("two") .addClasspathResource("org/activiti/engine/test/repository/two.bpmn20.xml") .deploymentProperty(DeploymentProperties.DEPLOY_AS_FLOWABLE5_PROCESS_DEFINITION, Boolean.TRUE) .deploy() .getId(); DeploymentQuery query = repositoryService.createDeploymentQuery(); assertEquals(4, query.list().size()); Set<String> deploymentNames = getDeploymentNames(repositoryService .createDeploymentQuery() .deploymentCategory("one") .list()); Set<String> expectedDeploymentNames = new HashSet<String>(); expectedDeploymentNames.add("1"); assertEquals(expectedDeploymentNames, deploymentNames); deploymentNames = getDeploymentNames(repositoryService .createDeploymentQuery() .deploymentCategoryNotEquals("two") .list()); expectedDeploymentNames.add("0"); assertEquals(expectedDeploymentNames, deploymentNames); deploymentTwoNoCategory = repositoryService .createDeployment() .name("noCategory") .addClasspathResource("org/activiti/engine/test/repository/two.bpmn20.xml") .deploymentProperty(DeploymentProperties.DEPLOY_AS_FLOWABLE5_PROCESS_DEFINITION, Boolean.TRUE) .deploy() .getId(); Deployment deploymentNoCategory = repositoryService.createDeploymentQuery().deploymentId(deploymentTwoNoCategory).singleResult(); assertNull(deploymentNoCategory.getCategory()); repositoryService.setDeploymentCategory(deploymentTwoNoCategory, "newCategory"); deploymentNoCategory = repositoryService.createDeploymentQuery().deploymentId(deploymentTwoNoCategory).singleResult(); assertEquals("newCategory", deploymentNoCategory.getCategory()); } finally { if (noCategoryDeploymentId != null) undeploy(noCategoryDeploymentId); if (deploymentOneId != null) undeploy(deploymentOneId); if (deploymentTwoV1Id != null) undeploy(deploymentTwoV1Id); if (deploymentTwoV2Id != null) undeploy(deploymentTwoV2Id); if (deploymentTwoNoCategory != null) undeploy(deploymentTwoNoCategory); } } private Set<String> getDeploymentNames(List<Deployment> deployments) { Set<String> deploymentNames = new HashSet<String>(); for (Deployment deployment : deployments) { deploymentNames.add(deployment.getName()); } return deploymentNames; } private void undeploy(String deploymentId) { try { repositoryService.deleteDeployment(deploymentId); } catch (Exception e) { e.printStackTrace(); } } }
2,592
540
<gh_stars>100-1000 /* ---------------------------------------------------------------------------- ** Copyright (c) 2016 <NAME>, All Rights Reserved. ** ** EnumContainer.h ** --------------------------------------------------------------------------*/ #pragma once #include "EnumBase.h" #include "Variant.h" #include <unordered_map> namespace ursine { namespace meta { template<typename EnumType> class EnumContainer : public EnumBase { public: typedef std::initializer_list<std::pair<std::string, EnumType>> Initializer; typedef std::unordered_map<std::string, EnumType> Table; EnumContainer(const std::string &name, const Initializer &initializer); EnumContainer( const std::string &name, const Initializer &initializer, TypeID owner ); Type GetType(void) const override; Type GetUnderlyingType(void) const override; const std::vector<std::string> &GetKeys(void) const override; std::vector<Variant> GetValues(void) const override; std::string GetKey(const Argument &value) const override; Variant GetValue(const std::string &key) const override; private: Table m_keyToValue; std::vector<std::string> m_keys; }; } } #include "Impl/EnumContainer.hpp"
592
4,071
<filename>xdl/ps-plus/ps-plus/client/udf.cc /* Copyright (C) 2016-2018 Alibaba Group Holding 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. ==============================================================================*/ #include "udf.h" namespace ps { namespace client { namespace { // Some constant about hash algorithm const unsigned long long kP = 98765431; const unsigned long long kP2 = kP * kP; const unsigned long long kHash0 = 19940319; const unsigned long long kHash1 = kP - kHash0; } void UdfChain::CalculateHash() { hash_ = kHash0 * kP + std::hash<std::string>()("__INPUT__"); node_ids_[nullptr] = 0; nodes_.push_back(nullptr); unsigned long long output_hash = 0; unsigned long long output_hash_offset = 1; for (const auto& data : datas_) { output_hash = output_hash * kP2 + CollectNode(data); output_hash_offset *= kP2; } hash_ = hash_ * kP + datas_.size() + kHash1; hash_ = hash_ * output_hash_offset + output_hash; } // return the hash of {nodex_inputx_node, nodex_inputx_index} unsigned long long UdfChain::CollectNode(const UdfData& data) { UdfData::UdfNode* node = data.node_.get(); auto iter = node_ids_.find(node); if (node_ids_.find(node) != node_ids_.end()) { return iter->second * kP + data.id_; } else { int64_t my_hash = (node->inputs_.size() + kHash0) * kP + std::hash<std::string>()(node->udf_name_); int64_t my_hash_offset = kP2; for (const auto& child : node->inputs_) { my_hash = my_hash * kP2 + CollectNode(child); my_hash_offset *= kP2; } hash_ = hash_ * my_hash_offset + my_hash; unsigned long long ret = nodes_.size() * kP + data.id_; node_ids_[node] = nodes_.size(); nodes_.push_back(node); return ret; } } UdfChainRegister UdfChain::BuildChainRegister() const { UdfChainRegister result; result.hash = hash_; for (auto node : nodes_) { UdfChainRegister::UdfDef def; if (node == nullptr) { def.udf_name = ""; } else { def.udf_name = node->udf_name_; for (const auto& child : node->inputs_) { def.inputs.emplace_back(node_ids_.find(child.node_.get())->second, child.id_); } } result.udfs.push_back(def); } for (const auto& data : datas_) { result.outputs.emplace_back(node_ids_.find(data.node_.get())->second, data.id_); } return result; } } }
1,034
628
<reponame>gaybro8777/osf.io<gh_stars>100-1000 """Delete a user to GDPR specifications python3 manage.py gdpr_delete_user guid1 Erroring deletions will be logged and skipped. """ import logging import sys from django.db import transaction from django.core.management.base import BaseCommand from osf.management.utils import ask_for_confirmation from osf.models import OSFUser logger = logging.getLogger(__name__) class Command(BaseCommand): def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--dry', action='store_true', dest='dry_run', help='Dry run', ) parser.add_argument('guids', type=str, nargs='+', help='user guid to be deleted') def handle(self, *args, **options): guids = options.get('guids', None) dry_run = options.get('dry_run', False) if not ask_for_confirmation( 'About to delete user(s): {}. yes or no?'.format(' '.join(guids)) ): print('Exiting...') sys.exit(1) with transaction.atomic(): for guid in guids: user = OSFUser.load(guid) user.gdpr_delete() user.save() logger.info('Deleted user {}'.format(user._id)) if dry_run: raise RuntimeError('Dry run -- transaction rolled back.')
635
2,112
<filename>thrift/conformance/cpp2/AnyRef.cpp /* * Copyright (c) Facebook, Inc. and its affiliates. * * 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. */ #include <thrift/conformance/cpp2/AnyRef.h> namespace apache::thrift::conformance { const std::type_info& any_ref::type() const noexcept { if (details_->type == typeid(std::any)) { const auto& value = *static_cast<const std::any*>(value_); if (value.has_value()) { return value.type(); } } return details_->type; } bool any_ref::has_value() const noexcept { if (!has_reference()) { return false; } if (details_->type == typeid(std::any)) { const auto& value = *static_cast<const std::any*>(value_); return value.has_value(); } return true; } } // namespace apache::thrift::conformance
418
4,036
typedef enum { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET } colors; int f(colors c) { switch (c) { case RED: //... case GREEN: //... case BLUE: //... //wrong: does not use all enum values, and has no default } switch(c) { case RED: //... case GREEN: //... default: //correct: does not use all enum values, but has a default } }
166
2,453
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <AppKit/NSTextField.h> @class NSAttributedString; @interface IDEFindNavigatorResultTextField : NSTextField { CDStruct_bf6d4a14 _layoutInset; } + (Class)cellClass; @property CDStruct_bf6d4a14 layoutInset; // @synthesize layoutInset=_layoutInset; - (BOOL)allowsVibrancy; @property(copy) NSAttributedString *expansionText; @end
184
389
/* * Copyright 2014 <NAME>, Inc. */ package gw.internal.gosu.ir.transform.expression; import gw.internal.gosu.ir.nodes.IRMethodFactory; import gw.internal.gosu.ir.nodes.IRMethodFromMethodInfo; import gw.internal.gosu.ir.transform.ExpressionTransformer; import gw.internal.gosu.ir.transform.TopLevelTransformationContext; import gw.internal.gosu.parser.Expression; import gw.internal.gosu.parser.TypeLord; import gw.internal.gosu.parser.expressions.BindingExpression; import gw.lang.ir.IRExpression; import gw.lang.reflect.FunctionType; import gw.lang.reflect.IType; import gw.lang.reflect.gs.IGosuMethodInfo; import java.util.Collections; /** */ public class BindingExpressionTransformer extends AbstractExpressionTransformer<BindingExpression> { public static IRExpression compile( TopLevelTransformationContext cc, BindingExpression expr ) { BindingExpressionTransformer compiler = new BindingExpressionTransformer( cc, expr ); return compiler.compile(); } private BindingExpressionTransformer( TopLevelTransformationContext cc, BindingExpression expr ) { super( cc, expr ); } protected IRExpression compile_impl() { String bindMethodName = _expr().isPrefix() ? "prefixBind" : "postfixBind"; Expression rhsExpr = _expr().isPrefix() ? _expr().getLhsExpr() : _expr().getRhsExpr(); Expression lhsExpr = _expr().isPrefix() ? _expr().getRhsExpr() : _expr().getLhsExpr(); IType lhsExprType = lhsExpr.getType(); if( lhsExprType.isPrimitive() ) { lhsExprType = TypeLord.getBoxedTypeFromPrimitiveType( lhsExprType ); } IType rhsExprType = rhsExpr.getType(); if( rhsExprType.isPrimitive() ) { rhsExprType = TypeLord.getBoxedTypeFromPrimitiveType( rhsExprType ); } IGosuMethodInfo bindMethod = (IGosuMethodInfo)rhsExprType.getTypeInfo().getCallableMethod( bindMethodName, lhsExprType ); IType owner = TypeLord.getPureGenericType( bindMethod.getContainer().getOwnersType() ); bindMethod = (IGosuMethodInfo)owner.getTypeInfo().getCallableMethod( bindMethodName, lhsExprType ); FunctionType funcType = new FunctionType( bindMethod ); funcType = funcType.getRuntimeType(); IRExpression irLhs = ExpressionTransformer.compile( lhsExpr, _cc() ); IRExpression irRhs = ExpressionTransformer.compile( rhsExpr, _cc() ); IRMethodFromMethodInfo irMethod = IRMethodFactory.createIRMethod( bindMethod, funcType ); IRExpression bindCall = callMethod( irMethod, boxValue( irRhs.getType(), irRhs ), Collections.singletonList( boxValue( irLhs.getType(), irLhs ) ) ); return buildCast( getDescriptor( _expr().getType() ), bindCall ); } }
924
803
#include "MaterialCache.h" #include "Material.h" #include "core/oxygine.h" namespace oxygine { Material* MaterialCache::clone_(const Material& other) { MutexAutoLock alock(_lock); size_t hash; Material::compare cm; other.update(hash, cm); materials::iterator itl = _materials.find(hash); if (itl != _materials.end()) { Material* sec = itl->second.get(); if (cm == sec->_compare && cm(sec, &other)) return sec; //hash collision? std::pair<materials::iterator, materials::iterator> it = _materials.equal_range(hash); itl = it.first; itl++;//skip first, already checked for (; itl != it.second; itl++) { Material* sec = itl->second.get(); if (cm == sec->_compare && cm(sec, &other)) return sec; } } _addCounter++; if (_addCounter > 30) removeUnusedNoLock(); Material* copy = other.clone(); copy->_hash = hash; copy->_compare = cm; _materials.insert(std::make_pair(hash, copy)); return copy; } void MaterialCache::removeUnusedNoLock() { _addCounter = 0; materials fresh; for (auto it = _materials.begin(); it != _materials.end(); it++) { if (it->second->_ref_counter > 1) { fresh.insert(std::make_pair(it->second->_hash, it->second)); } } std::swap(fresh, _materials); } void MaterialCache::removeUnused() { MutexAutoLock alock(_lock); removeUnusedNoLock(); } MaterialCache::MaterialCache(): _addCounter(0) { } void MaterialCache::clear() { MutexAutoLock alock(_lock); _addCounter = 0; _materials.clear(); } static MaterialCache mcache; MaterialCache& mc() { return mcache; } }
998
1,848
template<class K, class V> class Entry : public K { V mData; }; template<typename K, typename V> class nsBaseHashtable { typedef Entry<K, V> EntryType; struct EntryPtr { private: EntryType& mEntry; bool mExistingEntry; }; };
93
4,822
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ package org.opensearch.upgrades; import org.opensearch.Version; import org.opensearch.client.Request; import org.opensearch.client.Response; import org.opensearch.common.io.Streams; import java.io.IOException; public class RefreshVersionInClusterStateIT extends AbstractRollingTestCase { /* This test ensures that after the upgrade from ElasticSearch/ OpenSearch all nodes report the version on and after 1.0.0 */ public void testRefresh() throws IOException { switch (CLUSTER_TYPE) { case OLD: case MIXED: break; case UPGRADED: Response response = client().performRequest(new Request("GET", "/_cat/nodes?h=id,version")); for (String nodeLine : Streams.readAllLines(response.getEntity().getContent())) { String[] elements = nodeLine.split(" +"); assertEquals(Version.fromString(elements[1]), Version.CURRENT); } break; default: throw new UnsupportedOperationException("Unknown cluster type [" + CLUSTER_TYPE + "]"); } } }
543
324
{ "name": "myusualvm607", "id": "/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/networkInterfaces/myusualvm607", "etag": "W/\"01f72f0f-a12f-426a-bf9a-25d09be49cee\"", "location": "eastus", "tags": { "mycustomtag": "foobar" }, "properties": { "provisioningState": "Succeeded", "resourceGuid": "40a46008-5368-4e9f-ba39-a87b76ea047d", "ipConfigurations": [ { "name": "ipconfig1", "id": "/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/networkInterfaces/myusualvm607/ipConfigurations/ipconfig1", "etag": "W/\"01f72f0f-a12f-426a-bf9a-25d09be49cee\"", "properties": { "provisioningState": "Succeeded", "privateIPAddress": "192.168.0.4", "privateIPAllocationMethod": "Dynamic", "publicIPAddress": { "id": "/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/publicIPAddresses/myusualvm-ip" }, "subnet": { "id": "/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/virtualNetworks/abqvnet-bf0tuznt0x/subnets/abqsubnet-reauuik6qx" }, "primary": true, "privateIPAddressVersion": "IPv4", "isInUseWithService": false } } ], "dnsSettings": { "dnsServers": [], "appliedDnsServers": [], "internalDomainNameSuffix": "zqh4yoheybzejmruwtgyl2semg.bx.internal.cloudapp.net" }, "macAddress": "00-0D-3A-17-A4-C9", "enableAcceleratedNetworking": false, "enableIPForwarding": false, "networkSecurityGroup": { "id": "/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/networkSecurityGroups/myusualvm-nsg" }, "primary": true, "virtualMachine": { "id": "/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Compute/virtualMachines/myusualvm" } }, "type": "Microsoft.Network/networkInterfaces" }
1,056
888
<filename>tests/server/text_classification/test_api.py # coding=utf-8 # Copyright 2021-present, the Recognai S.L. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime import pytest from rubrix.server.datasets.model import Dataset from rubrix.server.tasks.commons import BulkResponse, PredictionStatus from rubrix.server.tasks.text_classification.api import ( TextClassificationAnnotation, TextClassificationBulkData, TextClassificationQuery, TextClassificationRecord, TextClassificationSearchRequest, TextClassificationSearchResults, ) from tests.server.test_helpers import client def test_create_records_for_text_classification_with_multi_label(): dataset = "test_create_records_for_text_classification_with_multi_label" assert client.delete(f"/api/datasets/{dataset}").status_code == 200 records = [ TextClassificationRecord.parse_obj(data) for data in [ { "id": 0, "inputs": {"data": "my data"}, "multi_label": True, "metadata": { "field_one": "value one", "field_two": "value 2", "one_more": [{"a": 1, "b": 2}], }, "prediction": { "agent": "test", "labels": [ {"class": "Test", "score": 0.6}, {"class": "Mocking", "score": 0.7}, {"class": "NoClass", "score": 0.2}, ], }, }, { "id": 1, "inputs": {"data": "my data"}, "multi_label": True, "metadata": {"field_one": "another value one", "field_two": "value 2"}, "prediction": { "agent": "test", "labels": [ {"class": "Test", "score": 0.6}, {"class": "Mocking", "score": 0.7}, {"class": "NoClass", "score": 0.2}, ], }, }, ] ] response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", json=TextClassificationBulkData( tags={"env": "test", "class": "text classification"}, metadata={"config": {"the": "config"}}, records=records, ).dict(by_alias=True), ) assert response.status_code == 200, response.json() bulk_response = BulkResponse.parse_obj(response.json()) assert bulk_response.dataset == dataset assert bulk_response.failed == 0 assert bulk_response.processed == 2 response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", json=TextClassificationBulkData( tags={"new": "tag"}, metadata={"new": {"metadata": "value"}}, records=records, ).dict(by_alias=True), ) get_dataset = Dataset.parse_obj(client.get(f"/api/datasets/{dataset}").json()) assert get_dataset.tags == { "env": "test", "class": "text classification", "new": "tag", } assert get_dataset.metadata == { "config": {"the": "config"}, "new": {"metadata": "value"}, } assert response.status_code == 200, response.json() response = client.post( f"/api/datasets/{dataset}/TextClassification:search", json={} ) assert response.status_code == 200 results = TextClassificationSearchResults.parse_obj(response.json()) assert results.total == 2 assert results.aggregations.predicted_as == {"Mocking": 2, "Test": 2} assert results.records[0].predicted is None def test_create_records_for_text_classification(): dataset = "test_create_records_for_text_classification" assert client.delete(f"/api/datasets/{dataset}").status_code == 200 tags = {"env": "test", "class": "text classification"} metadata = {"config": {"the": "config"}} classification_bulk = TextClassificationBulkData( tags=tags, metadata=metadata, records=[ TextClassificationRecord( **{ "id": 0, "inputs": {"data": "my data"}, "prediction": { "agent": "test", "labels": [ {"class": "Test", "score": 0.3}, {"class": "Mocking", "score": 0.7}, ], }, } ) ], ) response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", json=classification_bulk.dict(by_alias=True), ) assert response.status_code == 200 bulk_response = BulkResponse.parse_obj(response.json()) assert bulk_response.dataset == dataset assert bulk_response.failed == 0 assert bulk_response.processed == 1 response = client.get(f"/api/datasets/{dataset}") assert response.status_code == 200 created_dataset = Dataset.parse_obj(response.json()) assert created_dataset.tags == tags assert created_dataset.metadata == metadata response = client.post( f"/api/datasets/{dataset}/TextClassification:search", json={} ) assert response.status_code == 200 results = TextClassificationSearchResults.parse_obj(response.json()) assert results.total == 1 assert results.aggregations.predicted_as == {"Mocking": 1} assert results.aggregations.status == {"Default": 1} assert results.aggregations.score assert results.aggregations.predicted == {} def test_partial_record_update(): name = "test_partial_record_update" assert client.delete(f"/api/datasets/{name}").status_code == 200 record = TextClassificationRecord( **{ "id": 1, "inputs": {"text": "This is a text, oh yeah!"}, "prediction": { "agent": "test", "labels": [ {"class": "Positive", "score": 0.6}, {"class": "Negative", "score": 0.3}, {"class": "Other", "score": 0.1}, ], }, } ) bulk = TextClassificationBulkData( records=[record], ) response = client.post( f"/api/datasets/{name}/TextClassification:bulk", json=bulk.dict(by_alias=True), ) assert response.status_code == 200 bulk_response = BulkResponse.parse_obj(response.json()) assert bulk_response.failed == 0 assert bulk_response.processed == 1 record.annotation = TextClassificationAnnotation.parse_obj( { "agent": "gold_standard", "labels": [{"class": "Positive"}], } ) bulk.records = [record] client.post( f"/api/datasets/{name}/TextClassification:bulk", json=bulk.dict(by_alias=True), ) response = client.post( f"/api/datasets/{name}/TextClassification:search", json={ "query": TextClassificationQuery(predicted=PredictionStatus.OK).dict( by_alias=True ), }, ) assert response.status_code == 200 results = TextClassificationSearchResults.parse_obj(response.json()) assert results.total == 1 first_record = results.records[0] assert first_record.last_updated is not None first_record.last_updated = None assert TextClassificationRecord( **first_record.dict(by_alias=True, exclude_none=True) ) == TextClassificationRecord( **{ "id": 1, "inputs": {"text": "This is a text, oh yeah!"}, "prediction": { "agent": "test", "labels": [ {"class": "Positive", "score": 0.6}, {"class": "Negative", "score": 0.3}, {"class": "Other", "score": 0.1}, ], }, "annotation": { "agent": "gold_standard", "labels": [{"class": "Positive"}], }, } ) def test_sort_by_id_as_default(): dataset = "test_sort_by_id_as_default" assert client.delete(f"/api/datasets/{dataset}").status_code == 200 response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", json=TextClassificationBulkData( records=[ TextClassificationRecord( **{ "id": i, "inputs": {"data": "my data"}, "metadata": {"s": "value"}, } ) for i in range(0, 100) ], ).dict(by_alias=True), ) response = client.post( f"/api/datasets/{dataset}/TextClassification:search?from=0&limit=10", json={}, ) results = TextClassificationSearchResults.parse_obj(response.json()) assert results.total == 100 assert list(map(lambda r: r.id, results.records)) == [ 0, 1, 10, 11, 12, 13, 14, 15, 16, 17, ] def test_some_sort_by(): dataset = "test_some_sort_by" expected_records_length = 50 assert client.delete(f"/api/datasets/{dataset}").status_code == 200 response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", json=TextClassificationBulkData( records=[ TextClassificationRecord( **{ "id": i, "inputs": {"data": "my data"}, "prediction": {"agent": f"agent_{i%5}", "labels": []}, "metadata": { "s": f"{i} value", }, } ) for i in range(0, expected_records_length) ], ).dict(by_alias=True), ) with pytest.raises(AssertionError): client.post( f"/api/datasets/{dataset}/TextClassification:search?from=0&limit=10", json={ "sort": [ {"id": "wrong_field"}, ] }, ) response = client.post( f"/api/datasets/{dataset}/TextClassification:search?from=0&limit=10", json={ "sort": [ {"id": "predicted_by", "order": "desc"}, {"id": "metadata.s", "order": "asc"}, ] }, ) results = TextClassificationSearchResults.parse_obj(response.json()) assert results.total == expected_records_length assert list(map(lambda r: r.id, results.records)) == [14, 19, 24, 29, 34, 39, 4, 44, 49, 9] def test_disable_aggregations_when_scroll(): dataset = "test_disable_aggregations_when_scroll" assert client.delete(f"/api/datasets/{dataset}").status_code == 200 response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", json=TextClassificationBulkData( tags={"env": "test", "class": "text classification"}, metadata={"config": {"the": "config"}}, records=[ TextClassificationRecord( **{ "id": i, "inputs": {"data": "my data"}, "prediction": { "agent": "test", "labels": [ {"class": "Test", "score": 0.3}, {"class": "Mocking", "score": 0.7}, ], }, } ) for i in range(0, 100) ], ).dict(by_alias=True), ) bulk_response = BulkResponse.parse_obj(response.json()) assert bulk_response.processed == 100 response = client.post( f"/api/datasets/{dataset}/TextClassification:search?from=10", json={}, ) results = TextClassificationSearchResults.parse_obj(response.json()) assert results.total == 100 assert results.aggregations is None def test_include_event_timestamp(): dataset = "test_include_event_timestamp" assert client.delete(f"/api/datasets/{dataset}").status_code == 200 response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", data=TextClassificationBulkData( tags={"env": "test", "class": "text classification"}, metadata={"config": {"the": "config"}}, records=[ TextClassificationRecord( **{ "id": i, "inputs": {"data": "my data"}, "event_timestamp": datetime.utcnow(), "prediction": { "agent": "test", "labels": [ {"class": "Test", "score": 0.3}, {"class": "Mocking", "score": 0.7}, ], }, } ) for i in range(0, 100) ], ).json(by_alias=True), ) bulk_response = BulkResponse.parse_obj(response.json()) assert bulk_response.processed == 100 response = client.post( f"/api/datasets/{dataset}/TextClassification:search?from=10", json={}, ) results = TextClassificationSearchResults.parse_obj(response.json()) assert results.total == 100 assert all(map(lambda record: record.event_timestamp is not None, results.records)) def test_words_cloud(): dataset = "test_language_detection" assert client.delete(f"/api/datasets/{dataset}").status_code == 200 response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", data=TextClassificationBulkData( records=[ TextClassificationRecord( **{ "id": 0, "inputs": {"text": "Esto es un ejemplo de texto"}, } ), TextClassificationRecord( **{ "id": 1, "inputs": {"text": "This is an simple text example"}, } ), TextClassificationRecord( **{ "id": 2, "inputs": {"text": "C'est nes pas une pipe"}, } ), ], ).json(by_alias=True), ) BulkResponse.parse_obj(response.json()) response = client.post( f"/api/datasets/{dataset}/TextClassification:search", json={}, ) results = TextClassificationSearchResults.parse_obj(response.json()) assert results.aggregations.words is not None def test_metadata_with_point_in_field_name(): dataset = "test_metadata_with_point_in_field_name" assert client.delete(f"/api/datasets/{dataset}").status_code == 200 response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", data=TextClassificationBulkData( records=[ TextClassificationRecord( **{ "id": 0, "inputs": {"text": "Esto es un ejemplo de texto"}, "metadata": {"field.one": 1, "field.two": 2}, } ), TextClassificationRecord( **{ "id": 1, "inputs": {"text": "This is an simple text example"}, "metadata": {"field.one": 1, "field.two": 2}, } ), ], ).json(by_alias=True), ) response = client.post( f"/api/datasets/{dataset}/TextClassification:search?limit=0", json={}, ) results = TextClassificationSearchResults.parse_obj(response.json()) assert "field.one" in results.aggregations.metadata assert results.aggregations.metadata.get("field.one", {})["1"] == 2 assert results.aggregations.metadata.get("field.two", {})["2"] == 2 def test_wrong_text_query(): dataset = "test_wrong_text_query" assert client.delete(f"/api/datasets/{dataset}").status_code == 200 response = client.post( f"/api/datasets/{dataset}/TextClassification:bulk", data=TextClassificationBulkData( records=[ TextClassificationRecord( **{ "id": 0, "inputs": {"text": "Esto es un ejemplo de texto"}, "metadata": {"field.one": 1, "field.two": 2}, } ), ], ).json(by_alias=True), ) response = client.post( f"/api/datasets/{dataset}/TextClassification:search", json=TextClassificationSearchRequest( query=TextClassificationQuery(query_text="!") ).dict(), ) assert response.status_code == 400 assert response.json()["detail"] == "Failed to parse query [!]"
9,032
892
{ "schema_version": "1.2.0", "id": "GHSA-wgq3-h773-3ffp", "modified": "2022-02-17T00:00:43Z", "published": "2022-02-11T00:00:47Z", "aliases": [ "CVE-2022-24316" ], "details": "A CWE-665: Improper Initialization vulnerability exists that could cause information exposure when an attacker sends a specially crafted message. Affected Product: Interactive Graphical SCADA System Data Server (V15.0.0.22020 and prior)", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24316" }, { "type": "WEB", "url": "https://download.schneider-electric.com/files?p_Doc_Ref=SEVD-2022-039-01" }, { "type": "WEB", "url": "https://www.zerodayinitiative.com/advisories/ZDI-22-323/" } ], "database_specific": { "cwe_ids": [ "CWE-665" ], "severity": "HIGH", "github_reviewed": false } }
427
384
# Copyright 2021 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. from .helpers import make_connection, make_client, dataset_polymorphic import google.api_core.exceptions from google.cloud.bigquery.retry import DEFAULT_TIMEOUT import pytest @dataset_polymorphic def test_delete_dataset(make_dataset, get_reference, client, PROJECT, DS_ID): dataset = make_dataset(PROJECT, DS_ID) PATH = "projects/%s/datasets/%s" % (PROJECT, DS_ID) conn = client._connection = make_connection({}) client.delete_dataset(dataset, timeout=7.5) conn.api_request.assert_called_with( method="DELETE", path="/%s" % PATH, query_params={}, timeout=7.5 ) @dataset_polymorphic def test_delete_dataset_delete_contents( make_dataset, get_reference, client, PROJECT, DS_ID ): PATH = "projects/%s/datasets/%s" % (PROJECT, DS_ID) conn = client._connection = make_connection({}) dataset = make_dataset(PROJECT, DS_ID) client.delete_dataset(dataset, delete_contents=True) conn.api_request.assert_called_with( method="DELETE", path="/%s" % PATH, query_params={"deleteContents": "true"}, timeout=DEFAULT_TIMEOUT, ) def test_delete_dataset_wrong_type(client): with pytest.raises(TypeError): client.delete_dataset(42) def test_delete_dataset_w_not_found_ok_false(PROJECT, DS_ID): path = "/projects/{}/datasets/{}".format(PROJECT, DS_ID) http = object() client = make_client(_http=http) conn = client._connection = make_connection( google.api_core.exceptions.NotFound("dataset not found") ) with pytest.raises(google.api_core.exceptions.NotFound): client.delete_dataset(DS_ID) conn.api_request.assert_called_with( method="DELETE", path=path, query_params={}, timeout=DEFAULT_TIMEOUT ) def test_delete_dataset_w_not_found_ok_true(PROJECT, DS_ID): path = "/projects/{}/datasets/{}".format(PROJECT, DS_ID) http = object() client = make_client(_http=http) conn = client._connection = make_connection( google.api_core.exceptions.NotFound("dataset not found") ) client.delete_dataset(DS_ID, not_found_ok=True) conn.api_request.assert_called_with( method="DELETE", path=path, query_params={}, timeout=DEFAULT_TIMEOUT )
1,056
900
<filename>droidicon/src/main/java/com/thedazzler/droidicon/typeface/IconicTypefaceHolder.java package com.thedazzler.droidicon.typeface; import java.util.HashMap; import java.util.Map; /** * Author: <NAME> (<EMAIL>), 2/3/15. */ public class IconicTypefaceHolder extends TypefaceHolder { private final Map<String, Integer> iconicIconMap = new HashMap<String, Integer>(); IconicTypefaceHolder(String prefix, int resourceId) { super(prefix, resourceId); initIconMap(); setIconMap(iconicIconMap); } private void initIconMap() { iconicIconMap.put("iconic-search", 0x1F50E); iconicIconMap.put("iconic-mail", 0x2709); iconicIconMap.put("iconic-heart", 0x2665); iconicIconMap.put("iconic-heart-empty", 0x2661); iconicIconMap.put("iconic-star", 0x2605); iconicIconMap.put("iconic-user", 0x1F464); iconicIconMap.put("iconic-video", 0x1F3AC); iconicIconMap.put("iconic-picture", 0x1F304); iconicIconMap.put("iconic-camera", 0x1F4F7); iconicIconMap.put("iconic-ok", 0x2713); iconicIconMap.put("iconic-ok-circle", 0x2714); iconicIconMap.put("iconic-cancel", 0x2715); iconicIconMap.put("iconic-cancel-circle", 0x2716); iconicIconMap.put("iconic-plus", 0x2B); iconicIconMap.put("iconic-plus-circle", 0x2795); iconicIconMap.put("iconic-minus", 0x2D); iconicIconMap.put("iconic-minus-circle", 0x2796); iconicIconMap.put("iconic-help", 0x2753); iconicIconMap.put("iconic-info", 0x2139); iconicIconMap.put("iconic-home", 0x2302); iconicIconMap.put("iconic-link", 0x1F517); iconicIconMap.put("iconic-attach", 0x1F4CE); iconicIconMap.put("iconic-lock", 0x1F512); iconicIconMap.put("iconic-lock-empty", 0xE708); iconicIconMap.put("iconic-lock-open", 0x1F513); iconicIconMap.put("iconic-lock-open-empty", 0xE709); iconicIconMap.put("iconic-pin", 0x1F4CC); iconicIconMap.put("iconic-eye", 0xE70A); iconicIconMap.put("iconic-tag", 0xE70C); iconicIconMap.put("iconic-tag-empty", 0xE70E); iconicIconMap.put("iconic-download", 0x1F4E5); iconicIconMap.put("iconic-upload", 0x1F4E4); iconicIconMap.put("iconic-download-count", 0xE710); iconicIconMap.put("iconic-upload-count", 0xE711); iconicIconMap.put("iconic-quote-left", 0x275D); iconicIconMap.put("iconic-quote-right", 0x275E); iconicIconMap.put("iconic-quote-left-alt", 0x275B); iconicIconMap.put("iconic-quote-right-alt", 0x275C); iconicIconMap.put("iconic-pencil", 0x270E); iconicIconMap.put("iconic-pencil-neg", 0x270F); iconicIconMap.put("iconic-pencil-alt", 0x2710); iconicIconMap.put("iconic-undo", 0x21B6); iconicIconMap.put("iconic-comment", 0xE718); iconicIconMap.put("iconic-comment-inv", 0xE719); iconicIconMap.put("iconic-comment-alt", 0xE71A); iconicIconMap.put("iconic-comment-inv-alt", 0xE71B); iconicIconMap.put("iconic-comment-alt2", 0xE71C); iconicIconMap.put("iconic-comment-inv-alt2", 0xE71D); iconicIconMap.put("iconic-chat", 0xE720); iconicIconMap.put("iconic-chat-inv", 0xE721); iconicIconMap.put("iconic-location", 0xE724); iconicIconMap.put("iconic-location-inv", 0xE725); iconicIconMap.put("iconic-location-alt", 0xE726); iconicIconMap.put("iconic-compass", 0xE728); iconicIconMap.put("iconic-trash", 0xE729); iconicIconMap.put("iconic-trash-empty", 0xE72A); iconicIconMap.put("iconic-doc", 0xE730); iconicIconMap.put("iconic-doc-inv", 0xE731); iconicIconMap.put("iconic-doc-alt", 0xE732); iconicIconMap.put("iconic-doc-inv-alt", 0xE733); iconicIconMap.put("iconic-article", 0xE734); iconicIconMap.put("iconic-article-alt", 0xE735); iconicIconMap.put("iconic-book-open", 0x1F4D6); iconicIconMap.put("iconic-folder", 0x1F4C1); iconicIconMap.put("iconic-folder-empty", 0x1F4C2); iconicIconMap.put("iconic-box", 0x1F4E6); iconicIconMap.put("iconic-rss", 0xE73A); iconicIconMap.put("iconic-rss-alt", 0xE73B); iconicIconMap.put("iconic-cog", 0x2699); iconicIconMap.put("iconic-wrench", 0x1F527); iconicIconMap.put("iconic-share", 0xE73C); iconicIconMap.put("iconic-calendar", 0x1F4C5); iconicIconMap.put("iconic-calendar-inv", 0xE73E); iconicIconMap.put("iconic-calendar-alt", 0x1F4C6); iconicIconMap.put("iconic-mic", 0x1F3A4); iconicIconMap.put("iconic-volume-off", 0x1F507); iconicIconMap.put("iconic-volume-up", 0x1F50A); iconicIconMap.put("iconic-headphones", 0x1F3A7); iconicIconMap.put("iconic-clock", 0x1F554); iconicIconMap.put("iconic-lamp", 0x1F4A1); iconicIconMap.put("iconic-block", 0x1F6AB); iconicIconMap.put("iconic-resize-full", 0xE744); iconicIconMap.put("iconic-resize-full-alt", 0xE745); iconicIconMap.put("iconic-resize-small", 0xE746); iconicIconMap.put("iconic-resize-small-alt", 0xE747); iconicIconMap.put("iconic-resize-vertical", 0x2B0C); iconicIconMap.put("iconic-resize-horizontal", 0x2B0D); iconicIconMap.put("iconic-move", 0xE74A); iconicIconMap.put("iconic-popup", 0xE74C); iconicIconMap.put("iconic-down", 0x2193); iconicIconMap.put("iconic-left", 0x2190); iconicIconMap.put("iconic-right", 0x2192); iconicIconMap.put("iconic-up", 0x2191); iconicIconMap.put("iconic-down-circle", 0xE4A4); iconicIconMap.put("iconic-left-circle", 0xE4A1); iconicIconMap.put("iconic-right-circle", 0xE4A2); iconicIconMap.put("iconic-up-circle", 0xE4A3); iconicIconMap.put("iconic-cw", 0x27F3); iconicIconMap.put("iconic-loop", 0x1F504); iconicIconMap.put("iconic-loop-alt", 0x1F501); iconicIconMap.put("iconic-exchange", 0x21C4); iconicIconMap.put("iconic-split", 0x2387); iconicIconMap.put("iconic-arrow-curved", 0x2935); iconicIconMap.put("iconic-play", 0x25B6); iconicIconMap.put("iconic-play-circle2", 0xE048); iconicIconMap.put("iconic-stop", 0x25AA); iconicIconMap.put("iconic-pause", 0x2389); iconicIconMap.put("iconic-to-start", 0x23EE); iconicIconMap.put("iconic-to-end", 0x23ED); iconicIconMap.put("iconic-eject", 0x23CF); iconicIconMap.put("iconic-target", 0x1F3AF); iconicIconMap.put("iconic-signal", 0x1F4F6); iconicIconMap.put("iconic-award", 0x1F3C9); iconicIconMap.put("iconic-award-empty", 0xE764); iconicIconMap.put("iconic-list", 0xE765); iconicIconMap.put("iconic-list-nested", 0xE766); iconicIconMap.put("iconic-bat-empty", 0xE772); iconicIconMap.put("iconic-bat-half", 0xE774); iconicIconMap.put("iconic-bat-full", 0xE774); iconicIconMap.put("iconic-bat-charge", 0xE775); iconicIconMap.put("iconic-mobile", 0x1F4F1); iconicIconMap.put("iconic-cd", 0x1F4BF); iconicIconMap.put("iconic-equalizer", 0xE795); iconicIconMap.put("iconic-cursor", 0xE796); iconicIconMap.put("iconic-aperture", 0xE797); iconicIconMap.put("iconic-aperture-alt", 0xE798); iconicIconMap.put("iconic-aperture-wheel", 0xE799); iconicIconMap.put("iconic-book", 0x1F4D5); iconicIconMap.put("iconic-book-alt", 0x1F4D4); iconicIconMap.put("iconic-brush", 0xE79A); iconicIconMap.put("iconic-brush-alt", 0xE79B); iconicIconMap.put("iconic-eyedropper", 0xE79C); iconicIconMap.put("iconic-layers", 0xE79D); iconicIconMap.put("iconic-layers-alt", 0xE79E); iconicIconMap.put("iconic-sun", 0x263C); iconicIconMap.put("iconic-sun-inv", 0x2600); iconicIconMap.put("iconic-cloud", 0x2601); iconicIconMap.put("iconic-rain", 0x26C6); iconicIconMap.put("iconic-flash", 0x26A1); iconicIconMap.put("iconic-moon", 0x263E); iconicIconMap.put("iconic-moon-inv", 0xE7A0); iconicIconMap.put("iconic-umbrella", 0x2602); iconicIconMap.put("iconic-chart-bar", 0x1F4CA); iconicIconMap.put("iconic-chart-pie", 0xE7A2); iconicIconMap.put("iconic-chart-pie-alt", 0xE7A3); iconicIconMap.put("iconic-key", 0x26BF); iconicIconMap.put("iconic-key-inv", 0x1F511); iconicIconMap.put("iconic-hash", 0x23); iconicIconMap.put("iconic-at", 0x40); iconicIconMap.put("iconic-pilcrow", 0xB6); iconicIconMap.put("iconic-dial", 0xE7A4); } }
4,187
4,857
<reponame>gvprathyusha6/hbase /** * 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.hadoop.hbase.hbtop.screen.top; import java.util.Objects; import org.apache.yetus.audience.InterfaceAudience; /** * Represents the summary of the metrics. */ @InterfaceAudience.Private public class Summary { private final String currentTime; private final String version; private final String clusterId; private final int servers; private final int liveServers; private final int deadServers; private final int regionCount; private final int ritCount; private final double averageLoad; private final long aggregateRequestPerSecond; public Summary(String currentTime, String version, String clusterId, int servers, int liveServers, int deadServers, int regionCount, int ritCount, double averageLoad, long aggregateRequestPerSecond) { this.currentTime = Objects.requireNonNull(currentTime); this.version = Objects.requireNonNull(version); this.clusterId = Objects.requireNonNull(clusterId); this.servers = servers; this.liveServers = liveServers; this.deadServers = deadServers; this.regionCount = regionCount; this.ritCount = ritCount; this.averageLoad = averageLoad; this.aggregateRequestPerSecond = aggregateRequestPerSecond; } public String getCurrentTime() { return currentTime; } public String getVersion() { return version; } public String getClusterId() { return clusterId; } public int getServers() { return servers; } public int getLiveServers() { return liveServers; } public int getDeadServers() { return deadServers; } public int getRegionCount() { return regionCount; } public int getRitCount() { return ritCount; } public double getAverageLoad() { return averageLoad; } public long getAggregateRequestPerSecond() { return aggregateRequestPerSecond; } }
785
302
/* * Copyright 2018 astonbitecode * 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.astonbitecode.j4rs.api.dtos; import org.astonbitecode.j4rs.api.invocation.JsonInvocationImpl; import org.astonbitecode.j4rs.errors.InvalidArgumentException; import org.astonbitecode.j4rs.utils.Dummy; import org.junit.Test; public class InvocationArgTest { private static String CLASS_NAME = "a.class.Name"; @Test(expected = InvalidArgumentException.class) public void getNativeInvocationOnAnArgCreatedByRust() { InvocationArg ia = new InvocationArg(CLASS_NAME, "{\"a\":\"b\"}"); ia.getInstance(); } @Test(expected = InvalidArgumentException.class) public void getNativeInvocationOnAnArgCreatedByJava() { InvocationArg ia = new InvocationArg(CLASS_NAME, new JsonInvocationImpl(new Dummy(), Dummy.class)); ia.getJson(); } @Test public void getArgFrom() { InvocationArg ia1 = new InvocationArg(CLASS_NAME, "{\"a\":\"b\"}"); assert ia1.isSerialized(); assert ia1.getObjectClassName().equals(CLASS_NAME); InvocationArg ia2 = new InvocationArg(CLASS_NAME, new JsonInvocationImpl(new Dummy(), Dummy.class)); assert !ia2.isSerialized(); assert ia2.getObjectClassName().equals(CLASS_NAME); } }
619
1,012
#pragma once #include <unistd.h> #include "libpq-fe.h" #include <atomic> #include <boost/lexical_cast.hpp> #include <cassert> #include <cstring> #include <deque> #include <iostream> #include <map> #include <memory> #include <mutex> #include <optional> #include <sstream> #include <thread> #include <unordered_map> #include <li/callable_traits/callable_traits.hh> #include <li/metamap/metamap.hh> #include <li/sql/pgsql_result.hh> #include <li/sql/pgsql_statement.hh> #include <li/sql/sql_common.hh> #include <li/sql/symbols.hh> #include <li/sql/type_hashmap.hh> #include <li/sql/pgsql_connection_data.hh> namespace li { struct pgsql_tag {}; // template <typename Y> void pq_wait(Y& yield, PGconn* con) { // while (PQisBusy(con)) // yield(); // } template <typename Y> struct pgsql_connection { Y& fiber_; std::shared_ptr<pgsql_connection_data> data_; std::unordered_map<std::string, std::shared_ptr<pgsql_statement_data>>& stm_cache_; PGconn* connection_; typedef pgsql_tag db_tag; inline pgsql_connection(const pgsql_connection&) = delete; inline pgsql_connection& operator=(const pgsql_connection&) = delete; inline pgsql_connection(pgsql_connection&& o) = default; inline pgsql_connection(Y& fiber, std::shared_ptr<pgsql_connection_data>& data) : fiber_(fiber), data_(data), stm_cache_(data->statements), connection_(data->pgconn_) { } // FIXME long long int last_insert_rowid() { return pgsql_insert_id(connection_); } // pgsql_statement<Y> operator()(const std::string& rq) { return prepare(rq)(); } auto operator()(const std::string& rq) { if (!PQsendQueryParams(connection_, rq.c_str(), 0, nullptr, nullptr, nullptr, nullptr, 1)) throw std::runtime_error(std::string("Postresql error:") + PQerrorMessage(connection_)); return sql_result<pgsql_result<Y>>{ pgsql_result<Y>{this->data_, this->fiber_, data_->error_}}; } // PQsendQueryParams template <typename F, typename... K> pgsql_statement<Y> cached_statement(F f, K... keys) { if (data_->statements_hashmap(f, keys...).get() == nullptr) { pgsql_statement<Y> res = prepare(f()); data_->statements_hashmap(f, keys...) = res.data_.shared_from_this(); return res; } else return pgsql_statement<Y>{data_, fiber_, *data_->statements_hashmap(f, keys...)}; } pgsql_statement<Y> prepare(const std::string& rq) { auto it = stm_cache_.find(rq); if (it != stm_cache_.end()) { return pgsql_statement<Y>{data_, fiber_, *it->second}; } std::string stmt_name = boost::lexical_cast<std::string>(stm_cache_.size()); if (!PQsendPrepare(connection_, stmt_name.c_str(), rq.c_str(), 0, nullptr)) { throw std::runtime_error(std::string("PQsendPrepare error") + PQerrorMessage(connection_)); } // flush results. while (PGresult* ret = pg_wait_for_next_result(connection_, fiber_, data_->error_)) PQclear(ret); auto pair = stm_cache_.emplace(rq, std::make_shared<pgsql_statement_data>(stmt_name)); return pgsql_statement<Y>{data_, fiber_, *pair.first->second}; } template <typename T> inline std::string type_to_string(const T&, std::enable_if_t<std::is_integral<T>::value>* = 0) { return "INT"; } template <typename T> inline std::string type_to_string(const T&, std::enable_if_t<std::is_floating_point<T>::value>* = 0) { return "DOUBLE"; } inline std::string type_to_string(const std::string&) { return "TEXT"; } inline std::string type_to_string(const sql_blob&) { return "BLOB"; } template <unsigned S> inline std::string type_to_string(const sql_varchar<S>) { std::ostringstream ss; ss << "VARCHAR(" << S << ')'; return ss.str(); } }; } // namespace li #include <li/sql/pgsql_database.hh>
1,532
355
/* The MIT License (MIT) Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.lindenb.jvarkit.fastq; import java.util.AbstractList; import java.util.List; import htsjdk.samtools.fastq.FastqConstants; import htsjdk.samtools.fastq.FastqRecord; /** a pair of FastqRecord */ public interface FastqRecordPair extends List<FastqRecord> { /** get first of pair */ public FastqRecord getFirstInPair(); /** get second of pair */ public FastqRecord getSecondInPair(); /** check names R1 and R2 are valid */ public boolean isValidName(); /** assert names R1 and R2 are valid and return this*/ public default FastqRecordPair validateName() { if(!isValidName()) throw new IllegalArgumentException("Bad Fastq R1 and R2 names: " + getFirstInPair().getReadName()+" " + getSecondInPair().getReadName() ); return this; } public static FastqRecordPair of(final FastqRecord fq1, final FastqRecord fq2) { return new FastqRecordPairImpl(fq1,fq2); } static class FastqRecordPairImpl extends AbstractList<FastqRecord> implements FastqRecordPair { private final FastqRecord r1; private final FastqRecord r2; FastqRecordPairImpl(final FastqRecord r1,final FastqRecord r2) { this.r1 = r1; this.r2 = r2; } @Override public FastqRecord getFirstInPair() { return this.r1; } @Override public FastqRecord getSecondInPair() { return this.r2; } @Override public final int size() { return 2; } @Override public FastqRecord get(final int index) { switch(index) { case 0: return this.r1; case 1: return this.r2; default: throw new IndexOutOfBoundsException("0<="+index+"<2"); } } /** normalize read name */ private String normalize(String s, int side) { int w = s.indexOf(' '); if(w==-1) w=s.indexOf('\t'); if(w!=-1) s=s.substring(0,w); if( (side==0 && s.endsWith(FastqConstants.FIRST_OF_PAIR)) || (side==1 && s.endsWith(FastqConstants.SECOND_OF_PAIR))) { s=s.substring(0,s.length()-2); } return s; } @Override public boolean isValidName() { String n1 = this.getFirstInPair().getReadName(); String n2 = this.getSecondInPair().getReadName(); if(n1.equals(n2)) return true; n1 = normalize(n1,0); n2 = normalize(n2,0); return n1.equals(n2); } @Override public int hashCode() { return this.r1.hashCode()*31 + this.r2.hashCode(); } @Override public boolean equals(final Object o) { if(o==this) return true; if(o==null || !(o instanceof FastqRecordPair)) return false; final FastqRecordPair other = FastqRecordPair.class.cast(o); return this.r1.equals(other.getFirstInPair()) && this.r2.equals(other.getSecondInPair()) ; } @Override public String toString() { return "FastqRecordPair("+this.r1+","+this.r2+")"; } } }
1,360
454
<filename>vertx-pin/zero-crud/src/main/java/io/vertx/tp/crud/uca/input/ExcelPre.java package io.vertx.tp.crud.uca.input; import io.vertx.core.Future; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.tp.crud.uca.desk.IxMod; import io.vertx.tp.error._409ModuleConflictException; import io.vertx.tp.error._409MultiModuleException; import io.vertx.tp.ke.atom.specification.KModule; import io.vertx.tp.plugin.excel.ExcelClient; import io.vertx.tp.plugin.excel.atom.ExTable; import io.vertx.up.atom.Kv; import io.vertx.up.eon.KName; import io.vertx.up.exception.web._500InternalServerException; import io.vertx.up.fn.Fn; import io.vertx.up.unity.Ux; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author <a href="http://www.origin-x.cn">Lang</a> */ class ExcelPre implements Pre { private transient final ExcelClient client; ExcelPre(final ExcelClient client) { this.client = client; } @Override public Future<JsonArray> inJAAsync(final JsonObject data, final IxMod in) { final String filename = data.getString(KName.FILE_NAME); /* File Checking */ final File file = new File(filename); if (!file.exists() || Objects.isNull(this.client)) { return Ux.futureA(); } /* Read file into data table */ final Kv<String, Set<ExTable>> content = this.readFile(file); if (!content.valid()) { return Ux.futureA(); } /* Data Processing */ final KModule module = in.module(); final String expected = module.getTable(); final String actual = content.getKey(); Fn.out(!expected.equals(actual), _409ModuleConflictException.class, this.getClass(), actual, expected); /* Tenant Information */ return this.client.extractAsync(content.getValue()); } private Kv<String, Set<ExTable>> readFile(final File file) { final ConcurrentMap<String, Set<ExTable>> tableMap = new ConcurrentHashMap<>(); final Kv<String, Set<ExTable>> kv = Kv.create(); try { final InputStream stream = new FileInputStream(file); final Set<ExTable> tables = this.client.ingest(stream, true); /* * Filtered the tables that equal module in table */ tables.stream() .filter(Objects::nonNull) .filter(item -> Objects.nonNull(item.getName())) .forEach(item -> { if (!tableMap.containsKey(item.getName())) { tableMap.put(item.getName(), new HashSet<>()); } tableMap.get(item.getName()).add(item); }); Fn.out(1 != tableMap.size(), _409MultiModuleException.class, this.getClass(), tableMap.size()); final String tableName = tableMap.keySet().iterator().next(); kv.set(tableName, tableMap.get(tableName)); return kv; } catch (final IOException ex) { ex.printStackTrace(); throw new _500InternalServerException(this.getClass(), ex.getMessage()); } } }
1,453
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-wwvr-r64c-3ghh", "modified": "2022-03-17T00:02:00Z", "published": "2022-03-11T00:02:32Z", "aliases": [ "CVE-2021-33851" ], "details": "A Cross-Site Scripting (XSS) attack can cause arbitrary code (JavaScript) to run in a user’s browser while the browser is connected to a trusted website. The attack targets your application's users and not the application itself while using your application as the attack's vehicle. The XSS payload executes whenever the user opens the login page of the WordPress application.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-33851" }, { "type": "WEB", "url": "https://cybersecurityworks.com/zerodays/cve-2021-33851-stored-cross-site-scripting-in-wordpress-customize-login-image.html" } ], "database_specific": { "cwe_ids": [ "CWE-79" ], "severity": "MODERATE", "github_reviewed": false } }
495
945
/* * 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.iotdb.db.sync.receiver.collector; import org.apache.iotdb.commons.concurrent.IoTDBThreadPoolFactory; import org.apache.iotdb.commons.concurrent.ThreadName; import org.apache.iotdb.db.exception.sync.PipeDataLoadBearableException; import org.apache.iotdb.db.exception.sync.PipeDataLoadException; import org.apache.iotdb.db.sync.conf.SyncPathUtil; import org.apache.iotdb.db.sync.pipedata.PipeData; import org.apache.iotdb.db.sync.pipedata.queue.PipeDataQueue; import org.apache.iotdb.db.sync.pipedata.queue.PipeDataQueueFactory; import org.apache.iotdb.db.sync.receiver.manager.PipeMessage; import org.apache.iotdb.db.sync.receiver.manager.ReceiverManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** scan sync receiver folder and load pipeData into IoTDB */ public class Collector { private static final Logger logger = LoggerFactory.getLogger(Collector.class); private static final int WAIT_TIMEOUT = 2000; private ExecutorService executorService; private Map<String, Future> taskFutures; public Collector() { taskFutures = new ConcurrentHashMap<>(); } public void startCollect() { this.executorService = IoTDBThreadPoolFactory.newCachedThreadPool(ThreadName.SYNC_RECEIVER_COLLECTOR.getName()); } public void stopCollect() { for (Future f : taskFutures.values()) { f.cancel(true); } if (executorService != null) { executorService.shutdownNow(); int totalWaitTime = WAIT_TIMEOUT; while (!executorService.isTerminated()) { try { if (!executorService.awaitTermination(WAIT_TIMEOUT, TimeUnit.MILLISECONDS)) { logger.info( "{} thread pool doesn't exit after {}ms.", ThreadName.SYNC_RECEIVER_COLLECTOR.getName(), totalWaitTime); } totalWaitTime += WAIT_TIMEOUT; } catch (InterruptedException e) { logger.error( "Interrupted while waiting {} thread pool to exit. ", ThreadName.SYNC_RECEIVER_COLLECTOR.getName()); Thread.currentThread().interrupt(); } } executorService = null; } } public void startPipe(String pipeName, String remoteIp, long createTime) { String dir = SyncPathUtil.getReceiverPipeDirName(pipeName, remoteIp, createTime); synchronized (dir.intern()) { if (!taskFutures.containsKey(dir)) { ScanTask task = new ScanTask(pipeName, remoteIp, createTime); taskFutures.put(dir, executorService.submit(task)); } } } public void stopPipe(String pipeName, String remoteIp, long createTime) { String dir = SyncPathUtil.getReceiverPipeDirName(pipeName, remoteIp, createTime); logger.info("try stop task key={}", dir); synchronized (dir.intern()) { if (taskFutures.containsKey(dir)) { taskFutures.get(dir).cancel(true); taskFutures.remove(dir); logger.info("stop task success, key={}", dir); } } } private class ScanTask implements Runnable { private final String pipeName; private final String remoteIp; private final long createTime; private ScanTask(String pipeName, String remoteIp, long createTime) { this.pipeName = pipeName; this.remoteIp = remoteIp; this.createTime = createTime; } @Override public void run() { PipeDataQueue pipeDataQueue = PipeDataQueueFactory.getBufferedPipeDataQueue( SyncPathUtil.getReceiverPipeLogDir(pipeName, remoteIp, createTime)); while (!Thread.currentThread().isInterrupted()) { PipeData pipeData = null; try { pipeData = pipeDataQueue.take(); logger.info( "Start load pipeData with serialize number {} and type {},value={}", pipeData.getSerialNumber(), pipeData.getType(), pipeData); pipeData.createLoader().load(); pipeDataQueue.commit(); logger.info("Commit pipeData with serialize number {}", pipeData.getSerialNumber()); } catch (InterruptedException e) { logger.warn("Be interrupted when waiting for pipe data"); Thread.currentThread().interrupt(); break; } catch (PipeDataLoadBearableException e) { // bearable exception logger.warn(e.getMessage()); ReceiverManager.getInstance() .writePipeMessage( pipeName, remoteIp, createTime, new PipeMessage(PipeMessage.MsgType.WARN, e.getMessage())); pipeDataQueue.commit(); } catch (PipeDataLoadException e) { // unbearable exception // TODO: should drop this pipe? String msg; if (pipeData != null) { msg = String.format( "Cannot load pipeData with serialize number %d and type %s, because %s", pipeData.getSerialNumber(), pipeData.getType(), e.getMessage()); } else { msg = String.format("Cannot load pipeData because %s", e.getMessage()); } logger.error(msg); ReceiverManager.getInstance() .writePipeMessage( pipeName, remoteIp, createTime, new PipeMessage(PipeMessage.MsgType.ERROR, msg)); break; } } } } }
2,528
719
//#include "stdafx.h" #include "Bonsai.h" using namespace EdgeML; using namespace EdgeML::Bonsai; int main() { BonsaiModel::BonsaiHyperParams hyperParam; hyperParam.problemType = ProblemFormat::multiclass; hyperParam.dataformatType = DataFormat::interfaceIngestFormat; hyperParam.normalizationType = NormalizationFormat::none; hyperParam.seed = 41; hyperParam.batchSize = 1; hyperParam.iters = 20; hyperParam.epochs = 1; hyperParam.dataDimension = 784; hyperParam.projectionDimension = 30; hyperParam.numClasses = 10; hyperParam.nvalidation = 0; hyperParam.ntrain = 5000; hyperParam.Sigma = 1.0; hyperParam.treeDepth = 3; hyperParam.internalNodes = (pow(2, hyperParam.treeDepth) - 1); hyperParam.totalNodes = 2 * hyperParam.internalNodes + 1; hyperParam.regList.lW = 1.0e-3; hyperParam.regList.lZ = 1.0e-5; hyperParam.regList.lV = 1.0e-3; hyperParam.regList.lTheta = 1.0e-3; hyperParam.lambdaW = 10 / 30; hyperParam.lambdaZ = 150 / 785; hyperParam.lambdaV = 10 / 30; hyperParam.lambdaTheta = 10 / 30; hyperParam.finalizeHyperParams(); // trivial data set { BonsaiTrainer trainer(DataIngestType::InterfaceIngest, hyperParam); std::ifstream ifs("/home/t-vekusu/ICMLDatasets/multiclass/mnist/train"); FP_TYPE *trainvals = new FP_TYPE[hyperParam.dataDimension]; memset(trainvals, 0, sizeof(FP_TYPE)*(hyperParam.dataDimension)); FP_TYPE temp; // labelCount_t *temp1 = new labelCount_t[hyperParam.numClasses]; labelCount_t *labve = new labelCount_t[1]; for (int i = 0; i < hyperParam.ntrain; ++i) { int count = 0; ifs >> temp; // std::cout<<temp<<std::endl; labve[0] = (labelCount_t)temp; while (count < hyperParam.dataDimension) { ifs >> temp; trainvals[count] = temp; count++; } // std::cout<<labve[0]<<std::endl; labve[0]--; // std::cout<<labve[0]<<std::endl; // for(int j=0; j<hyperParam.numClasses; j++) { // ift >> temp1[j]; // if(temp1[j] != 0) { // labve[0] = j; // } // } trainer.feedDenseData(trainvals, labve, 1); // if(i%5000 == 0) std::cout<<i<<std::endl; } ifs.close(); trainer.finalizeData(); trainer.train(); // auto modelBytes = trainer.getModelSize(); // auto model = new char[modelBytes]; auto modelBytes = trainer.getSparseModelSize(); auto model = new char[modelBytes]; auto meanStdBytes = trainer.getMeanStdSize(); auto meanStd = new char[meanStdBytes]; // trainer.exportModel(modelBytes, model); trainer.exportSparseModel(modelBytes, model); trainer.exportMeanStd(meanStdBytes, meanStd); // BonsaiPredictor predictor(modelBytes, model); BonsaiPredictor predictor(modelBytes, model, false); predictor.importMeanStd(meanStdBytes, meanStd); FP_TYPE *scoreArray = new FP_TYPE[hyperParam.numClasses]; std::ifstream ifw("/home/t-vekusu/ICMLDatasets/multiclass/mnist/test"); int correct = 0; for (int i = 0; i < 10; ++i) { int count = 0; ifw >> temp; labve[0] = (labelCount_t)temp; while (count < hyperParam.dataDimension) { ifw >> temp; trainvals[count] = temp; count++; } predictor.scoreDenseDataPoint(scoreArray, trainvals); labelCount_t predLabel = 0; FP_TYPE max_score = scoreArray[0]; for (int j = 0; j < hyperParam.numClasses; j++) { if (max_score <= scoreArray[j]) { max_score = scoreArray[j]; predLabel = j; } } labve[0]--; if (labve[0] == predLabel) correct++; } std::cout << correct << std::endl; ifw.close(); std::cout << "Final Test Accuracy = " << ((FP_TYPE)correct) / ((FP_TYPE)10) << std::endl; delete[] scoreArray, trainvals, model, labve; } // // Slightly less trivial example // { // auto trainer = new BonsaiTrainer(DataIngestType::InterfaceIngest, hyperParam); // FP_TYPE trainPts[2*16] = {-1.1, -1.1, // 0.9, 1.1, // 1.1, 0.9, // -0.9, -0.9, // 1.1, 1.1, // 0.9, 1.1, // 1.1, 0.9, // 0.9, 0.9, // -1.1, 1.1, // -0.9, 1.1, // -1.1, 0.9, // -0.9, 0.9, // 1.1, -1.1, // 0.9, -1.1, // 1.1, -0.9, // 0.9, -0.9}; // Outlier // labelCount_t labels[3] = {0,1,2}; // for (int i=0; i<4; ++i) // trainer->feedDenseData (trainPts + 2*i, labels, 1); // for (int i=4; i<8; ++i) // trainer->feedDenseData (trainPts + 2*i, labels, 1); // for (int i=8; i<12; ++i) // trainer->feedDenseData (trainPts + 2*i, labels+1, 1); // for (int i=12; i<16; ++i) // trainer->feedDenseData (trainPts + 2*i, labels+2, 1); // trainer->finalizeData(); // // std::cout<<trainer->mean<<std::endl<<std::endl; // // std::cout<<trainer->stdDev<<std::endl<<std::endl; // trainer->train(); // auto modelBytes = trainer->getModelSize(); // auto model = new char[modelBytes]; // auto meanStdBytes = trainer->getMeanStdSize(); // auto meanStd = new char[meanStdBytes]; // trainer->exportModel(modelBytes, model); // trainer->exportMeanStd(meanStdBytes, meanStd); // auto predictor = new BonsaiPredictor(modelBytes, model); // predictor->importMeanStd(meanStdBytes, meanStd); // FP_TYPE scoreArray[3] = {0.0, 0.0, 0.0}; // FP_TYPE testPts[2*4] = {-1.0, -1.0, // 1.0, 1.0, // -1.0, 1.0, // 1.0, -1.0}; // for (int t=0; t<4; ++t) { // predictor->scoreDenseDataPoint(scoreArray, testPts + 2*t); // for(int i=0;i<3;++i) std::cout<<scoreArray[i]<<" ";std::cout<<std::endl; // } // delete[] model; // delete trainer, predictor; // } // // Slightly less trivial example for sparse data // { // auto trainer = new BonsaiTrainer(DataIngestType::InterfaceIngest, hyperParam); // featureCount_t indices[2] = {0, 1}; // int numIndices = 2; // FP_TYPE trainPts[2*17] = {-1.1, -1.1, // -0.9, -1.1, // -1.1, -0.9, // -0.9, -0.9, // 1.1, 1.1, // 0.9, 1.1, // 1.1, 0.9, // 0.9, 0.9, // -1.1, 1.1, // -0.9, 1.1, // -1.1, 0.9, // -0.9, 0.9, // 1.1, -1.1, // 0.9, -1.1, // 1.1, -0.9, // 0.9, -0.9, // 0.0, 0.0}; // Outlier // labelCount_t labels[3] = {0,1,2}; // for (int i=0; i<3; ++i) // trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels, 1); // trainer->feedSparseData (trainPts + 6, indices, numIndices, labels + 1, 1); // for (int i=4; i<7; ++i) // trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels, 1); // trainer->feedSparseData (trainPts + 14, indices, numIndices, labels + 2, 1); // for (int i=8; i<11; ++i) // trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels+1, 1); // trainer->feedSparseData (trainPts + 22, indices, numIndices, labels + 2, 1); // for (int i=12; i<15; ++i) // trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels+2, 1); // trainer->feedSparseData (trainPts + 30, indices, numIndices, labels + 1, 1); // trainer->feedSparseData (trainPts + 32, indices, numIndices, labels+2, 1); // trainer->finalizeData(); // trainer->train(); // auto modelBytes = trainer->getModelSize(); // auto model = new char[modelBytes]; // trainer->exportModel(modelBytes, model); // auto predictor = new BonsaiPredictor(modelBytes, model); // FP_TYPE scoreArray[3] = {0.0, 0.0, 0.0}; // FP_TYPE testPts[2*5] = {-1.0, -1.0, // 1.0, 1.0, // -1.0, 1.0, // 1.0, -1.0, // 0.5, 0.5}; // for (int t=0; t<5; ++t) { // predictor->scoreDenseDataPoint(scoreArray, testPts + 2*t); // for(int i=0;i<3;++i) std::cout<<scoreArray[i]<<" ";std::cout<<std::endl; // } // delete[] model; // delete trainer, predictor; // } // // Slightly less trivial example for sparse data // { // auto trainer = new BonsaiTrainer(DataIngestType::InterfaceIngest, hyperParam); // featureCount_t indices[2] = {0, 1}; // int numIndices = 2; // FP_TYPE trainPts[2*17] = {-1.1, -1.1, // -0.9, -1.1, // -1.1, -0.9, // -0.9, -0.9, // 1.1, 1.1, // 0.9, 1.1, // 1.1, 0.9, // 0.9, 0.9, // -1.1, 1.1, // -0.9, 1.1, // -1.1, 0.9, // -0.9, 0.9, // 1.1, -1.1, // 0.9, -1.1, // 1.1, -0.9, // 0.9, -0.9, // 0.0, 0.0}; // Outlier // labelCount_t labels[3] = {0,1,2}; // for (int i=0; i<3; ++i) // trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels, 1); // trainer->feedSparseData (trainPts + 6, indices, numIndices, labels + 1, 1); // for (int i=4; i<7; ++i) // trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels, 1); // trainer->feedSparseData (trainPts + 14, indices, numIndices, labels + 2, 1); // for (int i=8; i<11; ++i) // trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels+1, 1); // trainer->feedSparseData (trainPts + 22, indices, numIndices, labels + 2, 1); // for (int i=12; i<15; ++i) // trainer->feedSparseData (trainPts + 2*i, indices, numIndices, labels+2, 1); // trainer->feedSparseData (trainPts + 30, indices, numIndices, labels + 1, 1); // trainer->feedSparseData (trainPts + 32, indices, numIndices, labels+2, 1); // trainer->finalizeData(); // trainer->train(); // auto modelBytes = trainer->getModelSize(); // auto model = new char[modelBytes]; // trainer->exportModel(modelBytes, model); // auto predictor = new BonsaiPredictor(modelBytes, model); // FP_TYPE scoreArray[3] = {0.0, 0.0, 0.0}; // FP_TYPE testPts[2*5] = {-1.0, -1.0, // 1.0, 1.0, // -1.0, 1.0, // 1.0, -1.0, // 0.5, 0.5}; // for (int t=0; t<5; ++t) { // predictor->scoreSparseDataPoint(scoreArray, testPts + 2*t, indices, numIndices); // for(int i=0;i<3;++i) std::cout<<scoreArray[i]<<" ";std::cout<<std::endl; // } // delete[] model; // delete trainer, predictor; // } }
4,837
17,104
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: chat.proto package com.tencent.mars.sample.chat.proto; public final class Chat { private Chat() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface SendMessageRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:com.tencent.mars.sample.chat.proto.SendMessageRequest) com.google.protobuf.MessageOrBuilder { /** * <code>required string access_token = 1;</code> */ boolean hasAccessToken(); /** * <code>required string access_token = 1;</code> */ java.lang.String getAccessToken(); /** * <code>required string access_token = 1;</code> */ com.google.protobuf.ByteString getAccessTokenBytes(); /** * <code>required string from = 2;</code> */ boolean hasFrom(); /** * <code>required string from = 2;</code> */ java.lang.String getFrom(); /** * <code>required string from = 2;</code> */ com.google.protobuf.ByteString getFromBytes(); /** * <code>required string to = 3;</code> */ boolean hasTo(); /** * <code>required string to = 3;</code> */ java.lang.String getTo(); /** * <code>required string to = 3;</code> */ com.google.protobuf.ByteString getToBytes(); /** * <code>required string text = 4;</code> */ boolean hasText(); /** * <code>required string text = 4;</code> */ java.lang.String getText(); /** * <code>required string text = 4;</code> */ com.google.protobuf.ByteString getTextBytes(); } /** * Protobuf type {@code com.tencent.mars.sample.chat.proto.SendMessageRequest} */ public static final class SendMessageRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:com.tencent.mars.sample.chat.proto.SendMessageRequest) SendMessageRequestOrBuilder { // Use SendMessageRequest.newBuilder() to construct. private SendMessageRequest(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private SendMessageRequest(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final SendMessageRequest defaultInstance; public static SendMessageRequest getDefaultInstance() { return defaultInstance; } public SendMessageRequest getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SendMessageRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000001; accessToken_ = bs; break; } case 18: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000002; from_ = bs; break; } case 26: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000004; to_ = bs; break; } case 34: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000008; text_ = bs; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest.class, com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest.Builder.class); } public static com.google.protobuf.Parser<SendMessageRequest> PARSER = new com.google.protobuf.AbstractParser<SendMessageRequest>() { public SendMessageRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SendMessageRequest(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<SendMessageRequest> getParserForType() { return PARSER; } private int bitField0_; public static final int ACCESS_TOKEN_FIELD_NUMBER = 1; private java.lang.Object accessToken_; /** * <code>required string access_token = 1;</code> */ public boolean hasAccessToken() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string access_token = 1;</code> */ public java.lang.String getAccessToken() { java.lang.Object ref = accessToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { accessToken_ = s; } return s; } } /** * <code>required string access_token = 1;</code> */ public com.google.protobuf.ByteString getAccessTokenBytes() { java.lang.Object ref = accessToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); accessToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FROM_FIELD_NUMBER = 2; private java.lang.Object from_; /** * <code>required string from = 2;</code> */ public boolean hasFrom() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required string from = 2;</code> */ public java.lang.String getFrom() { java.lang.Object ref = from_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { from_ = s; } return s; } } /** * <code>required string from = 2;</code> */ public com.google.protobuf.ByteString getFromBytes() { java.lang.Object ref = from_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); from_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TO_FIELD_NUMBER = 3; private java.lang.Object to_; /** * <code>required string to = 3;</code> */ public boolean hasTo() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required string to = 3;</code> */ public java.lang.String getTo() { java.lang.Object ref = to_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { to_ = s; } return s; } } /** * <code>required string to = 3;</code> */ public com.google.protobuf.ByteString getToBytes() { java.lang.Object ref = to_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); to_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TEXT_FIELD_NUMBER = 4; private java.lang.Object text_; /** * <code>required string text = 4;</code> */ public boolean hasText() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>required string text = 4;</code> */ public java.lang.String getText() { java.lang.Object ref = text_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { text_ = s; } return s; } } /** * <code>required string text = 4;</code> */ public com.google.protobuf.ByteString getTextBytes() { java.lang.Object ref = text_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); text_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { accessToken_ = ""; from_ = ""; to_ = ""; text_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (!hasAccessToken()) { memoizedIsInitialized = 0; return false; } if (!hasFrom()) { memoizedIsInitialized = 0; return false; } if (!hasTo()) { memoizedIsInitialized = 0; return false; } if (!hasText()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getAccessTokenBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getFromBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getToBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeBytes(4, getTextBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getAccessTokenBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getFromBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getToBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(4, getTextBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code com.tencent.mars.sample.chat.proto.SendMessageRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:com.tencent.mars.sample.chat.proto.SendMessageRequest) com.tencent.mars.sample.chat.proto.Chat.SendMessageRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest.class, com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest.Builder.class); } // Construct using com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); accessToken_ = ""; bitField0_ = (bitField0_ & ~0x00000001); from_ = ""; bitField0_ = (bitField0_ & ~0x00000002); to_ = ""; bitField0_ = (bitField0_ & ~0x00000004); text_ = ""; bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_descriptor; } public com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest getDefaultInstanceForType() { return com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest.getDefaultInstance(); } public com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest build() { com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest buildPartial() { com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest result = new com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.accessToken_ = accessToken_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.from_ = from_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.to_ = to_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.text_ = text_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest) { return mergeFrom((com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest other) { if (other == com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest.getDefaultInstance()) return this; if (other.hasAccessToken()) { bitField0_ |= 0x00000001; accessToken_ = other.accessToken_; onChanged(); } if (other.hasFrom()) { bitField0_ |= 0x00000002; from_ = other.from_; onChanged(); } if (other.hasTo()) { bitField0_ |= 0x00000004; to_ = other.to_; onChanged(); } if (other.hasText()) { bitField0_ |= 0x00000008; text_ = other.text_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasAccessToken()) { return false; } if (!hasFrom()) { return false; } if (!hasTo()) { return false; } if (!hasText()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.tencent.mars.sample.chat.proto.Chat.SendMessageRequest) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object accessToken_ = ""; /** * <code>required string access_token = 1;</code> */ public boolean hasAccessToken() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string access_token = 1;</code> */ public java.lang.String getAccessToken() { java.lang.Object ref = accessToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { accessToken_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>required string access_token = 1;</code> */ public com.google.protobuf.ByteString getAccessTokenBytes() { java.lang.Object ref = accessToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); accessToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string access_token = 1;</code> */ public Builder setAccessToken( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; accessToken_ = value; onChanged(); return this; } /** * <code>required string access_token = 1;</code> */ public Builder clearAccessToken() { bitField0_ = (bitField0_ & ~0x00000001); accessToken_ = getDefaultInstance().getAccessToken(); onChanged(); return this; } /** * <code>required string access_token = 1;</code> */ public Builder setAccessTokenBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; accessToken_ = value; onChanged(); return this; } private java.lang.Object from_ = ""; /** * <code>required string from = 2;</code> */ public boolean hasFrom() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required string from = 2;</code> */ public java.lang.String getFrom() { java.lang.Object ref = from_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { from_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>required string from = 2;</code> */ public com.google.protobuf.ByteString getFromBytes() { java.lang.Object ref = from_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); from_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string from = 2;</code> */ public Builder setFrom( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; from_ = value; onChanged(); return this; } /** * <code>required string from = 2;</code> */ public Builder clearFrom() { bitField0_ = (bitField0_ & ~0x00000002); from_ = getDefaultInstance().getFrom(); onChanged(); return this; } /** * <code>required string from = 2;</code> */ public Builder setFromBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; from_ = value; onChanged(); return this; } private java.lang.Object to_ = ""; /** * <code>required string to = 3;</code> */ public boolean hasTo() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required string to = 3;</code> */ public java.lang.String getTo() { java.lang.Object ref = to_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { to_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>required string to = 3;</code> */ public com.google.protobuf.ByteString getToBytes() { java.lang.Object ref = to_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); to_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string to = 3;</code> */ public Builder setTo( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; to_ = value; onChanged(); return this; } /** * <code>required string to = 3;</code> */ public Builder clearTo() { bitField0_ = (bitField0_ & ~0x00000004); to_ = getDefaultInstance().getTo(); onChanged(); return this; } /** * <code>required string to = 3;</code> */ public Builder setToBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; to_ = value; onChanged(); return this; } private java.lang.Object text_ = ""; /** * <code>required string text = 4;</code> */ public boolean hasText() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>required string text = 4;</code> */ public java.lang.String getText() { java.lang.Object ref = text_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { text_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>required string text = 4;</code> */ public com.google.protobuf.ByteString getTextBytes() { java.lang.Object ref = text_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); text_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string text = 4;</code> */ public Builder setText( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; text_ = value; onChanged(); return this; } /** * <code>required string text = 4;</code> */ public Builder clearText() { bitField0_ = (bitField0_ & ~0x00000008); text_ = getDefaultInstance().getText(); onChanged(); return this; } /** * <code>required string text = 4;</code> */ public Builder setTextBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; text_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.tencent.mars.sample.chat.proto.SendMessageRequest) } static { defaultInstance = new SendMessageRequest(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:com.tencent.mars.sample.chat.proto.SendMessageRequest) } public interface SendMessageResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:com.tencent.mars.sample.chat.proto.SendMessageResponse) com.google.protobuf.MessageOrBuilder { /** * <code>required int32 err_code = 1;</code> */ boolean hasErrCode(); /** * <code>required int32 err_code = 1;</code> */ int getErrCode(); /** * <code>required string err_msg = 2;</code> */ boolean hasErrMsg(); /** * <code>required string err_msg = 2;</code> */ java.lang.String getErrMsg(); /** * <code>required string err_msg = 2;</code> */ com.google.protobuf.ByteString getErrMsgBytes(); } /** * Protobuf type {@code com.tencent.mars.sample.chat.proto.SendMessageResponse} */ public static final class SendMessageResponse extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:com.tencent.mars.sample.chat.proto.SendMessageResponse) SendMessageResponseOrBuilder { // Use SendMessageResponse.newBuilder() to construct. private SendMessageResponse(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private SendMessageResponse(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final SendMessageResponse defaultInstance; public static SendMessageResponse getDefaultInstance() { return defaultInstance; } public SendMessageResponse getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SendMessageResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; errCode_ = input.readInt32(); break; } case 18: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000002; errMsg_ = bs; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse.class, com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse.Builder.class); } public static com.google.protobuf.Parser<SendMessageResponse> PARSER = new com.google.protobuf.AbstractParser<SendMessageResponse>() { public SendMessageResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SendMessageResponse(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<SendMessageResponse> getParserForType() { return PARSER; } /** * Protobuf enum {@code com.tencent.mars.sample.chat.proto.SendMessageResponse.Error} */ public enum Error implements com.google.protobuf.ProtocolMessageEnum { /** * <code>ERR_OK = 0;</code> */ ERR_OK(0, 0), /** * <code>ERR_SYS = -1;</code> */ ERR_SYS(1, -1), ; /** * <code>ERR_OK = 0;</code> */ public static final int ERR_OK_VALUE = 0; /** * <code>ERR_SYS = -1;</code> */ public static final int ERR_SYS_VALUE = -1; public final int getNumber() { return value; } public static Error valueOf(int value) { switch (value) { case 0: return ERR_OK; case -1: return ERR_SYS; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Error> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<Error> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Error>() { public Error findValueByNumber(int number) { return Error.valueOf(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse.getDescriptor().getEnumTypes().get(0); } private static final Error[] VALUES = values(); public static Error valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private Error(int index, int value) { this.index = index; this.value = value; } // @@protoc_insertion_point(enum_scope:com.tencent.mars.sample.chat.proto.SendMessageResponse.Error) } private int bitField0_; public static final int ERR_CODE_FIELD_NUMBER = 1; private int errCode_; /** * <code>required int32 err_code = 1;</code> */ public boolean hasErrCode() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int32 err_code = 1;</code> */ public int getErrCode() { return errCode_; } public static final int ERR_MSG_FIELD_NUMBER = 2; private java.lang.Object errMsg_; /** * <code>required string err_msg = 2;</code> */ public boolean hasErrMsg() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required string err_msg = 2;</code> */ public java.lang.String getErrMsg() { java.lang.Object ref = errMsg_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { errMsg_ = s; } return s; } } /** * <code>required string err_msg = 2;</code> */ public com.google.protobuf.ByteString getErrMsgBytes() { java.lang.Object ref = errMsg_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); errMsg_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { errCode_ = 0; errMsg_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (!hasErrCode()) { memoizedIsInitialized = 0; return false; } if (!hasErrMsg()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeInt32(1, errCode_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getErrMsgBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, errCode_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getErrMsgBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code com.tencent.mars.sample.chat.proto.SendMessageResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:com.tencent.mars.sample.chat.proto.SendMessageResponse) com.tencent.mars.sample.chat.proto.Chat.SendMessageResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse.class, com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse.Builder.class); } // Construct using com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); errCode_ = 0; bitField0_ = (bitField0_ & ~0x00000001); errMsg_ = ""; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.tencent.mars.sample.chat.proto.Chat.internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_descriptor; } public com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse getDefaultInstanceForType() { return com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse.getDefaultInstance(); } public com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse build() { com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse buildPartial() { com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse result = new com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.errCode_ = errCode_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.errMsg_ = errMsg_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse) { return mergeFrom((com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse other) { if (other == com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse.getDefaultInstance()) return this; if (other.hasErrCode()) { setErrCode(other.getErrCode()); } if (other.hasErrMsg()) { bitField0_ |= 0x00000002; errMsg_ = other.errMsg_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasErrCode()) { return false; } if (!hasErrMsg()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.tencent.mars.sample.chat.proto.Chat.SendMessageResponse) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private int errCode_ ; /** * <code>required int32 err_code = 1;</code> */ public boolean hasErrCode() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int32 err_code = 1;</code> */ public int getErrCode() { return errCode_; } /** * <code>required int32 err_code = 1;</code> */ public Builder setErrCode(int value) { bitField0_ |= 0x00000001; errCode_ = value; onChanged(); return this; } /** * <code>required int32 err_code = 1;</code> */ public Builder clearErrCode() { bitField0_ = (bitField0_ & ~0x00000001); errCode_ = 0; onChanged(); return this; } private java.lang.Object errMsg_ = ""; /** * <code>required string err_msg = 2;</code> */ public boolean hasErrMsg() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required string err_msg = 2;</code> */ public java.lang.String getErrMsg() { java.lang.Object ref = errMsg_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { errMsg_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>required string err_msg = 2;</code> */ public com.google.protobuf.ByteString getErrMsgBytes() { java.lang.Object ref = errMsg_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); errMsg_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string err_msg = 2;</code> */ public Builder setErrMsg( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; errMsg_ = value; onChanged(); return this; } /** * <code>required string err_msg = 2;</code> */ public Builder clearErrMsg() { bitField0_ = (bitField0_ & ~0x00000002); errMsg_ = getDefaultInstance().getErrMsg(); onChanged(); return this; } /** * <code>required string err_msg = 2;</code> */ public Builder setErrMsgBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; errMsg_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.tencent.mars.sample.chat.proto.SendMessageResponse) } static { defaultInstance = new SendMessageResponse(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:com.tencent.mars.sample.chat.proto.SendMessageResponse) } private static final com.google.protobuf.Descriptors.Descriptor internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\nchat.proto\022\"com.tencent.mars.sample.ch" + "at.proto\"R\n\022SendMessageRequest\022\024\n\014access" + "_token\030\001 \002(\t\022\014\n\004from\030\002 \002(\t\022\n\n\002to\030\003 \002(\t\022\014" + "\n\004text\030\004 \002(\t\"c\n\023SendMessageResponse\022\020\n\010e" + "rr_code\030\001 \002(\005\022\017\n\007err_msg\030\002 \002(\t\")\n\005Error\022" + "\n\n\006ERR_OK\020\000\022\024\n\007ERR_SYS\020\377\377\377\377\377\377\377\377\377\001" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_com_tencent_mars_sample_chat_proto_SendMessageRequest_descriptor, new java.lang.String[] { "AccessToken", "From", "To", "Text", }); internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_com_tencent_mars_sample_chat_proto_SendMessageResponse_descriptor, new java.lang.String[] { "ErrCode", "ErrMsg", }); } // @@protoc_insertion_point(outer_class_scope) }
25,485
1,788
package com.fingerchar.storage; import java.io.InputStream; import java.nio.file.Path; import java.util.stream.Stream; import org.springframework.core.io.Resource; public class StorageAdaptor implements Storage { @Override public void store(InputStream inputStream, long contentLength, String contentType, String keyName) { // TODO Auto-generated method stub } @Override public String store(InputStream inputStream, String fileName) { // TODO Auto-generated method stub return null; } @Override public Stream<Path> loadAll() { // TODO Auto-generated method stub return null; } @Override public Path load(String keyName) { // TODO Auto-generated method stub return null; } @Override public Resource loadAsResource(String keyName) { // TODO Auto-generated method stub return null; } @Override public void delete(String keyName) { // TODO Auto-generated method stub } @Override public String generateUrl(String keyName) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see com.fingerchar.core.storage.Storage#store(java.io.InputStream[], * java.lang.String[]) */ @Override public String[] store(InputStream[] inputStreams, String[] fileNames, String dirPath) { // TODO Auto-generated method stub return null; } }
426
435
<gh_stars>100-1000 { "description": "Quelle structure JSON pour mon API ? Quelle syntaxe pour filtrer la\n liste via la querystring ? Comment g\u00e9rer les \u00e9critures concurrentes\n ? Et synchroniser les donn\u00e9es dans mon application cliente ?\n\nQuand nous d\u00e9veloppons un (micro)service Web, nous d\u00e9pensons\ng\u00e9n\u00e9ralement beaucoup d'\u00e9nergie dans la conception et la validation du\nprotocole HTTP, en particulier lorsqu'il s'agit d'un service qui\nmanipule des donn\u00e9es (*CRUD, offline first, pagination, ...*).\n\n Comment pouvons-nous v\u00e9rifier que le service est op\u00e9rationnel ?\n Quels indicateurs StatsD ? Est-ce que Sentry est bien configur\u00e9 ?\n Comment mettre \u00e0 jour sans casser les applications clientes ?\n\nDe m\u00eame, nous passons beaucoup de temps (ou pire, nous ne le faisons pas\n!) \u00e0 mettre en place tout l'outillage pour g\u00e9rer et superviser la mise\nen production du service. Et si les bonnes pratiques \u00e9voluent, il faut\nfaire suivre les projets d\u00e9j\u00e0 en place.\n\nPlut\u00f4t qu'\u00e9crire un \u00e9ni\u00e8me article de blog avec nos recommandations,\nnous avons fait le choix de mettre au point un protocole, et d'en\nfournir une impl\u00e9mentation en Python.\n\n*Cliquet* est donc un kit de d\u00e9marrage, bas\u00e9 sur Pyramid, pour\nconstruire des (micro)services en se concentrant sur l'essentiel.\n", "duration": 1778, "language": "fra", "recorded": "2015-10-17", "speakers": [ "<NAME>", "<NAME>\u00e9taireau", "R\u00e9<NAME>" ], "summary": "Bas\u00e9 sur Pyramid, Cliquet est un projet qui permet de se concentrer sur\nl'essentiel lors de la conception d'APIs.\n", "thumbnail_url": "http://dl.afpy.org/pycon-fr-15/013%20-%20Mathieu%20Leplatre,%20Alexis%20M%C3%A9taireau,%20R%C3%A9my%20Hubscher%20-%20Cliquet:%20un%20toolkit%20pour%20construire%20des%20(micro)services.mp4.jpg", "title": "Cliquet: un toolkit pour construire des (micro)services", "videos": [ { "type": "ogv", "url": "http://dl.afpy.org/pycon-fr-15/013%20-%20Mathieu%20Leplatre,%20Alexis%20M%C3%A9taireau,%20R%C3%A9my%20Hubscher%20-%20Cliquet:%20un%20toolkit%20pour%20construire%20des%20(micro)services.ogv" }, { "type": "mp4", "url": "http://dl.afpy.org/pycon-fr-15/013%20-%20Mathieu%20Leplatre,%20Alexis%20M%C3%A9taireau,%20R%C3%A9my%20Hubscher%20-%20Cliquet:%20un%20toolkit%20pour%20construire%20des%20(micro)services.mp4" }, { "type": "webm", "url": "http://dl.afpy.org/pycon-fr-15/013%20-%20Mathieu%20Leplatre,%20Alexis%20M%C3%A9taireau,%20R%C3%A9my%20Hubscher%20-%20Cliquet:%20un%20toolkit%20pour%20construire%20des%20(micro)services.webm" } ] }
1,229
5,169
{ "name": "UIMenuScroll", "version": "0.0.1", "summary": "UIMenuScroll creating menu how on Facebook Messenger on take photo", "authors": "AlekseyPleshkov <<EMAIL>>", "homepage": "https://github.com/AlekseyPleshkov/UIMenuScroll", "license": "MIT", "source": { "git": "https://github.com/AlekseyPleshkov/UIMenuScroll.git", "branch": "master", "tag": "0.0.1" }, "platforms": { "ios": "10.0" }, "source_files": "UIMenuScroll/*.{h,m,swift}", "requires_arc": true, "frameworks": "UIKit", "swift_version": "4.2" }
241
679
<gh_stars>100-1000 package org.togglz.core.repository.property; import java.util.Set; /** * Manages a source of property-like values. */ public interface PropertySource { /** * Reloads the properties from the source if they have been changed since the last load. */ void reloadIfUpdated(); /** * Returns the keys from the source that start with the specified prefix. * * @param prefix the prefix to find * @return the keys starting with the specified prefix; an empty collection if no keys are found */ Set<String> getKeysStartingWith(String prefix); /** * Returns the value of the specified key. If the key is not found the specified default value * is returned. * * @param key the key * @param defaultValue the default value if the key is not found * @return the value for the key */ String getValue(String key, String defaultValue); /** * Returns a class suitable for editing the properties in the underlying representation in a * thread-safe manner. * * @return an editor instance * @throws UnsupportedOperationException if this property source does not support updates */ Editor getEditor(); /** * Provides a means to update the underlying store in a thread-safe manner. */ interface Editor { /** * Sets the specified key to the specified value. * * @param key the key * @param value the value */ void setValue(String key, String value); /** * Removes all keys with the specified prefix. * * @param prefix the key prefix to remove */ void removeKeysStartingWith(String prefix); /** * Saves all changes to the underlying store. */ public void commit(); } }
705
547
<reponame>g2giovanni/xarray-spatial from xrspatial import bump def test_bump(): bumps = bump(20, 20) assert bumps is not None
54
638
// Copyright 2017, Additive Regularization of Topic Models. // Author: <NAME> (<EMAIL>) #include <string> #include <vector> #include <utility> #include "artm/core/protobuf_helpers.h" #include "artm/core/phi_matrix.h" #include "artm/regularizer/decorrelator_phi.h" namespace artm { namespace regularizer { bool DecorrelatorPhi::RegularizePhi(const ::artm::core::PhiMatrix& p_wt, const ::artm::core::PhiMatrix& n_wt, ::artm::core::PhiMatrix* r_wt, const float* tau) { // read the parameters from config and control their correctness const bool use_topic_pairs = (topic_pairs_.size() > 0); std::unordered_map<std::string, int> topics_to_regularize; if (!use_topic_pairs) { for (const auto& s : (config_.topic_name().size() ? config_.topic_name() : p_wt.topic_name())) { bool valid_topic = false; for (int i = 0; i < p_wt.topic_name().size(); ++i) { if (p_wt.topic_name(i) == s) { topics_to_regularize.insert(std::make_pair(s, i)); valid_topic = true; break; } } if (!valid_topic) { LOG(WARNING) << "Topic name " << s << " is not presented into model and will be ignored"; } } } std::unordered_map<std::string, int> all_topics; for (int i = 0; i < p_wt.topic_name().size(); ++i) { all_topics.insert(std::make_pair(p_wt.topic_name(i), i)); } bool use_all_classes = false; if (config_.class_id_size() == 0) { use_all_classes = true; } // proceed the regularization for (int token_pwt_id = 0; token_pwt_id < p_wt.token_size(); ++token_pwt_id) { const auto& token = p_wt.token(token_pwt_id); if (!use_all_classes && !core::is_member(token.class_id, config_.class_id())) { continue; } int token_nwt_id = n_wt.token_index(token); if (token_nwt_id == -1) { continue; } // count sum of weights float weights_sum = 0.0f; // simple case (without topic_pairs) if (!use_topic_pairs) { // create general normalizer for (const auto& pair : topics_to_regularize) { weights_sum += p_wt.get(token_pwt_id, pair.second); } // process every topic from topic_names for (const auto& pair : topics_to_regularize) { float weight = p_wt.get(token_pwt_id, pair.second); float value = static_cast<float>(-weight * (weights_sum - weight)); r_wt->increase(token_nwt_id, pair.second, value * (tau != nullptr ? *tau : 1.0f)); } } else { // complex case for (const auto& pair : topic_pairs_) { weights_sum = 0.0f; // check given topic exists in model auto first_iter = all_topics.find(pair.first); if (first_iter == all_topics.end()) { continue; } // create custom normilizer for this topic for (const auto& topic_and_value : pair.second) { auto second_iter = all_topics.find(topic_and_value.first); if (second_iter == all_topics.end()) { continue; } weights_sum += p_wt.get(token_pwt_id, second_iter->second) * topic_and_value.second; } // process this topic value float weight = p_wt.get(token_pwt_id, first_iter->second); float value = static_cast<float>(-weight * (weights_sum - weight)); r_wt->increase(token_nwt_id, first_iter->second, value * (tau != nullptr ? *tau : 1.0f)); } } } return true; } google::protobuf::RepeatedPtrField<std::string> DecorrelatorPhi::topics_to_regularize() { return config_.topic_name(); } google::protobuf::RepeatedPtrField<std::string> DecorrelatorPhi::class_ids_to_regularize() { return config_.class_id(); } void DecorrelatorPhi::UpdateTopicPairs(const DecorrelatorPhiConfig& config) { config_.clear_first_topic_name(); config_.clear_second_topic_name(); config_.clear_value(); topic_pairs_.clear(); int topics_len = config.first_topic_name_size(); if (topics_len) { if (topics_len != config.second_topic_name_size() || topics_len != config.value_size()) { BOOST_THROW_EXCEPTION(::artm::core::CorruptedMessageException( "Both topic indices and value arrays should have the same length")); } for (int i = 0; i < topics_len; ++i) { std::string first_name = config.first_topic_name(i); auto iter = topic_pairs_.find(first_name); if (iter == topic_pairs_.end()) { topic_pairs_.insert(std::make_pair(first_name, std::unordered_map<std::string, float>())); iter = topic_pairs_.find(first_name); } iter->second.insert(std::make_pair(config.second_topic_name(i), config.value(i))); } } } bool DecorrelatorPhi::Reconfigure(const RegularizerConfig& config) { std::string config_blob = config.config(); DecorrelatorPhiConfig regularizer_config; if (!regularizer_config.ParseFromString(config_blob)) { BOOST_THROW_EXCEPTION(::artm::core::CorruptedMessageException( "Unable to parse DecorrelatorPhiConfig from RegularizerConfig.config")); } config_.CopyFrom(regularizer_config); UpdateTopicPairs(regularizer_config); return true; } } // namespace regularizer } // namespace artm
2,220
1,447
<filename>users-api/src/main/java/com/elgris/usersapi/configuration/SecurityConfiguration.java<gh_stars>1000+ package com.elgris.usersapi.configuration; import com.elgris.usersapi.security.JwtAuthenticationFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) class HttpSecurityConfiguration { @Configuration public static class ApiConfigurerAdatper extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationFilter jwtAuthenticationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.antMatcher("/**") .addFilterAfter(jwtAuthenticationFilter, BasicAuthenticationFilter.class); } } }
406
2,151
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" #include "ui/base/ui_base_export.h" // A class that handles saving and restoring focus. An instance of // this class snapshots the currently focused view when it is // constructed, and callers can use restoreFocus to return focus to // that view. FocusTracker will not restore focus to views that are // no longer in the view hierarchy or are not in the correct window. UI_BASE_EXPORT @interface FocusTracker : NSObject { @private base::scoped_nsobject<NSView> focusedView_; } // |window| is the window that we are saving focus for. This // method snapshots the currently focused view. - (id)initWithWindow:(NSWindow*)window; // Attempts to restore focus to the snapshotted view. Returns YES if // focus was restored. Will not restore focus if the view is no // longer in the view hierarchy under |window|. - (BOOL)restoreFocusInWindow:(NSWindow*)window; @end
318
1,232
# Author: <NAME> # 83. Remove Duplicates from Sorted List # Given a sorted linked list, delete all duplicates such that each element appear only once. # # For example, # Given 1->1->2, return 1->2. # Given 1->1->2->3->3, return 1->2->3. # 思路,不需要删除这个Node,只需要将Pointer指向之后的一个Node就行 # 中间有个容易出错的就是,不要每次While循环,自动位移当前的Pointer # 在比对完当前Node和后面的所有Node直到没有重复的时候 # 再 cur = cur.next # **************** # Final Solution * # **************** class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ cur = head while cur and cur.next: if cur.val == cur.next.val: cur.next = cur.next.next else: cur = cur.next return head # *************************************** # The following code is an fail attempt * # *************************************** class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ cur = head while cur and cur.next: if cur.val == cur.next.val: cur.next = cur.next.next #问题出在这里 #cur不应该在每次比对以后直接位移,应该等没有 #duplicate以后再位移,所以这里要加Else #不加的后果是,底下之中corner case会失败: [1,1,1] cur = cur.next return head
810
453
/* * Copyright (c) 2011 <NAME> * * BSD license: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #define DREADY 1 #define TREADY 4 extern volatile int *console; void outbyte (int c) { volatile int *rxstat; volatile int *rxadata; int rxmask; while ((console[1] & TREADY) == 0); console[0] = (0x0ff & c); if (c == '\n') { while ((console[1] & TREADY) == 0); console[0] = (int) '\r'; } } int inbyte (void) { if (!console) return (0); while (!(console[1] & DREADY)); return console[0]; }
492
328
package com.stx.xhb.dmgameapp.mvp.contract; import com.stx.core.mvp.IModel; import com.stx.core.mvp.IView; import com.stx.xhb.dmgameapp.data.entity.CommentListBean; /** * @author: xiaohaibin. * @time: 2018/2/11 * @mail:<EMAIL> * @github:https://github.com/xiaohaibin * @describe: */ public interface GetCommentListContract { interface Model extends IModel { void getCommentListData(int currentPage, String arcurl, int uid); void postComment(String arcurl,String comment, int uid); void replyComment(String uid, int id, String arcurl, String content); } interface View extends IView { void setCommentListData(CommentListBean commentListData); void getCommentListDataFailed(); void postCommentSuccess(); void postCommentFailed(String msg); void showLoading(); void hideLoading(); } }
340
312
# Generated by Django 2.0.12 on 2019-11-25 10:29 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('forum', '0018_auto_20190821_1126'), ] operations = [ migrations.AlterField( model_name='priority', name='id', field=models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False), ), ]
194
625
package jtransc.jtransc.nativ; public class JTranscDNativeMixedTest { static public void main(String[] args) { JTranscReinterpretArrays.main(args); //DDynamic.global("writefln").call("Hello from DDynamic!"); } }
79
494
package com.icegreen.greenmail.imap.commands; import com.icegreen.greenmail.imap.ImapRequestLineReader; import com.icegreen.greenmail.imap.ProtocolException; /** * Created on 10/03/2016. * * @author Reda.Housni-Alaoui */ class SortCommandParser extends CommandParser { private final SearchCommandParser searchCommandParser = new SearchCommandParser(); public SortTerm sortTerm(ImapRequestLineReader request) throws ProtocolException { SortTerm sortTerm = new SortTerm(); /* Sort criteria */ char next = request.nextChar(); StringBuilder sb = new StringBuilder(); boolean buffering = false; while (next != '\n') { if (next != '(' && next != ')' && next != 32 /* space */ && next != 13 /* cr */) { sb.append(next); } else { if (buffering) { sortTerm.getSortCriteria().add(SortKey.valueOf(sb.toString())); sb = new StringBuilder(); } else { buffering = next == '('; } } request.consume(); if (next == ')') { break; } next = request.nextChar(); } /* Charset */ sortTerm.setCharset(consumeWord(request, new AtomCharValidator())); /* Search term */ sortTerm.setSearchTerm(searchCommandParser.searchTerm(request)); searchCommandParser.endLine(request); return sortTerm; } }
681
410
<gh_stars>100-1000 /* SPDX-License-Identifier: BSD-2-Clause */ /******************************************************************************* * Copyright 2017-2018, Fraunhofer SIT sponsored by Infineon Technologies AG * All rights reserved. *******************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include "tss2_fapi.h" #include "tss2_esys.h" #include "test-fapi.h" #include "fapi_util.h" #include "fapi_int.h" #include "tss2_esys.h" #include "esys_iutil.h" #define LOGMODULE test #include "util/log.h" #include "util/aux_util.h" #include "tss2_mu.h" #include "fapi_int.h" /** Test the FAPI cleanup in an error case. * * Tested FAPI commands: * - Fapi_Provision() * * @param[in,out] context The FAPI_CONTEXT. * @retval EXIT_FAILURE * @retval EXIT_SUCCESS */ int test_fapi_test_provisioning_error(FAPI_CONTEXT *context) { TSS2_RC r; r = Fapi_Provision(context, NULL, NULL, NULL); if ((r & ~TPM2_RC_N_MASK) == (TPM2_RC_NV_DEFINED & ~TPM2_RC_N_MASK)) return EXIT_SUCCESS; goto_if_error(r, "Error Fapi_Provision", error); return EXIT_FAILURE; error: Fapi_Delete(context, "/"); return EXIT_FAILURE; } int test_invoke_fapi(FAPI_CONTEXT *fapi_context) { return test_fapi_test_provisioning_error(fapi_context); }
545
1,403
package [PACKAGE]; import javafx.application.Application; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import java.util.ResourceBundle; public class [CLASS_NAME] extends Application { public static final ResourceBundle RES = ResourceBundle.getBundle("locale.[PLUGIN_NAME]"); public static void main(String[] args) { launch([CLASS_NAME].class, args); } @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load([CLASS_NAME].class.getResource("/fxml/[PLUGIN_NAME].fxml")); primaryStage.setTitle(RES.getString("Title")); primaryStage.setScene(new Scene(root, 800, 500)); primaryStage.show(); } }
285
16,259
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from torch import nn class SamePad(nn.Module): def __init__(self, kernel_size, causal=False): super().__init__() if causal: self.remove = kernel_size - 1 else: self.remove = 1 if kernel_size % 2 == 0 else 0 def forward(self, x): if self.remove > 0: x = x[:, :, : -self.remove] return x
224
839
/** * 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.cxf.rs.security.oauth2.grants.owner; import javax.ws.rs.core.MultivaluedMap; import org.apache.cxf.jaxrs.ext.MessageContext; import org.apache.cxf.rs.security.oauth2.common.Client; import org.apache.cxf.rs.security.oauth2.common.OAuthError; import org.apache.cxf.rs.security.oauth2.common.ServerAccessToken; import org.apache.cxf.rs.security.oauth2.common.UserSubject; import org.apache.cxf.rs.security.oauth2.grants.AbstractGrantHandler; import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException; import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants; import org.apache.cxf.rs.security.oauth2.utils.OAuthUtils; /** * The "resource owner" grant handler */ public class ResourceOwnerGrantHandler extends AbstractGrantHandler { private ResourceOwnerLoginHandler loginHandler; public ResourceOwnerGrantHandler() { super(OAuthConstants.RESOURCE_OWNER_GRANT); } public ServerAccessToken createAccessToken(Client client, MultivaluedMap<String, String> params) throws OAuthServiceException { String ownerName = params.getFirst(OAuthConstants.RESOURCE_OWNER_NAME); String ownerPassword = params.getFirst(OAuthConstants.RESOURCE_OWNER_PASSWORD); if (ownerName == null || ownerPassword == null) { throw new OAuthServiceException( new OAuthError(OAuthConstants.INVALID_REQUEST)); } UserSubject subject = loginHandler.createSubject(client, ownerName, ownerPassword); if (subject == null) { throw new OAuthServiceException(OAuthConstants.INVALID_GRANT); } return doCreateAccessToken(client, subject, params); } public ResourceOwnerLoginHandler getLoginHandler() { return this.loginHandler; } public void setLoginHandler(ResourceOwnerLoginHandler loginHandler) { this.loginHandler = loginHandler; } public void setMessageContext(MessageContext context) { if (loginHandler != null) { OAuthUtils.injectContextIntoOAuthProvider(context, loginHandler); } } }
964
3,402
<reponame>ApacheSourceCode/kylin /* * 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.kylin.query.routing; import java.util.Collections; import java.util.Map; import org.apache.kylin.metadata.realization.CapabilityResult; import org.apache.kylin.metadata.realization.IRealization; import org.apache.kylin.metadata.realization.RealizationType; import org.apache.kylin.metadata.realization.SQLDigest; import com.google.common.collect.Maps; public class Candidate implements Comparable<Candidate> { static Map<RealizationType, Integer> DEFAULT_PRIORITIES = Maps.newHashMap(); static Map<RealizationType, Integer> PRIORITIES = DEFAULT_PRIORITIES; static { DEFAULT_PRIORITIES.put(RealizationType.HYBRID, 0); DEFAULT_PRIORITIES.put(RealizationType.CUBE, 1); } /** for test only */ public static void setPriorities(Map<RealizationType, Integer> priorities) { PRIORITIES = Collections.unmodifiableMap(priorities); } /** for test only */ public static void restorePriorities() { PRIORITIES = Collections.unmodifiableMap(DEFAULT_PRIORITIES); } // ============================================================================ IRealization realization; SQLDigest sqlDigest; int priority; CapabilityResult capability; public Candidate(IRealization realization, SQLDigest sqlDigest) { this.realization = realization; this.sqlDigest = sqlDigest; this.priority = PRIORITIES.get(realization.getType()); } public IRealization getRealization() { return realization; } public SQLDigest getSqlDigest() { return sqlDigest; } public int getPriority() { return priority; } public CapabilityResult getCapability() { return capability; } public void setCapability(CapabilityResult capability) { this.capability = capability; } @Override public int compareTo(Candidate o) { int comp = this.priority - o.priority; if (comp != 0) { return comp; } comp = this.capability.cost - o.capability.cost; if (comp != 0) { return comp; } return 0; } @Override public String toString() { return realization.toString(); } }
1,042
1,498
<filename>interface/khronos/ext/gl_oes_framebuffer_object.c<gh_stars>1000+ /* Copyright (c) 2012, Broadcom Europe Ltd 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 copyright holder 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. */ #define GL_GLEXT_PROTOTYPES /* we want the prototypes so the compiler will check that the signatures match */ #include "interface/khronos/common/khrn_client_mangle.h" #include "interface/khronos/common/khrn_int_common.h" #include "interface/khronos/glxx/glxx_client.h" #include "interface/khronos/common/khrn_client_rpc.h" #ifdef RPC_DIRECT #include "interface/khronos/glxx/glxx_int_impl.h" #include "interface/khronos/glxx/gl11_int_impl.h" #endif #include "interface/khronos/include/GLES/gl.h" #include "interface/khronos/include/GLES/glext.h" extern GLboolean glxx_client_IsRenderbuffer(GLuint renderbuffer); extern void glxx_client_BindRenderbuffer(GLenum target, GLuint renderbuffer); extern void glxx_client_DeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers); extern void glxx_client_GenRenderbuffers(GLsizei n, GLuint *renderbuffers); extern void glxx_client_RenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); extern void glxx_client_GetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params); extern GLboolean glxx_client_IsFramebuffer(GLuint framebuffer); extern void glxx_client_BindFramebuffer(GLenum target, GLuint framebuffer); extern void glxx_client_DeleteFramebuffers(GLsizei n, const GLuint *framebuffers); extern void glxx_client_GenFramebuffers(GLsizei n, GLuint *framebuffers); extern GLenum glxx_client_CheckFramebufferStatus(GLenum target); extern void glxx_client_FramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); extern void glxx_client_FramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); extern void glxx_client_GetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint *params); extern void glxx_client_GenerateMipmap(GLenum target); GL_API GLboolean GL_APIENTRY glIsRenderbufferOES (GLuint renderbuffer) { return glxx_client_IsRenderbuffer(renderbuffer); } GL_API void GL_APIENTRY glBindRenderbufferOES (GLenum target, GLuint renderbuffer) { glxx_client_BindRenderbuffer(target, renderbuffer); } GL_API void GL_APIENTRY glDeleteRenderbuffersOES (GLsizei n, const GLuint* renderbuffers) { glxx_client_DeleteRenderbuffers(n, renderbuffers); } GL_API void GL_APIENTRY glGenRenderbuffersOES (GLsizei n, GLuint* renderbuffers) { glxx_client_GenRenderbuffers(n, renderbuffers); } GL_API void GL_APIENTRY glRenderbufferStorageOES (GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { glxx_client_RenderbufferStorage(target, internalformat, width, height); } GL_API void GL_APIENTRY glGetRenderbufferParameterivOES (GLenum target, GLenum pname, GLint* params) { glxx_client_GetRenderbufferParameteriv(target, pname, params); } GL_API GLboolean GL_APIENTRY glIsFramebufferOES (GLuint framebuffer) { return glxx_client_IsFramebuffer(framebuffer); } GL_API void GL_APIENTRY glBindFramebufferOES (GLenum target, GLuint framebuffer) { glxx_client_BindFramebuffer(target, framebuffer); } GL_API void GL_APIENTRY glDeleteFramebuffersOES (GLsizei n, const GLuint* framebuffers) { glxx_client_DeleteFramebuffers(n, framebuffers); } GL_API void GL_APIENTRY glGenFramebuffersOES (GLsizei n, GLuint* framebuffers) { glxx_client_GenFramebuffers(n, framebuffers); } GL_API GLenum GL_APIENTRY glCheckFramebufferStatusOES (GLenum target) { return glxx_client_CheckFramebufferStatus(target); } GL_API void GL_APIENTRY glFramebufferRenderbufferOES (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) { glxx_client_FramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); } GL_API void GL_APIENTRY glFramebufferTexture2DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) { glxx_client_FramebufferTexture2D(target, attachment, textarget, texture, level); } GL_API void GL_APIENTRY glGetFramebufferAttachmentParameterivOES (GLenum target, GLenum attachment, GLenum pname, GLint* params) { glxx_client_GetFramebufferAttachmentParameteriv(target, attachment, pname, params); } GL_API void GL_APIENTRY glGenerateMipmapOES (GLenum target) { glxx_client_GenerateMipmap(target); }
1,888
399
<reponame>KirmesBude/REGoth-bs #pragma once #include "RTTIUtil.hpp" #include <scripting/ScriptObjectStorage.hpp> namespace REGoth { namespace Scripting { class RTTI_ScriptObjectStorage : public bs::RTTIType<ScriptObjectStorage, bs::IReflectable, RTTI_ScriptObjectStorage> { using UINT32 = bs::UINT32; BS_BEGIN_RTTI_MEMBERS // BS_RTTI_MEMBER_PLAIN(mObjects, 0) // Commented out: Added manually, see constructor // BS_RTTI_MEMBER_PLAIN(mObjectHandles, 1) // Commented out: Added manually, see constructor BS_RTTI_MEMBER_PLAIN(mNextHandle, 2) BS_END_RTTI_MEMBERS ScriptObject& getObject(OwnerType* obj, UINT32 idx) { return mObjects[idx]; } void setObject(OwnerType* obj, UINT32 idx, ScriptObject& val) { mObjects[idx] = val; } UINT32 getSizeObjects(OwnerType* obj) { return (UINT32)mObjects.size(); } void setSizeObjects(OwnerType* obj, UINT32 val) { mObjects.resize(val); } ScriptObjectHandle& getObjectHandle(OwnerType* obj, UINT32 idx) { return mObjectHandles[idx]; } void setObjectHandle(OwnerType* obj, UINT32 idx, ScriptObjectHandle& val) { mObjectHandles[idx] = val; } UINT32 getSizeObjectHandles(OwnerType* obj) { return (UINT32)mObjectHandles.size(); } void setSizeObjectHandles(OwnerType* obj, UINT32 val) { mObjectHandles.resize(val); } public: RTTI_ScriptObjectStorage() { addReflectableArrayField("objects", 0, // &RTTI_ScriptObjectStorage::getObject, // &RTTI_ScriptObjectStorage::getSizeObjects, // &RTTI_ScriptObjectStorage::setObject, // &RTTI_ScriptObjectStorage::setSizeObjects); // addPlainArrayField("objectHandles", 1, // &RTTI_ScriptObjectStorage::getObjectHandle, // &RTTI_ScriptObjectStorage::getSizeObjectHandles, // &RTTI_ScriptObjectStorage::setObjectHandle, // &RTTI_ScriptObjectStorage::setSizeObjectHandles); // } void onSerializationStarted(bs::IReflectable* _obj, bs::SerializationContext* context) override { auto obj = static_cast<ScriptObjectStorage*>(_obj); for (const auto& v : obj->mObjects) { mObjectHandles.push_back(v.first); mObjects.push_back(v.second); } } void onDeserializationEnded(bs::IReflectable* _obj, bs::SerializationContext* context) override { auto obj = static_cast<ScriptObjectStorage*>(_obj); for (bs::UINT32 i = 0; i < (bs::UINT32)mObjectHandles.size(); i++) { obj->mObjects[mObjectHandles[i]] = mObjects[i]; } } REGOTH_IMPLEMENT_RTTI_CLASS_FOR_REFLECTABLE(ScriptObjectStorage) bs::Vector<ScriptObject> mObjects; bs::Vector<ScriptObjectHandle> mObjectHandles; }; } // namespace Scripting } // namespace REGoth
1,620
1,141
<reponame>smaeda-ks/twurl { "name": "twurl dev container", "dockerFile": "Dockerfile", "context": "..", "workspaceFolder": "/usr/src/app", "settings": { "terminal.integrated.shell.linux": "/bin/bash" }, "shutdownAction": "none", "extensions": [ "rebornix.Ruby" ] }
141
2,151
/* * * Copyright 2018 gRPC 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. * */ #ifndef GRPC_INTERNAL_CPP_EXT_FILTERS_CENSUS_GRPC_PLUGIN_H #define GRPC_INTERNAL_CPP_EXT_FILTERS_CENSUS_GRPC_PLUGIN_H #include <grpc/support/port_platform.h> #include "absl/strings/string_view.h" #include "include/grpcpp/opencensus.h" #include "opencensus/stats/stats.h" namespace grpc { class ServerContext; // The tag keys set when recording RPC stats. ::opencensus::stats::TagKey ClientMethodTagKey(); ::opencensus::stats::TagKey ClientStatusTagKey(); ::opencensus::stats::TagKey ServerMethodTagKey(); ::opencensus::stats::TagKey ServerStatusTagKey(); // Names of measures used by the plugin--users can create views on these // measures but should not record data for them. extern const absl::string_view kRpcClientSentMessagesPerRpcMeasureName; extern const absl::string_view kRpcClientSentBytesPerRpcMeasureName; extern const absl::string_view kRpcClientReceivedMessagesPerRpcMeasureName; extern const absl::string_view kRpcClientReceivedBytesPerRpcMeasureName; extern const absl::string_view kRpcClientRoundtripLatencyMeasureName; extern const absl::string_view kRpcClientServerLatencyMeasureName; extern const absl::string_view kRpcServerSentMessagesPerRpcMeasureName; extern const absl::string_view kRpcServerSentBytesPerRpcMeasureName; extern const absl::string_view kRpcServerReceivedMessagesPerRpcMeasureName; extern const absl::string_view kRpcServerReceivedBytesPerRpcMeasureName; extern const absl::string_view kRpcServerServerLatencyMeasureName; // Canonical gRPC view definitions. const ::opencensus::stats::ViewDescriptor& ClientSentMessagesPerRpcCumulative(); const ::opencensus::stats::ViewDescriptor& ClientSentBytesPerRpcCumulative(); const ::opencensus::stats::ViewDescriptor& ClientReceivedMessagesPerRpcCumulative(); const ::opencensus::stats::ViewDescriptor& ClientReceivedBytesPerRpcCumulative(); const ::opencensus::stats::ViewDescriptor& ClientRoundtripLatencyCumulative(); const ::opencensus::stats::ViewDescriptor& ClientServerLatencyCumulative(); const ::opencensus::stats::ViewDescriptor& ClientCompletedRpcsCumulative(); const ::opencensus::stats::ViewDescriptor& ServerSentBytesPerRpcCumulative(); const ::opencensus::stats::ViewDescriptor& ServerReceivedBytesPerRpcCumulative(); const ::opencensus::stats::ViewDescriptor& ServerServerLatencyCumulative(); const ::opencensus::stats::ViewDescriptor& ServerStartedCountCumulative(); const ::opencensus::stats::ViewDescriptor& ServerCompletedRpcsCumulative(); const ::opencensus::stats::ViewDescriptor& ServerSentMessagesPerRpcCumulative(); const ::opencensus::stats::ViewDescriptor& ServerReceivedMessagesPerRpcCumulative(); const ::opencensus::stats::ViewDescriptor& ClientSentMessagesPerRpcMinute(); const ::opencensus::stats::ViewDescriptor& ClientSentBytesPerRpcMinute(); const ::opencensus::stats::ViewDescriptor& ClientReceivedMessagesPerRpcMinute(); const ::opencensus::stats::ViewDescriptor& ClientReceivedBytesPerRpcMinute(); const ::opencensus::stats::ViewDescriptor& ClientRoundtripLatencyMinute(); const ::opencensus::stats::ViewDescriptor& ClientServerLatencyMinute(); const ::opencensus::stats::ViewDescriptor& ClientCompletedRpcsMinute(); const ::opencensus::stats::ViewDescriptor& ServerSentMessagesPerRpcMinute(); const ::opencensus::stats::ViewDescriptor& ServerSentBytesPerRpcMinute(); const ::opencensus::stats::ViewDescriptor& ServerReceivedMessagesPerRpcMinute(); const ::opencensus::stats::ViewDescriptor& ServerReceivedBytesPerRpcMinute(); const ::opencensus::stats::ViewDescriptor& ServerServerLatencyMinute(); const ::opencensus::stats::ViewDescriptor& ServerCompletedRpcsMinute(); const ::opencensus::stats::ViewDescriptor& ClientSentMessagesPerRpcHour(); const ::opencensus::stats::ViewDescriptor& ClientSentBytesPerRpcHour(); const ::opencensus::stats::ViewDescriptor& ClientReceivedMessagesPerRpcHour(); const ::opencensus::stats::ViewDescriptor& ClientReceivedBytesPerRpcHour(); const ::opencensus::stats::ViewDescriptor& ClientRoundtripLatencyHour(); const ::opencensus::stats::ViewDescriptor& ClientServerLatencyHour(); const ::opencensus::stats::ViewDescriptor& ClientCompletedRpcsHour(); const ::opencensus::stats::ViewDescriptor& ServerSentMessagesPerRpcHour(); const ::opencensus::stats::ViewDescriptor& ServerSentBytesPerRpcHour(); const ::opencensus::stats::ViewDescriptor& ServerReceivedMessagesPerRpcHour(); const ::opencensus::stats::ViewDescriptor& ServerReceivedBytesPerRpcHour(); const ::opencensus::stats::ViewDescriptor& ServerServerLatencyHour(); const ::opencensus::stats::ViewDescriptor& ServerStartedCountHour(); const ::opencensus::stats::ViewDescriptor& ServerCompletedRpcsHour(); } // namespace grpc #endif /* GRPC_INTERNAL_CPP_EXT_FILTERS_CENSUS_GRPC_PLUGIN_H */
1,649
454
<gh_stars>100-1000 from gazette.spiders.base.fecam import FecamGazetteSpider class ScPalmeiraSpider(FecamGazetteSpider): name = "sc_palmeira" FECAM_QUERY = "cod_entidade:187" TERRITORY_ID = "4212056"
97
1,605
/* * 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.pdfbox.debugger.streampane.tooltip; import java.util.ArrayList; import java.util.List; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import javax.swing.text.Utilities; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.contentstream.operator.OperatorName; import org.apache.pdfbox.pdmodel.PDResources; interface ToolTip { String getToolTipText(); } /** * @author <NAME> * A class that provides the tooltip for an operator. */ public class ToolTipController { private static final Log LOG = LogFactory.getLog(ToolTipController.class); private final PDResources resources; private JTextComponent textComponent; /** * Constructor. * @param resources PDResources instance. */ public ToolTipController(PDResources resources) { this.resources = resources; } static List<String> getWords(String str) { List<String> words = new ArrayList<>(); for (String string : str.trim().split(" ")) { string = string.trim(); if (!string.isEmpty() && !string.equals("\n")) { words.add(string); } } return words; } /** * Returns the tooltip text for the operator. * * @param offset The position of the mouse in the text component. * @param textComponent JTextComponent instance. * @return Tooltip text or null if there isn't any tooltip. */ public String getToolTip(int offset, JTextComponent textComponent) { this.textComponent = textComponent; String word = getWord(offset); if (word == null) { return null; } String rowText = getRowText(offset); ToolTip toolTip; String colorSpaceName; switch (word) { case OperatorName.SET_FONT_AND_SIZE: toolTip = new FontToolTip(resources, rowText); return toolTip.getToolTipText(); case OperatorName.STROKING_COLOR_N: colorSpaceName = findColorSpace(offset, OperatorName.STROKING_COLORSPACE); if (colorSpaceName != null) { toolTip = new SCNToolTip(resources, colorSpaceName, rowText); return toolTip.getToolTipText(); } break; case OperatorName.NON_STROKING_COLOR_N: colorSpaceName = findColorSpace(offset, OperatorName.NON_STROKING_COLORSPACE); if (colorSpaceName != null) { toolTip = new SCNToolTip(resources, colorSpaceName, rowText); return toolTip.getToolTipText(); } break; case OperatorName.STROKING_COLOR_RGB: case OperatorName.NON_STROKING_RGB: toolTip = new RGToolTip(rowText); return toolTip.getToolTipText(); case OperatorName.STROKING_COLOR_CMYK: case OperatorName.NON_STROKING_CMYK: toolTip = new KToolTip(rowText); return toolTip.getToolTipText(); case OperatorName.STROKING_COLOR_GRAY: case OperatorName.NON_STROKING_GRAY: toolTip = new GToolTip(rowText); return toolTip.getToolTipText(); default: break; } return null; } private String findColorSpace(int offset, String colorSpaceType) { try { while (offset != -1) { offset = Utilities.getPositionAbove(textComponent, offset, 0); String previousRowText = getRowText(offset); if (previousRowText == null) { return null; } previousRowText = previousRowText.trim(); if (isColorSpace(colorSpaceType, previousRowText)) { return previousRowText.split(" ")[0]; } } } catch (BadLocationException e) { LOG.error(e, e); } return null; } private boolean isColorSpace(String colorSpaceType, String rowText) { List<String> words = getWords(rowText); return words.size() == 2 && words.get(1).equals(colorSpaceType); } private String getWord(int offset) { try { int start = Utilities.getWordStart(textComponent, offset); int end = Utilities.getWordEnd(textComponent, offset); return textComponent.getDocument().getText(start, end - start + 1).trim(); } catch (BadLocationException e) { LOG.error(e, e); } return null; } private String getRowText(int offset) { try { int rowStart = Utilities.getRowStart(textComponent, offset); int rowEnd = Utilities.getRowEnd(textComponent, offset); return textComponent.getDocument().getText(rowStart, rowEnd - rowStart + 1); } catch (BadLocationException e) { LOG.error(e, e); } return null; } }
2,708
5,169
<filename>Specs/KRSVM/1.0.0/KRSVM.podspec.json { "name": "KRSVM", "version": "1.0.0", "summary": "KRSVM is implemented SVM of machine learning.", "description": "KRSVM is implemented Support Vector Machine (SVM) of machine learning, it current achieved SMO and RBF, Tangent, Linear these 3 kernel functions to do predication.", "homepage": "https://github.com/Kalvar/ios-KRSVM", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "https://twitter.com/ilovekalvar", "source": { "git": "https://github.com/Kalvar/ios-KRSVM.git", "tag": "1.0.0" }, "platforms": { "ios": "7.0" }, "requires_arc": true, "public_header_files": "SVM/**/*.h", "source_files": "SVM/**/*.{h,m}", "frameworks": "Foundation" }
333
305
<reponame>AgesX/llvm // REQUIRES: aarch64-registered-target // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -o - %s >/dev/null 2>%t // RUN: FileCheck --check-prefix=ASM --allow-empty %s <%t // If this check fails please read test/CodeGen/aarch64-sve-intrinsics/README for instructions on how to resolve it. // ASM-NOT: warning #include <arm_sve.h> #ifdef SVE_OVERLOADED_FORMS // A simple used,unused... macro, long enough to represent any SVE builtin. #define SVE_ACLE_FUNC(A1,A2_UNUSED,A3,A4_UNUSED) A1##A3 #else #define SVE_ACLE_FUNC(A1,A2,A3,A4) A1##A2##A3##A4 #endif svbool_t test_svcmple_s8(svbool_t pg, svint8_t op1, svint8_t op2) { // CHECK-LABEL: test_svcmple_s8 // CHECK: %[[INTRINSIC:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.cmpge.nxv16i8(<vscale x 16 x i1> %pg, <vscale x 16 x i8> %op2, <vscale x 16 x i8> %op1) // CHECK: ret <vscale x 16 x i1> %[[INTRINSIC]] return SVE_ACLE_FUNC(svcmple,_s8,,)(pg, op1, op2); } svbool_t test_svcmple_s16(svbool_t pg, svint16_t op1, svint16_t op2) { // CHECK-LABEL: test_svcmple_s16 // CHECK: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.cmpge.nxv8i16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x i16> %op2, <vscale x 8 x i16> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_s16,,)(pg, op1, op2); } svbool_t test_svcmple_s32(svbool_t pg, svint32_t op1, svint32_t op2) { // CHECK-LABEL: test_svcmple_s32 // CHECK: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.cmpge.nxv4i32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x i32> %op2, <vscale x 4 x i32> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_s32,,)(pg, op1, op2); } svbool_t test_svcmple_s64(svbool_t pg, svint64_t op1, svint64_t op2) { // CHECK-LABEL: test_svcmple_s64 // CHECK: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.cmpge.nxv2i64(<vscale x 2 x i1> %[[PG]], <vscale x 2 x i64> %op2, <vscale x 2 x i64> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv2i1(<vscale x 2 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_s64,,)(pg, op1, op2); } svbool_t test_svcmple_u8(svbool_t pg, svuint8_t op1, svuint8_t op2) { // CHECK-LABEL: test_svcmple_u8 // CHECK: %[[INTRINSIC:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.cmphs.nxv16i8(<vscale x 16 x i1> %pg, <vscale x 16 x i8> %op2, <vscale x 16 x i8> %op1) // CHECK: ret <vscale x 16 x i1> %[[INTRINSIC]] return SVE_ACLE_FUNC(svcmple,_u8,,)(pg, op1, op2); } svbool_t test_svcmple_u16(svbool_t pg, svuint16_t op1, svuint16_t op2) { // CHECK-LABEL: test_svcmple_u16 // CHECK: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.cmphs.nxv8i16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x i16> %op2, <vscale x 8 x i16> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_u16,,)(pg, op1, op2); } svbool_t test_svcmple_u32(svbool_t pg, svuint32_t op1, svuint32_t op2) { // CHECK-LABEL: test_svcmple_u32 // CHECK: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.cmphs.nxv4i32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x i32> %op2, <vscale x 4 x i32> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_u32,,)(pg, op1, op2); } svbool_t test_svcmple_u64(svbool_t pg, svuint64_t op1, svuint64_t op2) { // CHECK-LABEL: test_svcmple_u64 // CHECK: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.cmphs.nxv2i64(<vscale x 2 x i1> %[[PG]], <vscale x 2 x i64> %op2, <vscale x 2 x i64> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv2i1(<vscale x 2 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_u64,,)(pg, op1, op2); } svbool_t test_svcmple_n_s64(svbool_t pg, svint64_t op1, int64_t op2) { // CHECK-LABEL: test_svcmple_n_s64 // CHECK-DAG: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.dup.x.nxv2i64(i64 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.cmpge.nxv2i64(<vscale x 2 x i1> %[[PG]], <vscale x 2 x i64> %[[DUP]], <vscale x 2 x i64> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv2i1(<vscale x 2 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_s64,,)(pg, op1, op2); } svbool_t test_svcmple_n_u64(svbool_t pg, svuint64_t op1, uint64_t op2) { // CHECK-LABEL: test_svcmple_n_u64 // CHECK-DAG: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.dup.x.nxv2i64(i64 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.cmphs.nxv2i64(<vscale x 2 x i1> %[[PG]], <vscale x 2 x i64> %[[DUP]], <vscale x 2 x i64> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv2i1(<vscale x 2 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_u64,,)(pg, op1, op2); } svbool_t test_svcmple_wide_s8(svbool_t pg, svint8_t op1, svint64_t op2) { // CHECK-LABEL: test_svcmple_wide_s8 // CHECK: %[[INTRINSIC:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.cmple.wide.nxv16i8(<vscale x 16 x i1> %pg, <vscale x 16 x i8> %op1, <vscale x 2 x i64> %op2) // CHECK: ret <vscale x 16 x i1> %[[INTRINSIC]] return SVE_ACLE_FUNC(svcmple_wide,_s8,,)(pg, op1, op2); } svbool_t test_svcmple_wide_s16(svbool_t pg, svint16_t op1, svint64_t op2) { // CHECK-LABEL: test_svcmple_wide_s16 // CHECK: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.cmple.wide.nxv8i16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x i16> %op1, <vscale x 2 x i64> %op2) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple_wide,_s16,,)(pg, op1, op2); } svbool_t test_svcmple_wide_s32(svbool_t pg, svint32_t op1, svint64_t op2) { // CHECK-LABEL: test_svcmple_wide_s32 // CHECK: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.cmple.wide.nxv4i32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x i32> %op1, <vscale x 2 x i64> %op2) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple_wide,_s32,,)(pg, op1, op2); } svbool_t test_svcmple_wide_u8(svbool_t pg, svuint8_t op1, svuint64_t op2) { // CHECK-LABEL: test_svcmple_wide_u8 // CHECK: %[[INTRINSIC:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.cmpls.wide.nxv16i8(<vscale x 16 x i1> %pg, <vscale x 16 x i8> %op1, <vscale x 2 x i64> %op2) // CHECK: ret <vscale x 16 x i1> %[[INTRINSIC]] return SVE_ACLE_FUNC(svcmple_wide,_u8,,)(pg, op1, op2); } svbool_t test_svcmple_wide_u16(svbool_t pg, svuint16_t op1, svuint64_t op2) { // CHECK-LABEL: test_svcmple_wide_u16 // CHECK: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.cmpls.wide.nxv8i16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x i16> %op1, <vscale x 2 x i64> %op2) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple_wide,_u16,,)(pg, op1, op2); } svbool_t test_svcmple_wide_u32(svbool_t pg, svuint32_t op1, svuint64_t op2) { // CHECK-LABEL: test_svcmple_wide_u32 // CHECK: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.cmpls.wide.nxv4i32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x i32> %op1, <vscale x 2 x i64> %op2) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple_wide,_u32,,)(pg, op1, op2); } svbool_t test_svcmple_n_s8(svbool_t pg, svint8_t op1, int8_t op2) { // CHECK-LABEL: test_svcmple_n_s8 // CHECK: %[[DUP:.*]] = call <vscale x 16 x i8> @llvm.aarch64.sve.dup.x.nxv16i8(i8 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.cmpge.nxv16i8(<vscale x 16 x i1> %pg, <vscale x 16 x i8> %[[DUP]], <vscale x 16 x i8> %op1) // CHECK: ret <vscale x 16 x i1> %[[INTRINSIC]] return SVE_ACLE_FUNC(svcmple,_n_s8,,)(pg, op1, op2); } svbool_t test_svcmple_n_s16(svbool_t pg, svint16_t op1, int16_t op2) { // CHECK-LABEL: test_svcmple_n_s16 // CHECK-DAG: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 8 x i16> @llvm.aarch64.sve.dup.x.nxv8i16(i16 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.cmpge.nxv8i16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x i16> %[[DUP]], <vscale x 8 x i16> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_s16,,)(pg, op1, op2); } svbool_t test_svcmple_n_s32(svbool_t pg, svint32_t op1, int32_t op2) { // CHECK-LABEL: test_svcmple_n_s32 // CHECK-DAG: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 4 x i32> @llvm.aarch64.sve.dup.x.nxv4i32(i32 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.cmpge.nxv4i32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x i32> %[[DUP]], <vscale x 4 x i32> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_s32,,)(pg, op1, op2); } svbool_t test_svcmple_n_u8(svbool_t pg, svuint8_t op1, uint8_t op2) { // CHECK-LABEL: test_svcmple_n_u8 // CHECK: %[[DUP:.*]] = call <vscale x 16 x i8> @llvm.aarch64.sve.dup.x.nxv16i8(i8 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.cmphs.nxv16i8(<vscale x 16 x i1> %pg, <vscale x 16 x i8> %[[DUP]], <vscale x 16 x i8> %op1) // CHECK: ret <vscale x 16 x i1> %[[INTRINSIC]] return SVE_ACLE_FUNC(svcmple,_n_u8,,)(pg, op1, op2); } svbool_t test_svcmple_n_u16(svbool_t pg, svuint16_t op1, uint16_t op2) { // CHECK-LABEL: test_svcmple_n_u16 // CHECK-DAG: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 8 x i16> @llvm.aarch64.sve.dup.x.nxv8i16(i16 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.cmphs.nxv8i16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x i16> %[[DUP]], <vscale x 8 x i16> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_u16,,)(pg, op1, op2); } svbool_t test_svcmple_n_u32(svbool_t pg, svuint32_t op1, uint32_t op2) { // CHECK-LABEL: test_svcmple_n_u32 // CHECK-DAG: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 4 x i32> @llvm.aarch64.sve.dup.x.nxv4i32(i32 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.cmphs.nxv4i32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x i32> %[[DUP]], <vscale x 4 x i32> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_u32,,)(pg, op1, op2); } svbool_t test_svcmple_f16(svbool_t pg, svfloat16_t op1, svfloat16_t op2) { // CHECK-LABEL: test_svcmple_f16 // CHECK: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.fcmpge.nxv8f16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x half> %op2, <vscale x 8 x half> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_f16,,)(pg, op1, op2); } svbool_t test_svcmple_f32(svbool_t pg, svfloat32_t op1, svfloat32_t op2) { // CHECK-LABEL: test_svcmple_f32 // CHECK: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.fcmpge.nxv4f32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x float> %op2, <vscale x 4 x float> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_f32,,)(pg, op1, op2); } svbool_t test_svcmple_f64(svbool_t pg, svfloat64_t op1, svfloat64_t op2) { // CHECK-LABEL: test_svcmple_f64 // CHECK: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.fcmpge.nxv2f64(<vscale x 2 x i1> %[[PG]], <vscale x 2 x double> %op2, <vscale x 2 x double> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv2i1(<vscale x 2 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_f64,,)(pg, op1, op2); } svbool_t test_svcmple_n_f16(svbool_t pg, svfloat16_t op1, float16_t op2) { // CHECK-LABEL: test_svcmple_n_f16 // CHECK-DAG: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 8 x half> @llvm.aarch64.sve.dup.x.nxv8f16(half %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.fcmpge.nxv8f16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x half> %[[DUP]], <vscale x 8 x half> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_f16,,)(pg, op1, op2); } svbool_t test_svcmple_n_f32(svbool_t pg, svfloat32_t op1, float32_t op2) { // CHECK-LABEL: test_svcmple_n_f32 // CHECK-DAG: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 4 x float> @llvm.aarch64.sve.dup.x.nxv4f32(float %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.fcmpge.nxv4f32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x float> %[[DUP]], <vscale x 4 x float> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_f32,,)(pg, op1, op2); } svbool_t test_svcmple_n_f64(svbool_t pg, svfloat64_t op1, float64_t op2) { // CHECK-LABEL: test_svcmple_n_f64 // CHECK-DAG: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 2 x double> @llvm.aarch64.sve.dup.x.nxv2f64(double %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.fcmpge.nxv2f64(<vscale x 2 x i1> %[[PG]], <vscale x 2 x double> %[[DUP]], <vscale x 2 x double> %op1) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv2i1(<vscale x 2 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple,_n_f64,,)(pg, op1, op2); } svbool_t test_svcmple_wide_n_s8(svbool_t pg, svint8_t op1, int64_t op2) { // CHECK-LABEL: test_svcmple_wide_n_s8 // CHECK: %[[DUP:.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.dup.x.nxv2i64(i64 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.cmple.wide.nxv16i8(<vscale x 16 x i1> %pg, <vscale x 16 x i8> %op1, <vscale x 2 x i64> %[[DUP]]) // CHECK: ret <vscale x 16 x i1> %[[INTRINSIC]] return SVE_ACLE_FUNC(svcmple_wide,_n_s8,,)(pg, op1, op2); } svbool_t test_svcmple_wide_n_s16(svbool_t pg, svint16_t op1, int64_t op2) { // CHECK-LABEL: test_svcmple_wide_n_s16 // CHECK-DAG: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.dup.x.nxv2i64(i64 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.cmple.wide.nxv8i16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x i16> %op1, <vscale x 2 x i64> %[[DUP]]) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple_wide,_n_s16,,)(pg, op1, op2); } svbool_t test_svcmple_wide_n_s32(svbool_t pg, svint32_t op1, int64_t op2) { // CHECK-LABEL: test_svcmple_wide_n_s32 // CHECK-DAG: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.dup.x.nxv2i64(i64 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.cmple.wide.nxv4i32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x i32> %op1, <vscale x 2 x i64> %[[DUP]]) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple_wide,_n_s32,,)(pg, op1, op2); } svbool_t test_svcmple_wide_n_u8(svbool_t pg, svuint8_t op1, uint64_t op2) { // CHECK-LABEL: test_svcmple_wide_n_u8 // CHECK: %[[DUP:.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.dup.x.nxv2i64(i64 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.cmpls.wide.nxv16i8(<vscale x 16 x i1> %pg, <vscale x 16 x i8> %op1, <vscale x 2 x i64> %[[DUP]]) // CHECK: ret <vscale x 16 x i1> %[[INTRINSIC]] return SVE_ACLE_FUNC(svcmple_wide,_n_u8,,)(pg, op1, op2); } svbool_t test_svcmple_wide_n_u16(svbool_t pg, svuint16_t op1, uint64_t op2) { // CHECK-LABEL: test_svcmple_wide_n_u16 // CHECK-DAG: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.dup.x.nxv2i64(i64 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.cmpls.wide.nxv8i16(<vscale x 8 x i1> %[[PG]], <vscale x 8 x i16> %op1, <vscale x 2 x i64> %[[DUP]]) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple_wide,_n_u16,,)(pg, op1, op2); } svbool_t test_svcmple_wide_n_u32(svbool_t pg, svuint32_t op1, uint64_t op2) { // CHECK-LABEL: test_svcmple_wide_n_u32 // CHECK-DAG: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[DUP:.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.dup.x.nxv2i64(i64 %op2) // CHECK: %[[INTRINSIC:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.cmpls.wide.nxv4i32(<vscale x 4 x i1> %[[PG]], <vscale x 4 x i32> %op1, <vscale x 2 x i64> %[[DUP]]) // CHECK: %[[CAST:.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> %[[INTRINSIC]]) // CHECK: ret <vscale x 16 x i1> %[[CAST]] return SVE_ACLE_FUNC(svcmple_wide,_n_u32,,)(pg, op1, op2); }
11,528
1,255
/* Copyright (c) 2009-2010 <NAME>. 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 LibCat 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 <cat/threads/WaitableFlag.hpp> #include <cat/time/Clock.hpp> using namespace cat; #if !defined(CAT_OS_WINDOWS) #include <sys/time.h> // gettimeofday #include <errno.h> // ETIMEDOUT #endif WaitableFlag::WaitableFlag() { #if defined(CAT_OS_WINDOWS) _event = CreateEvent(0, FALSE, FALSE, 0); #else _flag = 0; _valid = false; _valid_cond = false; _valid_mutex = false; _valid_cond = pthread_cond_init(&_cond, 0) == 0; if (!_valid_cond) return; _valid_mutex = pthread_mutex_init(&_mutex, 0) == 0; if (!_valid_mutex) return; _valid = true; #endif } void WaitableFlag::Cleanup() { #if defined(CAT_OS_WINDOWS) if (_event) { CloseHandle(_event); _event = 0; } #else if (_valid_cond) { pthread_cond_destroy(&_cond); _valid_cond = false; } if (_valid_mutex) { pthread_mutex_destroy(&_mutex); _valid_mutex = false; } #endif } bool WaitableFlag::Set() { #if defined(CAT_OS_WINDOWS) if (_event) { return SetEvent(_event) == TRUE; } #else if (_valid) { pthread_mutex_lock(&_mutex); _flag = 1; pthread_mutex_unlock(&_mutex); return pthread_cond_signal(&_cond) == 0; } #endif return false; } bool WaitableFlag::Wait(int milliseconds) { #if defined(CAT_OS_WINDOWS) if (_event == 0) return false; return WaitForSingleObject(_event, (milliseconds >= 0) ? milliseconds : INFINITE) != WAIT_TIMEOUT; #else if (!_valid) return false; bool triggered = false; pthread_mutex_lock(&_mutex); if (_flag == 1) { triggered = true; } else if (milliseconds < 0) { triggered = pthread_cond_wait(&_cond, &_mutex) == 0; } else if (milliseconds > 0) { int interval_seconds = milliseconds / 1000; long interval_nanoseconds = (milliseconds % 1000) * 1000000; struct timeval tv; if (gettimeofday(&tv, 0) == 0) { long nsec = tv.tv_usec; if (nsec >= 0) { long nsec_trigger = nsec + interval_nanoseconds; static const long ONE_SECOND_IN_NANOSECONDS = 1000000000; if (nsec_trigger < nsec || nsec_trigger >= ONE_SECOND_IN_NANOSECONDS) { ++interval_seconds; nsec_trigger -= ONE_SECOND_IN_NANOSECONDS; } struct timespec ts; ts.tv_sec = tv.tv_sec + interval_seconds; ts.tv_nsec = nsec_trigger; triggered = pthread_cond_timedwait(&_cond, &_mutex, &ts) != ETIMEDOUT; } } } if (triggered) _flag = 0; pthread_mutex_unlock(&_mutex); return triggered; #endif }
1,684
442
<filename>hls/iperf/iperf.cpp /************************************************ Copyright (c) 2018, Systems Group, ETH Zurich. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 "iperf.hpp" void iperf( stream<ap_uint<16> >& listenPort, stream<bool>& listenPortStatus, // This is disabled for the time being, because it adds complexity/potential issues //stream<ap_uint<16> >& closePort, stream<appNotification>& notifications, stream<appReadRequest>& readRequest, stream<ap_uint<16> >& rxMetaData, stream<axiWord>& rxData, stream<ipTuple>& openConnection, stream<openStatus>& openConStatus, stream<ap_uint<16> >& closeConnection, stream<ap_uint<16> >& txMetaData, stream<axiWord>& txData, stream<ap_int<17> >& txStatus) { #pragma HLS PIPELINE II=1 #pragma HLS resource core=AXI4Stream variable=listenPort metadata="-bus_bundle m_axis_listen_port" #pragma HLS resource core=AXI4Stream variable=listenPortStatus metadata="-bus_bundle s_axis_listen_port_status" //#pragma HLS resource core=AXI4Stream variable=closePort metadata="-bus_bundle m_axis_close_port" #pragma HLS resource core=AXI4Stream variable=notifications metadata="-bus_bundle s_axis_notifications" #pragma HLS resource core=AXI4Stream variable=readRequest metadata="-bus_bundle m_axis_read_package" #pragma HLS DATA_PACK variable=notifications #pragma HLS DATA_PACK variable=readRequest #pragma HLS resource core=AXI4Stream variable=rxMetaData metadata="-bus_bundle s_axis_rx_metadata" #pragma HLS resource core=AXI4Stream variable=rxData metadata="-bus_bundle s_axis_rx_data" #pragma HLS DATA_PACK variable=rxData #pragma HLS resource core=AXI4Stream variable=openConnection metadata="-bus_bundle m_axis_open_connection" #pragma HLS resource core=AXI4Stream variable=openConStatus metadata="-bus_bundle s_axis_open_status" #pragma HLS DATA_PACK variable=openConnection #pragma HLS DATA_PACK variable=openConStatus #pragma HLS resource core=AXI4Stream variable=closeConnection metadata="-bus_bundle m_axis_close_connection" #pragma HLS resource core=AXI4Stream variable=txMetaData metadata="-bus_bundle m_axis_tx_metadata" #pragma HLS resource core=AXI4Stream variable=txData metadata="-bus_bundle m_axis_tx_data" #pragma HLS resource core=AXI4Stream variable=txStatus metadata="-bus_bundle s_axis_tx_status" #pragma HLS DATA_PACK variable=txMetaData #pragma HLS DATA_PACK variable=txData static bool listenDone = false; static bool runningExperiment = false; static ap_uint<1> listenFsm = 0; openStatus newConStatus; appNotification notification; ipTuple tuple; // Open Port 5001 if (!listenDone) { switch (listenFsm) { case 0: listenPort.write(5001); listenFsm++; break; case 1: if (!listenPortStatus.empty()) { listenPortStatus.read(listenDone); listenFsm++; } break; } } axiWord transmitWord; // In case we are connecting back if (!openConStatus.empty()) { openConStatus.read(newConStatus); txMetaData.write(0); transmitWord.data = 0x3736353433323130; transmitWord.keep = 0xff; transmitWord.last = 1; txData.write(transmitWord); if (newConStatus.success) { closeConnection.write(newConStatus.sessionID); } } if (!notifications.empty()) { notifications.read(notification); if (notification.length != 0) { readRequest.write(appReadRequest(notification.sessionID, notification.length)); } else // closed { runningExperiment = false; } } enum consumeFsmStateType {WAIT_PKG, CONSUME, HEADER_2, HEADER_3}; static consumeFsmStateType serverFsmState = WAIT_PKG; ap_uint<16> sessionID; axiWord currWord; currWord.last = 0; static bool dualTest = false; static ap_uint<32> mAmount = 0; switch (serverFsmState) { case WAIT_PKG: if (!rxMetaData.empty() && !rxData.empty()) { rxMetaData.read(sessionID); rxData.read(currWord); if (!runningExperiment) { if (currWord.data(31, 0) == 0x00000080) // Dual test { dualTest = true; } else { dualTest = false; } runningExperiment = true; serverFsmState = HEADER_2; } else { serverFsmState = CONSUME; } } break; case HEADER_2: if (!rxData.empty()) { rxData.read(currWord); if (dualTest) { tuple.ip_address = 0x0a010101; tuple.ip_port = currWord.data(31, 16); openConnection.write(tuple); } serverFsmState = HEADER_3; } break; case HEADER_3: if (!rxData.empty()) { rxData.read(currWord); mAmount = currWord.data(63, 32); serverFsmState = CONSUME; } break; case CONSUME: if (!rxData.empty()) { rxData.read(currWord); } break; } if (currWord.last == 1) { serverFsmState = WAIT_PKG; } if (!txStatus.empty()) { txStatus.read(); } }
2,288
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.desktopvirtualization.models; import com.azure.resourcemanager.desktopvirtualization.fluent.models.RegistrationInfoInner; import java.time.OffsetDateTime; /** An immutable client-side representation of RegistrationInfo. */ public interface RegistrationInfo { /** * Gets the expirationTime property: Expiration time of registration token. * * @return the expirationTime value. */ OffsetDateTime expirationTime(); /** * Gets the token property: The registration token base64 encoded string. * * @return the token value. */ String token(); /** * Gets the registrationTokenOperation property: The type of resetting the token. * * @return the registrationTokenOperation value. */ RegistrationTokenOperation registrationTokenOperation(); /** * Gets the inner com.azure.resourcemanager.desktopvirtualization.fluent.models.RegistrationInfoInner object. * * @return the inner object. */ RegistrationInfoInner innerModel(); }
359
558
package com.endava.cats.util; import io.quarkus.test.junit.QuarkusTest; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Set; @QuarkusTest class WordUtilsTest { @Test void shouldReturnAllCombinations() { String[] words = new String[]{"pet", "name", "id"}; Set<String> result = WordUtils.createWordCombinations(words); Assertions.assertThat(result).containsOnly("ID", "Id", "NAME-ID", "NAMEID", "NAME_ID", "Name-Id", "NameId", "Name_Id", "PET-NAME-ID", "PETNAMEID", "PET_NAME_ID", "Pet-Name-Id", "PetNameId", "Pet_Name_Id", "id", "name-Id", "name-id", "nameId", "name_Id", "name_id", "nameid", "pet-Name-Id", "pet-name-id", "petNameId", "pet_Name_Id", "pet_name_id", "petnameid"); } }
350
575
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_DNS_DNS_RESPONSE_RESULT_EXTRACTOR_H_ #define NET_DNS_DNS_RESPONSE_RESULT_EXTRACTOR_H_ #include <stdint.h> #include "net/base/net_export.h" #include "net/dns/host_cache.h" #include "net/dns/public/dns_query_type.h" namespace net { class DnsResponse; // Higher-level parser to take a DnsResponse and extract results. class NET_EXPORT_PRIVATE DnsResponseResultExtractor { public: enum class ExtractionError { kOk = 0, // Record failed to parse. kMalformedRecord, // Malformed CNAME kMalformedCname, // Found CNAME or result record with an unexpected name. kNameMismatch, // Malformed result record kMalformedResult, // CNAME record after a result record kCnameAfterResult, // Multiple CNAME records for the same owner name. kMultipleCnames, // Invalid alias chain, e.g. contains loops or disjoint aliases. kBadAliasChain, // Not expected. Used for DCHECKs. kUnexpected, }; explicit DnsResponseResultExtractor(const DnsResponse* response); ~DnsResponseResultExtractor(); DnsResponseResultExtractor(const DnsResponseResultExtractor&) = delete; DnsResponseResultExtractor& operator=(const DnsResponseResultExtractor&) = delete; // Extract results from the response. `query_type` must match the qtype from // the DNS query, and it must have already been validated (expected to be done // by DnsTransaction) that the response matches the query. // // May have the side effect of recording metrics about DnsResponses as they // are parsed, so while not an absolute requirement, any given DnsResponse // should only be used and extracted from at most once. // // Note that for INTEGRITY or HTTPS, this will ignore errors and pretend it // successfully parsed a no-result response. // TODO(crbug.com/1138620): Cleanup this "helpfulness" and let // HostResolverManager handle whether or not errors should be fatal due to // experimentation. ExtractionError ExtractDnsResults(DnsQueryType query_type, HostCache::Entry* out_results) const; // Creates the results of a NODATA response (successfully parsed but without // any results) appropriate for `query_type`. static HostCache::Entry CreateEmptyResult(DnsQueryType query_type); private: const DnsResponse* const response_; }; } // namespace net #endif // NET_DNS_DNS_RESPONSE_RESULT_EXTRACTOR_H_
838
5,169
<reponame>Gantios/Specs { "name": "Reminder", "version": "1.0.0", "summary": "Reminder is a library that helps by managing the scheduled actions on your app.", "description": "Using Reminder for creating async actions, it will be much more easier. All actions will be scheduled on a queue that will be consumed ate fire time.", "homepage": "https://github.com/umobi/Reminder", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "brennobemoura": "<EMAIL>" }, "source": { "git": "https://github.com/umobi/Reminder.git", "tag": "1.0.0" }, "swift_versions": "5.1", "platforms": { "ios": "8.0" }, "source_files": "Reminder/Classes/**/*", "swift_version": "5.1" }
280
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/history/core/browser/domain_mixing_metrics.h" #include "base/check_op.h" #include "base/containers/flat_map.h" #include "base/metrics/histogram_macros.h" #include "base/notreached.h" #include "base/numerics/safe_conversions.h" namespace history { namespace { // For readability, represents days as times rounded down to a multiple in // days from begin_time. using Day = base::Time; using DomainVisits = base::flat_map<std::string, int>; using DomainVisitsPerDay = base::flat_map<Day, DomainVisits>; // The time intervals in days to compute domain mixing metrics for, sorted // in ascending order. std::vector<int> NumDaysForMetrics() { return {kOneDay, kOneWeek, kTwoWeeks, kOneMonth}; } // Maps a time to the start of a day using ref_start_of_day as the reference // time for the start of a day. Some examples: // // time = 2018-01-02 13:00:00 UTC // ref = 2018-01-04 04:00:00 UTC // result = 2018-01-02 04:00:00 UTC // // time = 2018-01-06 03:00:00 UTC // ref = 2018-01-04 04:00:00 UTC // result = 2018-01-05 04:00:00 UTC Day ToStartOfDay(base::Time time, Day ref_start_of_day) { return ref_start_of_day + base::Days((time - ref_start_of_day).InDaysFloored()); } // Counts the number of visits per day and per domain as a nested map // day -> domain -> num_visits. // start_of_day is used as the reference time for the start of a day. DomainVisitsPerDay CountDomainVisitsPerDay( base::Time start_of_day, const std::vector<DomainVisit>& domain_visits) { DomainVisitsPerDay domain_visits_per_day; for (const DomainVisit& visit : domain_visits) { const Day day = ToStartOfDay(visit.visit_time(), start_of_day); DomainVisits& domain_visits_for_day = domain_visits_per_day[day]; ++domain_visits_for_day[visit.domain()]; } return domain_visits_per_day; } // Computes the domain mixing ratio given the number of visits for each domain. double ComputeDomainMixingRatio(const DomainVisits& domain_visits) { // First, we extract the domain with the most visits. const auto top_domain = std::max_element( domain_visits.begin(), domain_visits.end(), [](const DomainVisits::value_type& a, const DomainVisits::value_type& b) { return a.second < b.second; }); // Then we compute the number of visits that are not on the top domain // (secondary domains). int other_visits = 0; for (const auto& domain_num_visits : domain_visits) { if (domain_num_visits.first != top_domain->first) other_visits += domain_num_visits.second; } // Finally, we compute the domain mixing ratio which is the ratio of the // number of visits on secondary domains to the total number of visits. // This ratio is equal to 0 if all visits are on the top domain (no domain // mixing) and is close to 1 if most visits are on secondary domains. DCHECK_GT(other_visits + top_domain->second, 0) << "Tried to compute domain mixing for a time range with no domain " "visits, this should never happen as we only compute domain mixing " "for active days."; return static_cast<double>(other_visits) / (other_visits + top_domain->second); } void EmitDomainMixingMetric(const DomainVisits& domain_visits, int num_days) { double domain_mixing_ratio = ComputeDomainMixingRatio(domain_visits); int percentage = base::ClampRound(100 * domain_mixing_ratio); switch (num_days) { case kOneDay: UMA_HISTOGRAM_PERCENTAGE("DomainMixing.OneDay", percentage); break; case kOneWeek: UMA_HISTOGRAM_PERCENTAGE("DomainMixing.OneWeek", percentage); break; case kTwoWeeks: UMA_HISTOGRAM_PERCENTAGE("DomainMixing.TwoWeeks", percentage); break; case kOneMonth: UMA_HISTOGRAM_PERCENTAGE("DomainMixing.OneMonth", percentage); break; default: // This should never happen. NOTREACHED(); } } void EmitDomainMixingMetricsForDay( const DomainVisitsPerDay::const_iterator& active_day, const DomainVisitsPerDay& domain_visits_per_day) { DomainVisits domain_visits = active_day->second; // To efficiently compute domain mixing for each of the time periods, we // aggregate domain visits preceding the active day in a single pass. // The metrics to emit are sorted by increasing time period lengths. // We take them in order, aggregate the number of activity days required // for the current one, then move on to the next one. // Reverse iterator, starting at the day before active_day. auto it = std::make_reverse_iterator(active_day); for (const int num_days : NumDaysForMetrics()) { const Day first_day = active_day->first - base::Days(num_days - 1); for (; it != domain_visits_per_day.rend() && it->first >= first_day; ++it) { for (const auto& domain_num_visits : it->second) { domain_visits[domain_num_visits.first] += domain_num_visits.second; } } // We have aggregated all the days within the time window for the current // metric. EmitDomainMixingMetric(domain_visits, num_days); } } } // namespace void EmitDomainMixingMetrics(const std::vector<DomainVisit>& domain_visits, base::Time start_of_first_day_to_emit) { // We count the visits per domain for each day of user activity. DomainVisitsPerDay domain_visits_per_day = CountDomainVisitsPerDay(start_of_first_day_to_emit, domain_visits); // We then compute domain mixing metrics for each day of activity within // [start_of_first_day_to_emit, last_day]. for (auto active_day_it = domain_visits_per_day.lower_bound(start_of_first_day_to_emit); active_day_it != domain_visits_per_day.end(); ++active_day_it) { EmitDomainMixingMetricsForDay(active_day_it, domain_visits_per_day); } } } // namespace history
2,086
14,668
<filename>src/font.h /* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Data model for a font file in sfnt format, reading and writing functions and accessors for the glyph data. */ #ifndef WOFF2_FONT_H_ #define WOFF2_FONT_H_ #include <stddef.h> #include <inttypes.h> #include <map> #include <vector> namespace woff2 { // Represents an sfnt font file. Only the table directory is parsed, for the // table data we only store a raw pointer, therefore a font object is valid only // as long the data from which it was parsed is around. struct Font { uint32_t flavor; uint16_t num_tables; struct Table { uint32_t tag; uint32_t checksum; uint32_t offset; uint32_t length; const uint8_t* data; // Buffer used to mutate the data before writing out. std::vector<uint8_t> buffer; // If we've seen this tag/offset before, pointer to the first time we saw it // If this is the first time we've seen this table, NULL // Intended use is to bypass re-processing tables Font::Table* reuse_of; uint8_t flag_byte; // Is this table reused by a TTC bool IsReused() const; }; std::map<uint32_t, Table> tables; std::vector<uint32_t> OutputOrderedTags() const; Table* FindTable(uint32_t tag); const Table* FindTable(uint32_t tag) const; }; // Accomodates both singular (OTF, TTF) and collection (TTC) fonts struct FontCollection { uint32_t flavor; uint32_t header_version; // (offset, first use of table*) pairs std::map<uint32_t, Font::Table*> tables; std::vector<Font> fonts; }; // Parses the font from the given data. Returns false on parsing failure or // buffer overflow. The font is valid only so long the input data pointer is // valid. Does NOT support collections. bool ReadFont(const uint8_t* data, size_t len, Font* font); // Parses the font from the given data. Returns false on parsing failure or // buffer overflow. The font is valid only so long the input data pointer is // valid. Supports collections. bool ReadFontCollection(const uint8_t* data, size_t len, FontCollection* fonts); // Returns the file size of the font. size_t FontFileSize(const Font& font); size_t FontCollectionFileSize(const FontCollection& font); // Writes the font into the specified dst buffer. The dst_size should be the // same as returned by FontFileSize(). Returns false upon buffer overflow (which // should not happen if dst_size was computed by FontFileSize()). bool WriteFont(const Font& font, uint8_t* dst, size_t dst_size); // Write the font at a specific offset bool WriteFont(const Font& font, size_t* offset, uint8_t* dst, size_t dst_size); bool WriteFontCollection(const FontCollection& font_collection, uint8_t* dst, size_t dst_size); // Returns the number of glyphs in the font. // NOTE: Currently this works only for TrueType-flavored fonts, will return // zero for CFF-flavored fonts. int NumGlyphs(const Font& font); // Returns the index format of the font int IndexFormat(const Font& font); // Sets *glyph_data and *glyph_size to point to the location of the glyph data // with the given index. Returns false if the glyph is not found. bool GetGlyphData(const Font& font, int glyph_index, const uint8_t** glyph_data, size_t* glyph_size); // Removes the digital signature (DSIG) table bool RemoveDigitalSignature(Font* font); } // namespace woff2 #endif // WOFF2_FONT_H_
1,133
715
<filename>Greedy Algorithms/Activity Selection/python/activity_selection.py class Activity: def __init__(self, start, finish): self.start = start self.finish = finish def __lt__(self, other): return self.finish < other.finish def __repr__(self): return "( %s, %s )" % (self.start, self.finish) def activity_selection(activity_arr): selected_activities = [] if activity_arr: activity_arr.sort() selected = activity_arr[0] selected_activities.append(selected) for activity in activity_arr: if activity.start >= selected.finish: selected = activity selected_activities.append(selected) return selected_activities activity_arr = [Activity(5,9), Activity(1, 2), Activity(3, 4), Activity(0, 6), Activity(5, 7), Activity(8, 9)] print(activity_selection(activity_arr))
365
1,144
<filename>misc/services/camel/de-metas-camel-externalsystems/de-metas-camel-shopware6/src/test/resources/de/metas/camel/externalsystems/shopware6/api/JsonOrder.json<gh_stars>1000+ { "orderNumber": "orderNumber", "currencyId": "currencyId", "billingAddressId": "billingAddressId", "orderCustomer": { "email": "<EMAIL>", "orderId": "orderId", "salutationId": "salutationId", "firstName": "firstName", "lastName": "lastName", "title": null, "company": "company", "customerNumber": "customerNumber", "customerId": "customerId", "customFields": { "metasfreshId": "customBPartnerId", "customUserId": "customSalesRepId" }, "translated": [], "id": "id", "orderVersionId": "orderVersionId" }, "stateMachineState": { "technicalName": "open" }, "createdAt": "2021-04-29T07:40:31.676+00:00", "updatedAt": "2021-04-29T07:40:31.906+00:00", "id": "id", "billingAddressVersionId": "billingAddressVersionId", "apiAlias": "order" }
424
848
#!/usr/bin/python3 # Copyright 2020 Xilinx 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 sys import os import ctypes import logging import json from ascii_table import * """ IP_LAYOUT SECTION """ class IP_CONTROL: AP_CTRL_HS = 0 AP_CTRL_CHAIN = 1 AP_CTRL_NONE = 2 AP_CTRL_ME = 3 class indices (ctypes.Structure): _fields_ = [ ("m_index", ctypes.c_uint16), ("m_pc_index", ctypes.c_uint8), ("unused", ctypes.c_uint8) ] class ip_u1 (ctypes.Union): _fields_ = [ ("m_base_address", ctypes.c_int64), ("indices", indices) ] class ip_data (ctypes.Structure): _fields_ = [ ("m_type", ctypes.c_uint32), ("properties", ctypes.c_uint32), ("ip_u1", ip_u1), ("m_name", ctypes.c_uint8 * 64) ] class ip_layout (ctypes.Structure): _fields_ = [ ("m_count", ctypes.c_int32), ("m_ip_data", ip_data*16) ] """ CONNECTIVITY SECTION """ class connection(ctypes.Structure): _fields_ = [ ("arg_index", ctypes.c_int32), ("m_ip_layout_index", ctypes.c_int32), ("mem_data_index", ctypes.c_int32) ] class connectivity(ctypes.Structure): _fields_ = [ ("m_count", ctypes.c_int32), ("m_connection", connection*64) ] cu_args_name = { 0: {"name": "dpu_doneclr", "port": "S_AXI_CONTROL"}, 1: {"name": "dpu_prof_en", "port": "S_AXI_CONTROL"}, 2: {"name": "dpu_cmd", "port": "S_AXI_CONTROL"}, 3: {"name": "dpu_instr_addr", "port": "M_AXI_GP0"}, 4: {"name": "dpu_prof_addr", "port": "M_AXI_GP0"}, 5: {"name": "dpu_base0_addr", "port": "M_AXI_HP0"}, 6: {"name": "dpu_base1_addr", "port": "M_AXI_HP0"}, 7: {"name": "dpu_base2_addr", "port": "M_AXI_HP0"}, 8: {"name": "dpu_base3_addr", "port": "M_AXI_HP0"}, 9: {"name": "dpu_base4_addr", "port": "M_AXI_HP2"}, 10: {"name": "dpu_base5_addr", "port": "M_AXI_HP2"}, 11: {"name": "dpu_base6_addr", "port": "M_AXI_HP2"}, 12: {"name": "dpu_base7_addr", "port": "M_AXI_HP2"} } def getIPsZynq(path): cus = {} ip_layout_data = open(path, 'rb').read() ips = ip_layout() ctypes.memmove(ctypes.pointer(ips), ip_layout_data, len(ip_layout_data)) for i in range(0, ips.m_count): ip = ips.m_ip_data[i] cu_name = str() for c in ip.m_name: cu_name += chr(c) cu_type, cu_name = cu_name.strip('\x00').split(':') cu_name = cu_name.replace('_xrt_top', '') cu_paddr = hex(ip.ip_u1.m_base_address) cu_idx = ip.ip_u1.indices.m_index cu_pc_idx = ip.ip_u1.indices.m_pc_index #cus[cu_name] = (cu_pc_idx,cu_paddr) #cus[cu_pc_idx] = (cu_name,cu_paddr) cus[i] = (cu_name, cu_paddr) return {'cus': cus} def getConnectivity(path): conn_data = open(path, 'rb').read() conn = connectivity() ret = {} ctypes.memmove(ctypes.pointer(conn), conn_data, len(conn_data)) for i in range(0, conn.m_count): con = conn.m_connection[i] ret.setdefault(con.m_ip_layout_index, []).append( {'arg_index': con.arg_index, 'mem_data_index': con.mem_data_index}) #print ("m_ip_layout_index %d, arg_index %d, mem_data_index %d" % (con.m_ip_layout_index, con.arg_index, con.mem_data_index)) return {'connectivity': ret} def getMemTopo(): xbutil_path_alt = ["/usr/bin/xbutil", "/opt/xilinx/xrt/bin/xbutil"] xbutil_cmd = "xbutil" for alt in xbutil_path_alt: if os.path.exists(alt): xbutil_cmd = alt d = os.popen('%s dump' % xbutil_cmd).read() if len(d) == 0: return {} ret = json.loads(d)['board']["memory"] return ret def checkPath(): alt_dirs = [ "/sys/devices/platform/amba/amba:zyxclmm_drm/", "/sys/devices/platform/axi/axi:zyxclmm_drm/", "/sys/devices/platform/amba_pl@0/amba_pl@0:zyxclmm_drm/" ] for d in alt_dirs: if os.path.isdir(d): return d logging.error("Cannot find path amba:zyxclmm_drm") exit(-1) path = checkPath() ip_connect = getConnectivity(os.path.join(path, "connectivity")) ip_layout = getIPsZynq(os.path.join(path, "ip_layout")) mem_topo = getMemTopo() # print(ip_connect) # print(ip_layout) # print(mem_topo) # DPU_TOPO = {} for dpu_idx in ip_layout['cus'].keys(): DPU_TOPO.setdefault(dpu_idx, {})['name'] = ip_layout['cus'][dpu_idx][0] DPU_TOPO.setdefault(dpu_idx, {})['address'] = ip_layout['cus'][dpu_idx][1] DPU_TOPO.setdefault(dpu_idx, {})[ 'ports'] = ip_connect['connectivity'][dpu_idx] for port in DPU_TOPO[dpu_idx]['ports']: port_idx = port['mem_data_index'] port_idx_tag = mem_topo['mem'][str(port_idx)]['tag'] arg_idx = int(port['arg_index']) arg_name = cu_args_name[arg_idx]['name'] port['tag'] = port_idx_tag port['arg_name'] = arg_name def print_dpu_info(dpu_info): title = ['CU Index', 'CU Name', 'CU Address', 'Instruct Port', 'Data Ports'] datas = [] datas.append(title) for dpu_idx in dpu_info.keys(): content = dpu_info[dpu_idx] cu_id = dpu_idx cu_name = content.get("name", "") cu_addr = content.get("address", "0x0") cu_ports = content.get("ports", []) inst_port = [p for p in cu_ports if p["arg_name"] == "dpu_instr_addr"] inst_port_tags = str(list(set([p["tag"] for p in inst_port]))).replace( "'", "").strip('[').strip(']') data_port = [ p for p in cu_ports if p["arg_name"].find("dpu_base") >= 0] data_port_tags = str(list(set([p["tag"] for p in data_port]))).replace( "'", "").strip('[').strip(']') datas.append([dpu_idx, cu_name, cu_addr, inst_port_tags, data_port_tags]) print_ascii_table(datas) print_dpu_info(DPU_TOPO) #print(json.dumps(DPU_TOPO, indent=1))
3,108
11,334
{ "contexts": { "application": { "beans": { "spring.jpa-org.springframework.boot.autoconfigure.orm.jpa.JpaProperties": { "prefix": "spring.jpa", "properties": { "error": "Cannot serialize 'spring.jpa'" } }, "endpoints-org.springframework.boot.actuate.endpoint.EndpointProperties": { "prefix": "endpoints", "properties": { "enabled": true, "sensitive": null } } } }, "parentContext": { "beans": { "spring.cloud.config-org.springframework.cloud.bootstrap.config.PropertySourceBootstrapProperties": { "prefix": "spring.cloud.config", "properties": { "overrideSystemProperties": true, "overrideNone": false, "allowOverride": true } } } } } }
451
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/web_package/signed_exchange_utils.h" #include "base/feature_list.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "content/browser/web_package/signed_exchange_devtools_proxy.h" #include "content/browser/web_package/web_package_request_handler.h" #include "content/public/common/content_features.h" #include "services/network/public/cpp/resource_response.h" #include "third_party/blink/public/common/origin_trials/trial_token_validator.h" namespace content { namespace signed_exchange_utils { void ReportErrorAndEndTraceEvent(SignedExchangeDevToolsProxy* devtools_proxy, const char* trace_event_name, const std::string& error_message) { if (devtools_proxy) devtools_proxy->ReportErrorMessage(error_message); TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("loading"), trace_event_name, "error", error_message); } bool IsSignedExchangeHandlingEnabled() { return base::FeatureList::IsEnabled(features::kSignedHTTPExchange) || base::FeatureList::IsEnabled(features::kSignedHTTPExchangeOriginTrial); } bool ShouldHandleAsSignedHTTPExchange( const GURL& request_url, const network::ResourceResponseHead& head) { // Currently we don't support the signed exchange which is returned from a // service worker. // TODO(crbug/803774): Decide whether we should support it or not. if (head.was_fetched_via_service_worker) return false; if (!WebPackageRequestHandler::IsSupportedMimeType(head.mime_type)) return false; if (base::FeatureList::IsEnabled(features::kSignedHTTPExchange)) return true; if (!base::FeatureList::IsEnabled(features::kSignedHTTPExchangeOriginTrial)) return false; std::unique_ptr<blink::TrialTokenValidator> validator = std::make_unique<blink::TrialTokenValidator>(); return validator->RequestEnablesFeature(request_url, head.headers.get(), features::kSignedHTTPExchange.name, base::Time::Now()); } } // namespace signed_exchange_utils } // namespace content
866
320
// Copyright (c) 2015, <NAME>. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "OSD.h" #include <algorithm> #include "..\3RVX.h" #include "..\DisplayManager.h" #include "..\Error.h" #include "..\HotkeyInfo.h" #include "..\Monitor.h" OSD::OSD(LPCWSTR className, HINSTANCE hInstance) : Window(className, className, hInstance), _settings(Settings::Instance()), _enabled(true) { _masterWnd = FindWindow(_3RVX::CLASS_3RVX, _3RVX::CLASS_3RVX); } bool OSD::Enabled() { return _enabled; } void OSD::Enabled(bool enabled) { _enabled = enabled; } void OSD::HideOthers(OSDType except = All) { SendMessage(_masterWnd, _3RVX::WM_3RVX_CTRL, _3RVX::MSG_HIDEOSD, except); } void OSD::InitMeterWnd(MeterWnd &mWnd) { mWnd.AlwaysOnTop(_settings->AlwaysOnTop()); mWnd.HideAnimation(_settings->HideAnim(), _settings->HideSpeed()); mWnd.VisibleDuration(_settings->HideDelay()); mWnd.NoShowFullscreen(_settings->HideFullscreen()); mWnd.NoShowD3DOccluded(_settings->HideDirectX()); mWnd.DeleteClones(); std::vector<Monitor> monitors = ActiveMonitors(); for (unsigned int i = 1; i < monitors.size(); ++i) { mWnd.Clone(); } PositionWindow(monitors[0], mWnd); std::vector<LayeredWnd *> clones = mWnd.Clones(); for (unsigned int i = 1; i < monitors.size(); ++i) { PositionWindow(monitors[i], *clones[i - 1]); } } std::vector<Monitor> OSD::ActiveMonitors() { std::vector<Monitor> monitors; std::wstring monitorStr = _settings->Monitor(); if (monitorStr == L"") { /* Primary Monitor */ monitors.push_back(DisplayManager::Primary()); CLOG(L"Monitor: (Primary)"); } else if (monitorStr == L"*") { /* All Monitors */ std::unordered_map<std::wstring, Monitor> map = DisplayManager::MonitorMap(); for (auto it = map.begin(); it != map.end(); ++it) { CLOG(L"Monitor: %s", it->first.c_str()); monitors.push_back(it->second); } } else { /* Specific Monitor */ std::unordered_map<std::wstring, Monitor> map = DisplayManager::MonitorMap(); for (auto it = map.begin(); it != map.end(); ++it) { if (monitorStr == it->first) { CLOG(L"Monitor: %s", it->first.c_str()); monitors.push_back(it->second); break; } } } return monitors; } void OSD::PositionWindow(Monitor monitor, LayeredWnd &lWnd) { Settings::OSDPos pos = _settings->OSDPosition(); if (pos == Settings::OSDPos::CustomPosition) { int customX = _settings->OSDX(); int customY = _settings->OSDY(); lWnd.X(customX); lWnd.Y(customY); return; } int offset = _settings->OSDEdgeOffset(); /* Edge cases ;-) */ switch (pos) { case Settings::TopLeft: lWnd.X(monitor.X() + offset); lWnd.Y(monitor.Y() + offset); return; case Settings::TopRight: lWnd.X(monitor.X() + monitor.Width() - lWnd.Width() - offset); lWnd.Y(monitor.Y() + offset); return; case Settings::BottomLeft: lWnd.X(monitor.X() + offset); lWnd.Y(monitor.Y() + monitor.Height() - lWnd.Height() - offset); return; case Settings::BottomRight: lWnd.X(monitor.X() + monitor.Width() - lWnd.Width() - offset); lWnd.Y(monitor.Y() + monitor.Height() - lWnd.Height() - offset); return; } /* Center */ CenterWindowX(monitor, lWnd); CenterWindowY(monitor, lWnd); if (pos == Settings::OSDPos::Center) { return; } /* We're centered. Now adjust based on top, bottom, left, or right: */ switch (pos) { case Settings::Top: lWnd.Y(monitor.Y() + offset); return; case Settings::Bottom: lWnd.Y(monitor.Y() + monitor.Height() - lWnd.Height() - offset); return; case Settings::Left: lWnd.X(monitor.X() + offset); return; case Settings::Right: lWnd.X(monitor.X() + monitor.Width() - lWnd.Width() - offset); return; } } void OSD::CenterWindowX(Monitor monitor, LayeredWnd &lWnd) { lWnd.X(monitor.X() + monitor.Width() / 2 - lWnd.Width() / 2); } void OSD::CenterWindowY(Monitor monitor, LayeredWnd &lWnd) { lWnd.Y(monitor.Y() + monitor.Height() / 2 - lWnd.Height() / 2); } void OSD::ProcessHotkeys(HotkeyInfo &hki) { } LRESULT OSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd, message, wParam, lParam); }
2,039
2,211
<reponame>gaurangkumar/crosswalk { "name": "loadAppFromManifest Test", "version": "1.0.0", "description": "Test for loadAppFromManifest", "start_url": "index.html" }
69
5,169
{ "name": "UnzipKit", "version": "1.7.2", "summary": "An Objective-C zlib wrapper for compressing and decompressing Zip files", "license": "BSD", "homepage": "https://github.com/abbeycode/UnzipKit", "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "https://twitter.com/dovfrankel", "source": { "git": "https://github.com/abbeycode/UnzipKit.git", "tag": "1.7.2" }, "platforms": { "ios": "7.0", "osx": "10.9" }, "requires_arc": "Source/**/*", "public_header_files": [ "Source/UnzipKit.h", "Source/UZKArchive.h", "Source/UZKFileInfo.h" ], "private_header_files": [ "Source/UZKFileInfo_Private.h", "Lib/**/*.h" ], "source_files": [ "Source/**/*.{m,h}", "Lib/**/*.{c,h}" ], "libraries": "z" }
360
502
<gh_stars>100-1000 # coding: utf-8 import os import time import libmc import slow_memcached_server import subprocess def memcached_server_ctl(cmd, port): ctl_path = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__) ))), 'misc', 'memcached_server' ) print(ctl_path) subprocess.check_call([ctl_path, cmd, str(port)]) def test_soft_server_error(): mc = libmc.Client(["127.0.0.1:%d" % slow_memcached_server.PORT]) mc.config(libmc._client.MC_POLL_TIMEOUT, slow_memcached_server.BLOCKING_SECONDS * 1000 * 2) # ms RETRY_TIMEOUT = 2 mc.config(libmc.MC_RETRY_TIMEOUT, RETRY_TIMEOUT) assert mc.set('foo', 1) assert not mc.set(slow_memcached_server.KEY_SET_SERVER_ERROR.decode('utf8'), 1) assert mc.set('foo', 1) # back to live time.sleep(RETRY_TIMEOUT / 2) assert mc.set('foo', 1) # alive time.sleep(RETRY_TIMEOUT + 1) assert mc.set('foo', 1) # alive def test_hard_server_error(): normal_port = 21211 mc = libmc.Client(["127.0.0.1:%d" % normal_port]) RETRY_TIMEOUT = 20 mc.config(libmc.MC_RETRY_TIMEOUT, RETRY_TIMEOUT) assert mc.set('foo', 1) memcached_server_ctl('stop', normal_port) assert not mc.set('foo', 1) # fail memcached_server_ctl('start', normal_port) assert not mc.set('foo', 1) # still fail time.sleep(RETRY_TIMEOUT + 1) assert mc.set('foo', 1) # back to live def main(): test_soft_server_error() test_hard_server_error() if __name__ == '__main__': main()
708
7,881
package com.kunminx.puremusic.data.api; /** * Create by KunMinX at 2021/6/3 */ public class APIs { public final static String BASE_URL = "https://test.com/"; }
60
310
{ "name": "RF645", "description": "A medium format film camera.", "url": "https://camerapedia.fandom.com/wiki/Bronica_RF645" }
51
1,436
''' Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. Please see LICENSE file in the project root for terms. ''' from com.yahoo.ml.caffe.CaffeOnSpark import CaffeOnSpark from com.yahoo.ml.caffe.Config import Config from com.yahoo.ml.caffe.DataSource import DataSource from pyspark.sql import DataFrame from pyspark.mllib.linalg import Vectors from pyspark.sql import Row from pyspark import SparkConf,SparkContext from itertools import izip_longest import unittest import os.path conf = SparkConf().setAppName("caffe-on-spark").setMaster("local[1]") sc = SparkContext(conf=conf) class PythonApiTest(unittest.TestCase): def grouper(self,iterable, n, fillvalue=None): args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) def setUp(self): #Initialize all objects self.cos=CaffeOnSpark(sc) cmdargs = conf.get('spark.pythonargs') self.args= dict(self.grouper(cmdargs.split(),2)) self.cfg=Config(sc,self.args) self.train_source = DataSource(sc).getSource(self.cfg,True) self.validation_source = DataSource(sc).getSource(self.cfg,False) def testTrain(self): self.cos.train(self.train_source) self.assertTrue(os.path.isfile(self.args.get('-model').split(":")[1][3:])) result=self.cos.features(self.validation_source) self.assertTrue('accuracy' in result.columns) self.assertTrue('ip1' in result.columns) self.assertTrue('ip2' in result.columns) self.assertTrue(result.count() > 100) self.assertTrue(result.first()['SampleID'] == '00000000') result=self.cos.test(self.validation_source) self.assertTrue(result.get('accuracy') > 0.9) def testTrainWithValidation(self): result=self.cos.trainWithValidation(self.train_source, self.validation_source) self.assertEqual(len(result.columns), 2) self.assertEqual(result.columns[0], 'accuracy') self.assertEqual(result.columns[1], 'loss') result.show(2) row_count = result.count() last_row = result.rdd.zipWithIndex().filter(lambda (row,index): index==(row_count - 1)).collect()[0][0] finalAccuracy = last_row[0][0] self.assertTrue(finalAccuracy > 0.8) finalLoss = last_row[1][0] self.assertTrue(finalLoss < 0.5) unittest.main(verbosity=2)
1,004
1,380
<gh_stars>1000+ # -*- coding: utf-8 -*- """ Defines the unit tests for the :mod:`colour.volume.spectrum` module. """ import numpy as np import unittest from itertools import permutations from colour.colorimetry import (MSDS_CMFS, SPECTRAL_SHAPE_DEFAULT, SpectralShape, reshape_msds) from colour.volume import (generate_pulse_waves, XYZ_outer_surface, is_within_visible_spectrum) from colour.utilities import ignore_numpy_errors __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2013-2021 - Colour Developers' __license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = '<EMAIL>' __status__ = 'Production' __all__ = [ 'TestGeneratePulseWaves', 'TestXYZOuterSurface', 'TestIsWithinVisibleSpectrum' ] class TestGeneratePulseWaves(unittest.TestCase): """ Defines :func:`colour.volume.spectrum.generate_pulse_waves` definition unit tests methods. """ def test_generate_pulse_waves(self): """ Tests :func:`colour.volume.spectrum.generate_pulse_waves` definition. """ np.testing.assert_array_equal( generate_pulse_waves(5), np.array([ [0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 1.0, 1.0], [1.0, 0.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], ])) np.testing.assert_array_equal( generate_pulse_waves(5, 'Pulse Wave Width'), np.array([ [0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0, 1.0], [1.0, 0.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], ])) np.testing.assert_equal( np.sort(generate_pulse_waves(5), axis=0), np.sort(generate_pulse_waves(5, 'Pulse Wave Width'), axis=0)) np.testing.assert_array_equal( generate_pulse_waves(5, 'Pulse Wave Width', True), np.array([ [0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], ])) class TestXYZOuterSurface(unittest.TestCase): """ Defines :func:`colour.volume.spectrum.XYZ_outer_surface` definition unit tests methods. """ def test_XYZ_outer_surface(self): """ Tests :func:`colour.volume.spectrum.XYZ_outer_surface` definition. """ shape = SpectralShape(SPECTRAL_SHAPE_DEFAULT.start, SPECTRAL_SHAPE_DEFAULT.end, 84) cmfs = MSDS_CMFS['CIE 1931 2 Degree Standard Observer'] # pylint: disable=E1102 np.testing.assert_array_almost_equal( XYZ_outer_surface(reshape_msds(cmfs, shape)), np.array([ [0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [9.63613812e-05, 2.90567768e-06, 4.49612264e-04], [2.59105294e-01, 2.10312980e-02, 1.32074689e+00], [1.05610219e-01, 6.20382435e-01, 3.54235713e-02], [7.26479803e-01, 3.54608696e-01, 2.10051491e-04], [1.09718745e-02, 3.96354538e-03, 0.00000000e+00], [3.07925724e-05, 1.11197622e-05, 0.00000000e+00], [2.59201656e-01, 2.10342037e-02, 1.32119651e+00], [3.64715514e-01, 6.41413733e-01, 1.35617047e+00], [8.32090022e-01, 9.74991131e-01, 3.56336228e-02], [7.37451677e-01, 3.58572241e-01, 2.10051491e-04], [1.10026671e-02, 3.97466514e-03, 0.00000000e+00], [1.27153954e-04, 1.40254398e-05, 4.49612264e-04], [3.64811875e-01, 6.41416639e-01, 1.35662008e+00], [1.09119532e+00, 9.96022429e-01, 1.35638052e+00], [8.43061896e-01, 9.78954677e-01, 3.56336228e-02], [7.37482470e-01, 3.58583361e-01, 2.10051491e-04], [1.10990285e-02, 3.97757082e-03, 4.49612264e-04], [2.59232448e-01, 2.10453234e-02, 1.32119651e+00], [1.09129168e+00, 9.96025335e-01, 1.35683013e+00], [1.10216719e+00, 9.99985975e-01, 1.35638052e+00], [8.43092689e-01, 9.78965796e-01, 3.56336228e-02], [7.37578831e-01, 3.58586267e-01, 6.59663755e-04], [2.70204323e-01, 2.50088688e-02, 1.32119651e+00], [3.64842668e-01, 6.41427759e-01, 1.35662008e+00], [1.10226355e+00, 9.99988880e-01, 1.35683013e+00], [1.10219798e+00, 9.99997094e-01, 1.35638052e+00], [8.43189050e-01, 9.78968702e-01, 3.60832350e-02], [9.96684125e-01, 3.79617565e-01, 1.32140656e+00], [3.75814542e-01, 6.45391304e-01, 1.35662008e+00], [1.09132247e+00, 9.96036455e-01, 1.35683013e+00], [1.10229434e+00, 1.00000000e+00, 1.35683013e+00], ]), decimal=7) class TestIsWithinVisibleSpectrum(unittest.TestCase): """ Defines :func:`colour.volume.spectrum.is_within_visible_spectrum` definition unit tests methods. """ def test_is_within_visible_spectrum(self): """ Tests :func:`colour.volume.spectrum.is_within_visible_spectrum` definition. """ self.assertTrue( is_within_visible_spectrum(np.array([0.3205, 0.4131, 0.5100]))) self.assertFalse( is_within_visible_spectrum(np.array([-0.0005, 0.0031, 0.0010]))) self.assertTrue( is_within_visible_spectrum(np.array([0.4325, 0.3788, 0.1034]))) self.assertFalse( is_within_visible_spectrum(np.array([0.0025, 0.0088, 0.0340]))) def test_n_dimensional_is_within_visible_spectrum(self): """ Tests :func:`colour.volume.spectrum.is_within_visible_spectrum` definition n-dimensional arrays support. """ a = np.array([0.3205, 0.4131, 0.5100]) b = is_within_visible_spectrum(a) a = np.tile(a, (6, 1)) b = np.tile(b, 6) np.testing.assert_almost_equal(is_within_visible_spectrum(a), b) a = np.reshape(a, (2, 3, 3)) b = np.reshape(b, (2, 3)) np.testing.assert_almost_equal(is_within_visible_spectrum(a), b) @ignore_numpy_errors def test_nan_is_within_visible_spectrum(self): """ Tests :func:`colour.volume.spectrum.is_within_visible_spectrum` definition nan support. """ cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] cases = set(permutations(cases * 3, r=3)) for case in cases: is_within_visible_spectrum(case) if __name__ == '__main__': unittest.main()
5,388
3,227
<reponame>ffteja/cgal // Copyright (c) 2007 // GeometryFactory (France), // Utrecht University (The Netherlands), // ETH Zurich (Switzerland), // INRIA Sophia-Antipolis (France), // Max-Planck-Institute Saarbruecken (Germany), // and Tel-Aviv University (Israel). All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL$ // $Id$ // SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : <NAME> <<EMAIL>> // <NAME> <<EMAIL>> // <NAME> // <NAME> <<EMAIL>> #ifndef CGAL_ITERATOR_TRANSFORM_H #define CGAL_ITERATOR_TRANSFORM_H 1 #include <CGAL/Iterator_project.h> namespace CGAL { template < class I, class Fct> class Iterator_transform { protected: I nt; // The internal iterator. public: typedef Iterator_transform<I,Fct> Self; typedef I Iterator; // base iterator typedef std::iterator_traits<I> traits; typedef typename traits::difference_type difference_type; typedef typename traits::iterator_category iterator_category; typedef typename traits::value_type base_value_type; typedef typename traits::pointer base_pointer; typedef typename traits::reference base_reference; typedef typename Fct::argument_type argument_type; typedef typename Fct::result_type value_type; // This iterator returns rvalues by design (allowing the conversion function to return new objects) typedef value_type reference; // Use I_TYPE_MATCH_IF to find correct pointer type. typedef I_TYPE_MATCH_IF< base_pointer, const base_value_type *, const value_type *, value_type *> Match2; typedef typename Match2::Result pointer; // CREATION // -------- Iterator_transform() {} Iterator_transform( I j) : nt(j) {} // make two iterators assignable if the underlying iterators are template <class I2> Iterator_transform( const Iterator_transform<I2,Fct>& i2) : nt( i2.current_iterator()) {} template <class I2> Self& operator= ( const Iterator_transform<I2,Fct>& i2) { nt = i2.current_iterator(); return *this; } // OPERATIONS Forward Category // --------------------------- Iterator current_iterator() const { return nt;} bool operator==( const Self& i) const { return ( nt == i.nt); } bool operator!=( const Self& i) const { return !(*this == i); } struct Proxy { Proxy(const reference r) : ref(r) {} reference ref; pointer operator->() { return &ref; } }; Proxy operator->() const { return Proxy(Fct()(*nt)); } reference operator* () const { Fct fct; return fct(*nt); } Self& operator++() { ++nt; return *this; } Self operator++(int) { Self tmp = *this; ++*this; return tmp; } // OPERATIONS Bidirectional Category // --------------------------------- Self& operator--() { --nt; return *this; } Self operator--(int) { Self tmp = *this; --*this; return tmp; } // OPERATIONS Random Access Category // --------------------------------- Self& operator+=( difference_type n) { nt += n; return *this; } Self operator+( difference_type n) const { Self tmp = *this; return tmp += n; } Self& operator-=( difference_type n) { return operator+=( -n); } Self operator-( difference_type n) const { Self tmp = *this; return tmp += -n; } difference_type operator-( const Self& i) const { return nt - i.nt; } reference operator[]( difference_type n) const { Self tmp = *this; tmp += n; return tmp.operator*(); } bool operator< ( const Self& i) const { return ( nt < i.nt); } bool operator> ( const Self& i) const { return i < *this; } bool operator<=( const Self& i) const { return !(i < *this); } bool operator>=( const Self& i) const { return !(*this < i); } }; template < class Dist, class Fct, class I> inline Iterator_transform<I,Fct> operator+( Dist n, Iterator_transform<I,Fct> i) { return i += n; } } //namespace CGAL #endif // CGAL_Iterator_transform_H // // EOF //
1,577
737
<reponame>etnrlz/rtbkit /** periodic_utils.cc <NAME>, 4 April 2012 Copyright (c) 2012 Datacratic. All rights reserved. */ #include "periodic_utils.h" #include "jml/utils/parse_context.h" #include <boost/tuple/tuple.hpp> #include "jml/utils/exc_assert.h" using namespace std; using namespace Datacratic; namespace { TimeGranularity granularities[] = { MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS, WEEKS, MONTHS, YEARS }; size_t maxGranularity = (sizeof(granularities) / sizeof(TimeGranularity)); int granularityIndex(TimeGranularity granularity) { for (size_t i = 0; i < maxGranularity; i++) { if (granularities[i] == granularity) { return i; } } throw ML::Exception("granularity not found"); } } namespace Datacratic { TimeGranularity operator + (TimeGranularity granularity, int steps) { int i = granularityIndex(granularity); if (steps > 0) { if (i + steps >= maxGranularity) { throw ML::Exception("granularity index would be too high"); } } else if (steps < 0) { if (i + steps < 0) { throw ML::Exception("granularity index would be negative"); } } return granularities[i + steps]; } /** Returns whether one granularity unit can be translated to the other. */ bool canTranslateGranularity(TimeGranularity sourceGranularity, TimeGranularity destGranularity) { /* We have 2 families of granularities: one based on milliseconds and the other based on months. They are incompatible with one another but they share characteristics which enables the simplification of this code : - the source granularity unit must be >= to the destination unit - both units must be from the same family */ if (sourceGranularity == destGranularity) { return true; } else if (destGranularity > sourceGranularity) { return false; } else if (sourceGranularity < MONTHS) { return true; } else if (sourceGranularity == YEARS) { return destGranularity == MONTHS; } throw ML::Exception("we should never get here"); } /** Number of units of one granularity that first in the other granularity. */ int granularityMultiplier(TimeGranularity sourceGranularity, TimeGranularity destGranularity) { if (!canTranslateGranularity(sourceGranularity, destGranularity)) { throw ML::Exception("specified granularities are incompatible with" " each other"); } int fromIndex = granularityIndex(destGranularity); int toIndex = granularityIndex(sourceGranularity); if (fromIndex > toIndex) { throw ML::Exception("the source granularity must be bigger that the" " destination"); } int multiplier(1); const int msMults[] = { 1000, 60, 60, 24, 7 }; const int monthsMults[] = { 12 }; const int * multipliers; if (sourceGranularity < MONTHS) { multipliers = msMults; } else { multipliers = monthsMults; } int offset = fromIndex >= 6 ? 6 : 0; for (int i = fromIndex; i < toIndex; i++) { multiplier *= multipliers[i - offset]; } return multiplier; } std::pair<TimeGranularity, double> parsePeriod(const std::string & pattern) { TimeGranularity granularity; double number; ML::Parse_Context context(pattern, pattern.c_str(), pattern.c_str() + pattern.length()); number = context.expect_double(); //if (number <= 0) // context.exception("invalid time number: must be > 0"); if (context.match_literal('x') || context.match_literal("ms")) granularity = MILLISECONDS; else if (context.match_literal('s')) granularity = SECONDS; else if (context.match_literal('m')) granularity = MINUTES; else if (context.match_literal('h')) granularity = HOURS; else if (context.match_literal('d')) granularity = DAYS; else if (context.match_literal('w')) granularity = WEEKS; else if (context.match_literal('M')) granularity = MONTHS; else if (context.match_literal('y')) granularity = YEARS; else context.exception("excepted h, m, s, d, w, M, y or x"); context.expect_eof(); return make_pair(granularity, number); } std::pair<Date, double> findPeriod(Date current, const std::string & period) { TimeGranularity p; double n; boost::tie(p, n) = parsePeriod(period); return findPeriod(current, p, n); } std::pair<Date, double> findPeriod(Date current, TimeGranularity granularity, double number_) { if (number_ == 0) return make_pair(current, 0); int64_t number = number_; // Make sure it's an integer number of seconds ExcAssertEqual(number, number_); // Find where the current period starts tm t = current.toTm(); // Remove fractional seconds Date result = current; int64_t seconds = result.secondsSinceEpoch(); result = Date::fromSecondsSinceEpoch(seconds); //Date unadjusted = result; double interval; switch (granularity) { case DAYS: current.quantize(3600 * 24); interval = 3600 * 24 * number; break; if (number != 1) throw ML::Exception("only 1d is supported for days"); // Go to the start of the day result.addSeconds(-(3600 * t.tm_hour + 60 * t.tm_min + t.tm_sec)); // Go to day interval = 3600 * 24 * number; break; case HOURS: // Go to the start of the hour result.addSeconds(-(60 * t.tm_min + t.tm_sec)); // Go to hour number n of the day result.addSeconds(-3600 * (t.tm_hour % number)); interval = 3600 * number; break; case MINUTES: // Go to the start of the minute result.addSeconds(-t.tm_sec); // Go to the next multiple of minutes result.addSeconds(-60 * (t.tm_min % number)); interval = 60 * number; break; case SECONDS: //cerr << "seconds: t.tm_sec = " << t.tm_sec // << " number = " << number << " before = " // << result; result.addSeconds(-(t.tm_sec % number)); //cerr <<" after = " << result << " current = " // << current << endl; interval = number; break; case MILLISECONDS: interval = number / 1000.0; result = current.quantized(interval); if (result > current) result.addSeconds(-interval); break; default: throw ML::Exception("that granularity is not supported"); } return make_pair(result, interval); } std::string filenameFor(const Date & date, const std::string & pattern) { return date.print(pattern); } /*****************************************************************************/ /* TIME PERIOD */ /*****************************************************************************/ TimePeriod:: TimePeriod(const std::string & periodName) { parse(periodName); } TimePeriod:: TimePeriod(const char * periodName) { parse(periodName); } TimePeriod:: TimePeriod(TimeGranularity granularity, double number) : granularity(granularity), number(number), interval(findPeriod(Date(), granularity, number).second) { } Date TimePeriod:: current(Date now) const { return findPeriod(now, granularity, number).first; } Date TimePeriod:: next(Date now) const { return current(now).plusSeconds(interval); } std::string TimePeriod:: toString() const { string result = boost::lexical_cast<string>(number);//ML::format("%f", number); switch (granularity) { case MILLISECONDS: result += "ms"; return result; case SECONDS: result += 's'; return result; case MINUTES: result += 'm'; return result; case HOURS: result += 'h'; return result; case DAYS: result += 'd'; return result; case WEEKS: result += 'w'; return result; case MONTHS: result += 'M'; return result; case YEARS: result += 'y'; return result; default: throw ML::Exception("unknown time period"); } } void TimePeriod:: parse(const std::string & str) { std::tie(granularity, number) = parsePeriod(str); interval = findPeriod(Date(), granularity, number).second; } TimePeriod TimePeriod:: operator + (const TimePeriod & other) const { TimePeriod result; int thisIndex = granularityIndex(granularity); int otherIndex = granularityIndex(other.granularity); if (thisIndex < otherIndex) { int multiplier = granularityMultiplier(other.granularity, granularity); result.number = number + multiplier * other.number; result.granularity = granularity; } else { int multiplier = granularityMultiplier(granularity, other.granularity); result.number = other.number + multiplier * number; result.granularity = other.granularity; } result.interval = interval + other.interval; return result; } } // namespace Datacratic
3,748
3,702
/* * 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 app.metatron.discovery.domain.dataprep; import static org.junit.Assert.assertEquals; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; import org.junit.Test; public class PrepDatasetStagingDbServiceTest { class SQLStringTestSet { @Nullable String queryStmt; String size; @Nullable String dbName; @Nullable String tblName; String expected; SQLStringTestSet(@Nullable String queryStmt, String size, String expected) { this.queryStmt = queryStmt; this.size = size; this.expected = expected; } SQLStringTestSet( @Nullable String queryStmt, String size, @Nullable String dbName, @Nullable String tblName, String expected) { this.queryStmt = queryStmt; this.size = size; this.dbName = dbName; this.tblName = tblName; this.expected = expected; } } @Test public void testSQLString() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { PrepDatasetStagingDbService service = new PrepDatasetStagingDbService(); Class stringClass = String.class; Method getSQLString = service.getClass() .getDeclaredMethod("getSQLString", stringClass, stringClass, stringClass, stringClass); getSQLString.setAccessible(true); List<SQLStringTestSet> testSets = Arrays.asList( new SQLStringTestSet("SELECT * FROM db.table", "10", "SELECT * FROM db.table LIMIT 10"), new SQLStringTestSet("SELECT * FROM db.table;", "10", "SELECT * FROM db.table LIMIT 10"), new SQLStringTestSet("SELECT * FROM db.table;\t", "10", "SELECT * FROM db.table LIMIT 10"), new SQLStringTestSet("SELECT * FROM db.table LIMIT 100", "10", "SELECT * FROM db.table LIMIT 100"), new SQLStringTestSet("SELECT * FROM db.table LIMIT 100;", "10", "SELECT * FROM db.table LIMIT 100"), new SQLStringTestSet("SELECT * FROM db.table LIMIT 100;\t", "10", "SELECT * FROM db.table LIMIT 100"), new SQLStringTestSet(null, "10", "db", "table", "SELECT * FROM db.table LIMIT 10") ); for (SQLStringTestSet test : testSets) { assertEquals(test.expected, getSQLString.invoke(service, test.queryStmt, test.size, test.dbName, test.tblName)); } } }
1,080