text:
.class Lcom/android/server/MountService$1;
.super Landroid/content/BroadcastReceiver;
.source "MountService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/MountService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/MountService;

# direct methods
.method constructor <init>(Lcom/android/server/MountService;)V
    .locals 0
    .parameter

    .prologue
    .line 561
    iput-object p1, p0, Lcom/android/server/MountService$1;->this$0:Lcom/android/server/MountService;

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 8
    .parameter "context"
    .parameter "intent"

    .prologue
    const/4 v7, -0x1

    .line 564
    const-string v6, "android.intent.extra.user_handle"

    invoke-virtual {p2, v6, v7}, Landroid/content/Intent;->getIntExtra(Ljava/lang/String;I)I

    move-result v4

    .line 565
    .local v4, userId:I
    if-ne v4, v7, :cond_1

    .line 587
    :cond_0
    :goto_0
    return-void

    .line 566
    :cond_1
    new-instance v3, Landroid/os/UserHandle;

    invoke-direct {v3, v4}, Landroid/os/UserHandle;-><init>(I)V

    .line 568
    .local v3, user:Landroid/os/UserHandle;
    invoke-virtual {p2}, Landroid/content/Intent;->getAction()Ljava/lang/String;

    move-result-object v0

    .line 569
    .local v0, action:Ljava/lang/String;
    const-string v6, "android.intent.action.USER_ADDED"

    invoke-virtual {v6, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_2

    .line 570
    iget-object v6, p0, Lcom/android/server/MountService$1;->this$0:Lcom/android/server/MountService;

    #getter for: Lcom/android/server/MountService;->mVolumesLock:Ljava/lang/Object;
    invoke-static {v6}, Lcom/android/server/MountService;->access$600(Lcom/android/server/MountService;)Ljava/lang/Object;

    move-result-object v7

    monitor-enter v7

    .line 571
    :try_start_0
    iget-object v6, p0, Lcom/android/server/MountService$1;->this$0:Lcom/android/server/MountService;

    #calls: Lcom/android/server/MountService;->createEmulatedVolumeForUserLocked(Landroid/os/UserHandle;)V
    invoke-static {v6, v3}, Lcom/android/server/MountService;->access$700(Lcom/android/server/MountService;Landroid/os/UserHandle;)V

    .line 572
    monitor-exit v7

    goto :goto_0

    :catchall_0
    move-exception v6

    monitor-exit v7
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v6

    .line 574
    :cond_2
    const-string v6, "android.intent.action.USER_REMOVED"

    invoke-virtual {v6, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_0

    .line 575
    iget-object v6, p0, Lcom/android/server/MountService$1;->this$0:Lcom/android/server/MountService;

    #getter for: Lcom/android/server/MountService;->mVolumesLock:Ljava/lang/Object;
    invoke-static {v6}, Lcom/android/server/MountService;->access$600(Lcom/android/server/MountService;)Ljava/lang/Object;

    move-result-object v7

    monitor-enter v7

    .line 576
    :try_start_1
    invoke-static {}, Lcom/google/android/collect/Lists;->newArrayList()Ljava/util/ArrayList;

    move-result-object v2

    .line 577
    .local v2, toRemove:Ljava/util/List;,"Ljava/util/List<Landroid/os/storage/StorageVolume;>;"
    iget-object v6, p0, Lcom/android/server/MountService$1;->this$0:Lcom/android/server/MountService;

    #getter for: Lcom/android/server/MountService;->mVolumes:Ljava/util/ArrayList;
    invoke-static {v6}, Lcom/android/server/MountService;->access$800(Lcom/android/server/MountService;)Ljava/util/ArrayList;

    move-result-object v6

    invoke-virtual {v6}, Ljava/util/ArrayList;->iterator()Ljava/util/Iterator;

    move-result-object v1

    .local v1, i$:Ljava/util/Iterator;
    :cond_3
    :goto_1
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v6

    if-eqz v6, :cond_4

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v5

    check-cast v5, Landroid/os/storage/StorageVolume;

    .line 578
    .local v5, volume:Landroid/os/storage/StorageVolume;
    invoke-virtual {v5}, Landroid/os/storage/StorageVolume;->getOwner()Landroid/os/UserHandle;

    move-result-object v6

    invoke-virtual {v3, v6}, Landroid/os/UserHandle;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_3

    .line 579
    invoke-interface {v2, v5}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    goto :goto_1

    .line 585
    .end local v1           #i$:Ljava/util/Iterator;
    .end local v2           #toRemove:Ljava/util/List;,"Ljava/util/List<Landroid/os/storage/StorageVolume;>;"
    .end local v5           #volume:Landroid/os/storage/StorageVolume;
    :catchall_1
    move-exception v6

    monitor-exit v7
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_1

    throw v6

    .line 582
    .restart local v1       #i$:Ljava/util/Iterator;
    .restart local v2       #toRemove:Ljava/util/List;,"Ljava/util/List<Landroid/os/storage/StorageVolume;>;"
    :cond_4
    :try_start_2
    invoke-interface {v2}, Ljava/util/List;->iterator()Ljava/util/Iterator;

    move-result-object v1

    :goto_2
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v6

    if-eqz v6, :cond_5

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v5

    check-cast v5, Landroid/os/storage/StorageVolume;

    .line 583
    .restart local v5       #volume:Landroid/os/storage/StorageVolume;
    iget-object v6, p0, Lcom/android/server/MountService$1;->this$0:Lcom/android/server/MountService;

    #calls: Lcom/android/server/MountService;->removeVolumeLocked(Landroid/os/storage/StorageVolume;)V
    invoke-static {v6, v5}, Lcom/android/server/MountService;->access$900(Lcom/android/server/MountService;Landroid/os/storage/StorageVolume;)V

    goto :goto_2

    .line 585
    .end local v5           #volume:Landroid/os/storage/StorageVolume;
    :cond_5
    monitor-exit v7
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_1

    goto :goto_0
.end method


text:
import * as React from 'react';
import Box from '@material-ui/core/Box';

export default function Display() {
  return (
    <div style={{ width: '100%' }}>
      <Box sx={{ display: 'flex', p: 1, bgcolor: 'background.paper' }}>
        {"I'm a flexbox container!"}
      </Box>
    </div>
  );
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\ExceptionInterface;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;

/**
 * This replaces all ChildDefinition instances with their equivalent fully
 * merged Definition instance.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 * @author Nicolas Grekas <p@tchwork.com>
 */
class ResolveDefinitionTemplatesPass extends AbstractRecursivePass
{
    protected function processValue($value, $isRoot = false)
    {
        if (!$value instanceof Definition) {
            return parent::processValue($value, $isRoot);
        }
        if ($isRoot) {
            // yes, we are specifically fetching the definition from the
            // container to ensure we are not operating on stale data
            $value = $this->container->getDefinition($this->currentId);
        }
        if ($value instanceof ChildDefinition) {
            $value = $this->resolveDefinition($value);
            if ($isRoot) {
                $this->container->setDefinition($this->currentId, $value);
            }
        }

        return parent::processValue($value, $isRoot);
    }

    /**
     * Resolves the definition.
     *
     * @return Definition
     *
     * @throws RuntimeException When the definition is invalid
     */
    private function resolveDefinition(ChildDefinition $definition)
    {
        try {
            return $this->doResolveDefinition($definition);
        } catch (ExceptionInterface $e) {
            $r = new \ReflectionProperty($e, 'message');
            $r->setAccessible(true);
            $r->setValue($e, sprintf('Service "%s": %s', $this->currentId, $e->getMessage()));

            throw $e;
        }
    }

    private function doResolveDefinition(ChildDefinition $definition)
    {
        if (!$this->container->has($parent = $definition->getParent())) {
            throw new RuntimeException(sprintf('Parent definition "%s" does not exist.', $parent));
        }

        $parentDef = $this->container->findDefinition($parent);
        if ($parentDef instanceof ChildDefinition) {
            $id = $this->currentId;
            $this->currentId = $parent;
            $parentDef = $this->resolveDefinition($parentDef);
            $this->container->setDefinition($parent, $parentDef);
            $this->currentId = $id;
        }

        $this->container->log($this, sprintf('Resolving inheritance for "%s" (parent: %s).', $this->currentId, $parent));
        $def = new Definition();

        // merge in parent definition
        // purposely ignored attributes: abstract, tags
        $def->setClass($parentDef->getClass());
        $def->setArguments($parentDef->getArguments());
        $def->setMethodCalls($parentDef->getMethodCalls());
        $def->setOverriddenGetters($parentDef->getOverriddenGetters());
        $def->setProperties($parentDef->getProperties());
        if ($parentDef->getAutowiringTypes(false)) {
            $def->setAutowiringTypes($parentDef->getAutowiringTypes(false));
        }
        if ($parentDef->isDeprecated()) {
            $def->setDeprecated(true, $parentDef->getDeprecationMessage('%service_id%'));
        }
        $def->setFactory($parentDef->getFactory());
        $def->setConfigurator($parentDef->getConfigurator());
        $def->setFile($parentDef->getFile());
        $def->setPublic($parentDef->isPublic());
        $def->setLazy($parentDef->isLazy());
        $def->setAutowiredCalls($parentDef->getAutowiredCalls());

        self::mergeDefinition($def, $definition);

        // merge autowiring types
        foreach ($definition->getAutowiringTypes(false) as $autowiringType) {
            $def->addAutowiringType($autowiringType);
        }

        // these attributes are always taken from the child
        $def->setAbstract($definition->isAbstract());
        $def->setShared($definition->isShared());
        $def->setTags($definition->getTags());

        return $def;
    }

    /**
     * @internal
     */
    public static function mergeDefinition(Definition $def, ChildDefinition $definition)
    {
        // overwrite with values specified in the decorator
        $changes = $definition->getChanges();
        if (isset($changes['class'])) {
            $def->setClass($definition->getClass());
        }
        if (isset($changes['factory'])) {
            $def->setFactory($definition->getFactory());
        }
        if (isset($changes['configurator'])) {
            $def->setConfigurator($definition->getConfigurator());
        }
        if (isset($changes['file'])) {
            $def->setFile($definition->getFile());
        }
        if (isset($changes['public'])) {
            $def->setPublic($definition->isPublic());
        }
        if (isset($changes['lazy'])) {
            $def->setLazy($definition->isLazy());
        }
        if (isset($changes['deprecated'])) {
            $def->setDeprecated($definition->isDeprecated(), $definition->getDeprecationMessage('%service_id%'));
        }
        if (isset($changes['autowired_calls'])) {
            $def->setAutowiredCalls($definition->getAutowiredCalls());
        }
        if (isset($changes['decorated_service'])) {
            $decoratedService = $definition->getDecoratedService();
            if (null === $decoratedService) {
                $def->setDecoratedService($decoratedService);
            } else {
                $def->setDecoratedService($decoratedService[0], $decoratedService[1], $decoratedService[2]);
            }
        }

        // merge arguments
        foreach ($definition->getArguments() as $k => $v) {
            if (is_numeric($k)) {
                $def->addArgument($v);
                continue;
            }

            if (0 === strpos($k, 'index_')) {
                $index = (int) substr($k, strlen('index_'));
            } elseif (0 !== strpos($k, '$')) {
                throw new RuntimeException(sprintf('Invalid argument key "%s" found.', $k));
            }

            $def->replaceArgument($index, $v);
        }

        // merge properties
        foreach ($definition->getProperties() as $k => $v) {
            $def->setProperty($k, $v);
        }

        // append method calls
        if ($calls = $definition->getMethodCalls()) {
            $def->setMethodCalls(array_merge($def->getMethodCalls(), $calls));
        }

        // merge overridden getters
        foreach ($definition->getOverriddenGetters() as $k => $v) {
            $def->setOverriddenGetter($k, $v);
        }
    }
}


text:
package com.dseuss.alarmclock;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import com.dseuss.deskclock.DeskClock;
import com.dseuss.deskclock.R;
import com.dseuss.deskclock.Utils;
import com.dseuss.deskclock.alarms.AlarmNotifications;
import com.dseuss.deskclock.worldclock.Cities;
import com.dseuss.deskclock.worldclock.CitiesActivity;

import java.util.Locale;

public class DigitalAppWidgetProvider extends AppWidgetProvider {
    private static final String TAG = "DigitalAppWidgetProvider";

    /**
     * Intent to be used for checking if a world clock's date has changed. Must be every fifteen
     * minutes because not all time zones are hour-locked.
     **/
    public static final String ACTION_ON_QUARTER_HOUR = "com.dseuss.deskclock.ON_QUARTER_HOUR";

    // Lazily creating this intent to use with the AlarmManager
    private PendingIntent mPendingIntent;
    // Lazily creating this name to use with the AppWidgetManager
    private ComponentName mComponentName;

    public DigitalAppWidgetProvider() {
    }

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        startAlarmOnQuarterHour(context);
    }

    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
        cancelAlarmOnQuarterHour(context);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DigitalAppWidgetService.LOGGING) {
            Log.i(TAG, "onReceive: " + action);
        }
        super.onReceive(context, intent);

        if (ACTION_ON_QUARTER_HOUR.equals(action)
                || Intent.ACTION_DATE_CHANGED.equals(action)
                || Intent.ACTION_TIMEZONE_CHANGED.equals(action)
                || Intent.ACTION_TIME_CHANGED.equals(action)
                || Intent.ACTION_LOCALE_CHANGED.equals(action)) {
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            if (appWidgetManager != null) {
                int[] appWidgetIds = appWidgetManager.getAppWidgetIds(getComponentName(context));
                for (int appWidgetId : appWidgetIds) {
                    appWidgetManager.
                            notifyAppWidgetViewDataChanged(appWidgetId,
                                    R.id.digital_appwidget_listview);
                    RemoteViews widget = new RemoteViews(context.getPackageName(),
                            R.layout.digital_appwidget);
                    float ratio = WidgetUtils.getScaleRatio(context, null, appWidgetId);
                    WidgetUtils.setTimeFormat(widget, 0/*no am/pm*/, R.id.the_clock);
                    WidgetUtils.setClockSize(context, widget, ratio);
                    refreshAlarm(context, widget);
                    appWidgetManager.partiallyUpdateAppWidget(appWidgetId, widget);
                }
            }
            if(!ACTION_ON_QUARTER_HOUR.equals(action)) {
                cancelAlarmOnQuarterHour(context);
            }
            startAlarmOnQuarterHour(context);
        } else if (AlarmNotifications.SYSTEM_ALARM_CHANGE_ACTION.equals(action)
                || Intent.ACTION_SCREEN_ON.equals(action)) {
            // Refresh the next alarm
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            if (appWidgetManager != null) {
                int[] appWidgetIds = appWidgetManager.getAppWidgetIds(getComponentName(context));
                for (int appWidgetId : appWidgetIds) {
                    RemoteViews widget = new RemoteViews(context.getPackageName(),
                            R.layout.digital_appwidget);
                    refreshAlarm(context, widget);
                    appWidgetManager.partiallyUpdateAppWidget(appWidgetId, widget);
                }
            }
        } else if (Cities.WORLDCLOCK_UPDATE_INTENT.equals(action)) {
            // Refresh the world cities list
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            if (appWidgetManager != null) {
                int[] appWidgetIds = appWidgetManager.getAppWidgetIds(getComponentName(context));
                for (int appWidgetId : appWidgetIds) {
                    appWidgetManager.
                            notifyAppWidgetViewDataChanged(appWidgetId,
                                    R.id.digital_appwidget_listview);
                }
            }
        }
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        if (DigitalAppWidgetService.LOGGING) {
            Log.i(TAG, "onUpdate");
        }
        for (int appWidgetId : appWidgetIds) {
            float ratio = WidgetUtils.getScaleRatio(context, null, appWidgetId);
            updateClock(context, appWidgetManager, appWidgetId, ratio);
        }
        startAlarmOnQuarterHour(context);
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager,
            int appWidgetId, Bundle newOptions) {
        // scale the fonts of the clock to fit inside the new size
        float ratio = WidgetUtils.getScaleRatio(context, newOptions, appWidgetId);
        AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
        updateClock(context, widgetManager, appWidgetId, ratio);
    }

    private void updateClock(
            Context context, AppWidgetManager appWidgetManager, int appWidgetId, float ratio) {
        RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.digital_appwidget);

        // Launch clock when clicking on the time in the widget only if not a lock screen widget
        Bundle newOptions = appWidgetManager.getAppWidgetOptions(appWidgetId);
        if (newOptions != null &&
                newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, -1)
                != AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD) {
            widget.setOnClickPendingIntent(R.id.digital_appwidget,
                    PendingIntent.getActivity(context, 0, new Intent(context, DeskClock.class), 0));
        }

        // Setup alarm text clock's format and font sizes
        refreshAlarm(context, widget);
        WidgetUtils.setTimeFormat(widget, 0/*no am/pm*/, R.id.the_clock);
        WidgetUtils.setClockSize(context, widget, ratio);

        // Set today's date format
        CharSequence dateFormat = DateFormat.getBestDateTimePattern(Locale.getDefault(),
                context.getString(R.string.abbrev_wday_month_day_no_year));
        widget.setCharSequence(R.id.date, "setFormat12Hour", dateFormat);
        widget.setCharSequence(R.id.date, "setFormat24Hour", dateFormat);

        // Set up R.id.digital_appwidget_listview to use a remote views adapter
        // That remote views adapter connects to a RemoteViewsService through intent.
        final Intent intent = new Intent(context, DigitalAppWidgetService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
        widget.setRemoteAdapter(R.id.digital_appwidget_listview, intent);

        // Set up the click on any world clock to start the Cities Activity
        //TODO: Should this be in the options guard above?
        widget.setPendingIntentTemplate(R.id.digital_appwidget_listview,
                PendingIntent.
                        getActivity(context, 0, new Intent(context, CitiesActivity.class), 0));

        // Refresh the widget
        appWidgetManager.notifyAppWidgetViewDataChanged(
                appWidgetId, R.id.digital_appwidget_listview);
        appWidgetManager.updateAppWidget(appWidgetId, widget);
    }

    protected void refreshAlarm(Context context, RemoteViews widget) {
        String nextAlarm = Settings.System.getString(context.getContentResolver(),
                Settings.System.NEXT_ALARM_FORMATTED);
        if (!TextUtils.isEmpty(nextAlarm)) {
            widget.setTextViewText(R.id.nextAlarm,
                    context.getString(R.string.control_set_alarm_with_existing, nextAlarm));
            widget.setViewVisibility(R.id.nextAlarm, View.VISIBLE);
            if (DigitalAppWidgetService.LOGGING) {
                Log.v(TAG, "DigitalWidget sets next alarm string to " + nextAlarm);
            }
        } else  {
            widget.setViewVisibility(R.id.nextAlarm, View.GONE);
            if (DigitalAppWidgetService.LOGGING) {
                Log.v(TAG, "DigitalWidget sets next alarm string to null");
            }
        }
    }

    /**
     * Start an alarm that fires on the next quarter hour to update the world clock city
     * day when the local time or the world city crosses midnight.
     *
     * @param context The context in which the PendingIntent should perform the broadcast.
     */
    private void startAlarmOnQuarterHour(Context context) {
        if (context != null) {
            long onQuarterHour = Utils.getAlarmOnQuarterHour();
            PendingIntent quarterlyIntent = getOnQuarterHourPendingIntent(context);
            AlarmManager alarmManager = ((AlarmManager) context
                    .getSystemService(Context.ALARM_SERVICE));
            if (Utils.isKitKatOrLater()) {
                alarmManager.setExact(AlarmManager.RTC, onQuarterHour, quarterlyIntent);
            } else {
                alarmManager.set(AlarmManager.RTC, onQuarterHour, quarterlyIntent);
            }
            if (DigitalAppWidgetService.LOGGING) {
                Log.v(TAG, "startAlarmOnQuarterHour " + context.toString());
            }
        }
    }

    /**
     * Remove the alarm for the quarter hour update.
     *
     * @param context The context in which the PendingIntent was started to perform the broadcast.
     */
    public void cancelAlarmOnQuarterHour(Context context) {
        if (context != null) {
            PendingIntent quarterlyIntent = getOnQuarterHourPendingIntent(context);
            if (DigitalAppWidgetService.LOGGING) {
                Log.v(TAG, "cancelAlarmOnQuarterHour " + context.toString());
            }
            ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(
                    quarterlyIntent);
        }
    }

    /**
     * Create the pending intent that is broadcast on the quarter hour.
     *
     * @param context The Context in which this PendingIntent should perform the broadcast.
     * @return a pending intent with an intent unique to DigitalAppWidgetProvider
     */
    private PendingIntent getOnQuarterHourPendingIntent(Context context) {
        if (mPendingIntent == null) {
            mPendingIntent = PendingIntent.getBroadcast(context, 0,
                new Intent(ACTION_ON_QUARTER_HOUR), PendingIntent.FLAG_CANCEL_CURRENT);
        }
        return mPendingIntent;
    }

    /**
     * Create the component name for this class
     *
     * @param context The Context in which the widgets for this component are created
     * @return the ComponentName unique to DigitalAppWidgetProvider
     */
    private ComponentName getComponentName(Context context) {
        if (mComponentName == null) {
            mComponentName = new ComponentName(context, getClass());
        }
        return mComponentName;
    }
}


text:
import {Component, Injectable, OnInit} from '@angular/core';
import {ActivatedRoute, ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot} from '@angular/router';
import {GroupList, ApiGroup, ConsoleService, UserRole} from '../console.service';
import {Observable} from 'rxjs';
import {FormBuilder, FormGroup} from '@angular/forms';
import {AuthenticationService} from '../authentication.service';

@Component({
  templateUrl: './groups.component.html',
  styleUrls: ['./groups.component.scss']
})
export class GroupListComponent implements OnInit {
  public readonly systemUserId = '00000000-0000-0000-0000-000000000000';
  public error = '';
  public groupsCount = 0;
  public groups: Array<ApiGroup> = [];
  public nextCursor = '';
  public prevCursor = '';
  public searchForm: FormGroup;

  constructor(
    private readonly route: ActivatedRoute,
    private readonly router: Router,
    private readonly consoleService: ConsoleService,
    private readonly authService: AuthenticationService,
    private readonly formBuilder: FormBuilder,
  ) {}

  ngOnInit(): void {
    this.searchForm = this.formBuilder.group({
      filter: [''],
    });

    const qp = this.route.snapshot.queryParamMap;
    this.f.filter.setValue(qp.get('filter'));
    this.nextCursor = qp.get('cursor');

    if (this.nextCursor && this.nextCursor !== '') {
      this.search(1);
    } else if (this.f.filter.value) {
      this.search(0);
    }

    this.route.data.subscribe(
      d => {
        this.groups.length = 0;
        if (d) {
          this.groups.push(...d[0].groups);
          this.groupsCount = d[0].total_count;
          this.nextCursor = d[0].next_cursor;
          this.prevCursor = d[0].prev_cursor;
        }
      },
      err => {
        this.error = err;
      });
  }

  search(state: number): void {
    let cursor = '';
    switch (state) {
      case -1:
        cursor = this.prevCursor;
        break;
      case 0:
        cursor = '';
        break;
      case 1:
        cursor = this.nextCursor;
        break;
    }

    this.consoleService.listGroups('', this.f.filter.value, cursor).subscribe(d => {
      this.error = '';

      this.groups.length = 0;
      this.groups.push(...d.groups);
      this.groupsCount = d.total_count;
      this.nextCursor = d.next_cursor;

      this.router.navigate([], {
        relativeTo: this.route,
        queryParams: {
          filter: this.f.filter.value,
          cursor
        },
        queryParamsHandling: 'merge',
      });
    }, err => {
      this.error = err;
    });
  }

  deleteGroup(event, i: number, o: ApiGroup): void {
    event.target.disabled = true;
    event.preventDefault();
    this.error = '';
    this.consoleService.deleteGroup('', o.id).subscribe(() => {
      this.error = '';
      this.groups.splice(i, 1);
      this.groupsCount--;
    }, err => {
      this.error = err;
    });
  }

  deleteAllowed(): boolean {
    // only admin and developers are allowed.
    return this.authService.sessionRole <= UserRole.USER_ROLE_DEVELOPER;
  }

  viewGroup(g: ApiGroup): void {
    this.router.navigate(['/groups', g.id], {relativeTo: this.route});
  }

  get f(): any {
    return this.searchForm.controls;
  }
}

@Injectable({providedIn: 'root'})
export class GroupSearchResolver implements Resolve<GroupList> {
  constructor(private readonly consoleService: ConsoleService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<GroupList> {
    const filter = route.queryParamMap.get('filter');

    return this.consoleService.listGroups('', filter, null);
  }
}


text:
    #pragma hdrstop
#endif

#ifndef WX_PRECOMP
    #include "wx/app.h"
    #include "wx/frame.h"
    #include "wx/log.h"
#endif

#include "wx/textctrl.h"
#include "wx/msgdlg.h"
#include "wx/menu.h"
#include "wx/timer.h"

#include "wx/power.h"

#ifndef wxHAS_IMAGES_IN_RESOURCES
    #include "../sample.xpm"
#endif

// ----------------------------------------------------------------------------
// main frame class
// ----------------------------------------------------------------------------

class MyFrame : public wxFrame
{
public:
    MyFrame()
        : wxFrame(NULL, wxID_ANY, wxT("wxWidgets Power Management Sample"),
                  wxDefaultPosition, wxSize(500, 200))
    {
        m_powerResourceBlocker = NULL;

        wxMenu *fileMenu = new wxMenu;
        fileMenu->Append(wxID_NEW, "Start long running task\tCtrl-S");
        fileMenu->Append(wxID_ABORT, "Stop long running task");

        wxMenuBar* menuBar = new wxMenuBar();
        menuBar->Append(fileMenu, wxT("&Task"));
        SetMenuBar(menuBar);

        wxTextCtrl *text = new wxTextCtrl(this, wxID_ANY, wxT(""),
                                          wxDefaultPosition, wxDefaultSize,
                                          wxTE_MULTILINE | wxTE_READONLY);
        m_logOld = wxLog::SetActiveTarget(new wxLogTextCtrl(text));

        CreateStatusBar();

        SetIcon(wxICON(sample));

        UpdatePowerSettings(wxPOWER_UNKNOWN, wxBATTERY_UNKNOWN_STATE);

        StopLongTask();
        Bind(wxEVT_COMMAND_MENU_SELECTED,
             &MyFrame::OnStartTaskClicked, this, wxID_NEW);
        Bind(wxEVT_COMMAND_MENU_SELECTED,
             &MyFrame::OnStopTaskClicked, this, wxID_ABORT);
        m_taskTimer.Bind(wxEVT_TIMER, &MyFrame::OnTaskTimer, this);

        Show();
    }

    virtual ~MyFrame()
    {
        delete m_powerResourceBlocker;

        delete wxLog::SetActiveTarget(m_logOld);
    }

private:
    void OnIdle(wxIdleEvent& WXUNUSED(event))
    {
        const wxPowerType powerType = wxGetPowerType();
        const wxBatteryState batteryState = wxGetBatteryState();
        if ( powerType != m_powerType || batteryState != m_batteryState )
        {
            UpdatePowerSettings(powerType, batteryState);
        }
    }

#ifdef wxHAS_POWER_EVENTS
    void OnSuspending(wxPowerEvent& event)
    {
        wxLogMessage(wxT("System suspend starting..."));
        if ( wxMessageBox(wxT("Veto suspend?"), wxT("Please answer"),
                          wxYES_NO, this) == wxYES )
        {
            event.Veto();
            wxLogMessage(wxT("Vetoed suspend."));
        }
    }

    void OnSuspended(wxPowerEvent& WXUNUSED(event))
    {
        wxLogMessage(wxT("System is going to suspend."));
    }

    void OnSuspendCancel(wxPowerEvent& WXUNUSED(event))
    {
        wxLogMessage(wxT("System suspend was cancelled."));
    }

    void OnResume(wxPowerEvent& WXUNUSED(event))
    {
        wxLogMessage(wxT("System resumed from suspend."));
    }
#endif // wxHAS_POWER_EVENTS

    void UpdatePowerSettings(wxPowerType powerType, wxBatteryState batteryState)
    {
        wxString powerStr;
        switch ( m_powerType = powerType )
        {
            case wxPOWER_SOCKET:
                powerStr = wxT("wall");
                break;

            case wxPOWER_BATTERY:
                powerStr = wxT("battery");
                break;

            default:
                wxFAIL_MSG(wxT("unknown wxPowerType value"));
                // fall through

            case wxPOWER_UNKNOWN:
                powerStr = wxT("psychic");
                break;
        }

        wxString batteryStr;
        switch ( m_batteryState = batteryState )
        {
            case wxBATTERY_NORMAL_STATE:
                batteryStr = wxT("charged");
                break;

            case wxBATTERY_LOW_STATE:
                batteryStr = wxT("low");
                break;

            case wxBATTERY_CRITICAL_STATE:
                batteryStr = wxT("critical");
                break;

            case wxBATTERY_SHUTDOWN_STATE:
                batteryStr = wxT("empty");
                break;

            default:
                wxFAIL_MSG(wxT("unknown wxBatteryState value"));
                // fall through

            case wxBATTERY_UNKNOWN_STATE:
                batteryStr = wxT("unknown");
                break;
        }

        SetStatusText(wxString::Format(
                        wxT("System is on %s power, battery state is %s"),
                        powerStr.c_str(),
                        batteryStr.c_str()));
    }

    void OnStartTaskClicked( wxCommandEvent& WXUNUSED(event) )
    {
        wxLogMessage("Starting long running task "
                     "(screen should keep powered on while running)...");
        StartLongTask();
    }

    void OnStopTaskClicked(wxCommandEvent& WXUNUSED(event))
    {
        StopLongTask();
        wxLogMessage("Stopped long running task");
    }

    void OnTaskTimer(wxTimerEvent& WXUNUSED(event))
    {
        ++m_taskProgress;

        if ( m_taskProgress == 100 )
        {
            StopLongTask();
            wxLogMessage("Long running task finished");
        }
        else
        {
            wxLogMessage("Long running task at %d%%...", m_taskProgress);
        }
    }

    void StartLongTask()
    {
        m_taskProgress = 0;
        m_taskTimer.Start(12000);
        GetMenuBar()->Enable(wxID_NEW, false);
        GetMenuBar()->Enable(wxID_ABORT, true);

        m_powerResourceBlocker
            = new wxPowerResourceBlocker(wxPOWER_RESOURCE_SYSTEM);

        if ( !m_powerResourceBlocker->IsInEffect() )
        {
            wxLogMessage("Power resource could not be acquired, "
                         "user input is required to prevent system standby");
        }
    }

    void StopLongTask()
    {
        GetMenuBar()->Enable(wxID_NEW, true);
        GetMenuBar()->Enable(wxID_ABORT, false);
        m_taskTimer.Stop();

        wxDELETE(m_powerResourceBlocker);
    }

    wxPowerType m_powerType;
    wxBatteryState m_batteryState;

    wxLog *m_logOld;
    wxTimer m_taskTimer;
    wxPowerResourceBlocker *m_powerResourceBlocker;
    int m_taskProgress;

    wxDECLARE_EVENT_TABLE();
};

wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
    EVT_IDLE(MyFrame::OnIdle)

#ifdef wxHAS_POWER_EVENTS
    EVT_POWER_SUSPENDING(MyFrame::OnSuspending)
    EVT_POWER_SUSPENDED(MyFrame::OnSuspended)
    EVT_POWER_SUSPEND_CANCEL(MyFrame::OnSuspendCancel)
    EVT_POWER_RESUME(MyFrame::OnResume)
#endif // wxHAS_POWER_EVENTS
wxEND_EVENT_TABLE()

// ----------------------------------------------------------------------------
// main application class
// ----------------------------------------------------------------------------

class MyApp : public wxApp
{
public:
    virtual bool OnInit()
    {
        new MyFrame;

        return true;
    }
};

wxIMPLEMENT_APP(MyApp);


text:
import EventEmitter from 'event-emitter';
import Enum from '../Enum';

export default class TransportBase {
  constructor({ name, prefix, timeout = 90 * 1000 } = {}) {
    if (!name) {
      throw new Error(`${this.constructor.name}: "name" is required.`);
    }
    const prefixString = prefix ? `${prefix}-` : '';
    this._events = new Enum([
      'request',
      'response',
      'push',
      'timeout',
    ], `${prefixString}${name}`);

    this._timeout = timeout;
  }
  get events() {
    return this._events;
  }
}

EventEmitter(TransportBase.prototype);


text:
var expect = require('chai').expect;
var asArray = require('../');

describe('as-array', function() {
  it('should work', function() {
    expect(asArray('a')).to.eql(['a']);
    expect(asArray(['a'])).to.eql(['a']);
    expect(asArray(undefined)).to.eql([]);
    expect(asArray()).to.eql([]);
    expect(asArray(null)).to.eql([null]);
    expect(asArray(['a', 'b'])).to.eql(['a', 'b']);
  });
});


text:
This is a plugin for [Logstash](https://github.com/elastic/logstash).

## Documentation

Logstash provides infrastructure to automatically generate documentation for this plugin. We use the asciidoc format to write documentation so any comments in the source code will be first converted into asciidoc and then into html. All plugin documentation are placed under one [central location](http://www.elastic.co/guide/en/logstash/current/).

- For formatting code or config example, you can use the asciidoc `[source,ruby]` directive
- For more asciidoc formatting tips, see the excellent reference here https://github.com/elastic/docs#asciidoc-guide

## Why this plugin

When setting up logging stacks, we weren't able to use the [solr_http](https://rubygems.org/gems/logstash-output-solr_http) output plugin in logstash conf to talk to solr
On the other hand, we found SiLK 1.5 stack is shipping its own customized version of logstash, which is a java jar file.
Though the example provided with customized version of [SiLK logstash](https://docs.lucidworks.com/display/SiLK/Solr+Writer+for+Logstash+Initial+Setup) was able to pipe events to solr server, our needs were

1. We already had a logstash server running for a while and it had a great ecosystem of input, filter and output plugins
2. We would like to use this existing logstash server and NOT have to re-invent the wheel
3. We want multiple conf files to be loaded by logstash server, which the SiLK 1.5 solrWriter for logstash did not allow as per their documentation

Specifically, we want the same [logstash server](https://www.elastic.co/products/logstash) (that elastic search provides) to work with solr. It should be as simple as install a plugin, write the output conf and see the pipeline work, by viewing the events on the other side of solr

## Installing and using

1. git clone
2. JRUBY >=1.7 (We tried with MRI Ruby, however that did not go well. Guess because logstash is developed in JRUBY)
3. If you are on windows, use pik and switch to use jruby (pik use <identifier>). If on *nix, use rvm to switch to jruby
4. jgem build logstash-output-solr_post.gemspec (output should be a gem like logstash-output-solr_post-0.1.gem
5. Copy this gem to ~/logstash root folder
6. Install as output plugin to logstash using "./bin/plugin install logstash-output-solr_post-0.1.gem"
7. ./bin/plugin list to verify that the plugin installed successfully and registered as output plugin
8. See the next section on usage instructions

## How does this plugin do it

It is possible to do a simple http POST to solr end point and post documents. Hence, we wrote simple logic extending logstash output base class and POST the event to solr endpoint. Of course, since solr expects the http post payload to be in a certain format, we format the event and then directly do a POST. That is it!

## Working Example

### Solr
Version: 5.3.1
**Note:** We tried starting solr in schemaless mode (gettingstarted collection automatically created), however we did not have success posting events directly to http://localhost:8983/solr/update?commit=true&wt=json endpoint

### Logstash (2.0.0) conf
```
input {
  tcp {
    type => "eventlog"
    port => 5544
    codec=> "json"
    }
  }
output {
  solr_post{
    solr_url => "http://localhost:8983/solr/mycollection/update?commit=true&wt=json"
    }
  }
```
where 'mycollection' is the name of your collection. We require collection name in the url

### Windows nxlog (nxlog-ce-2.9.1347) conf
```
<Extension json>
  Module xm_json
</Extension>

<Extension xml>
  Module xm_xml
</Extension>

<Input in>
    Module im_msvistalog
  Exec $raw_event=to_json();
</Input>

<Output out>
  Module om_tcp
  Host 127.0.0.1
  Port 5544
</Output>

<Route r>
  Path in => out
</Route>
```

We have used the above conf and were able to use this plugin to pipe events through the pipeline. We were also able to view the events in Banana. Below is how it looked for us

![Banana Dashboard](https://github.com/machzqcq/logstash-output-solr_post/blob/master/images/banana_dashboard.JPG "Banana Dashboard")

## TODO

1. Use idle flush time, flush size & documents parameters (currently it is declared inside the code but not used)
2. Write rspec unit tests
3. Support for XML (depends on need for the community)
4. Register this plugin for logstash plugin binary
5. Miscellaneous

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>JcaCertStoreBuilder (Bouncy Castle Library 1.52 API Specification)</title>
<meta name="date" content="2015-03-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.52

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.cert.jcajce

Class JcaCertStoreBuilder

java.lang.Object

org.bouncycastle.cert.jcajce.JcaCertStoreBuilder

public class JcaCertStoreBuilder
extends java.lang.Object

Builder to create a CertStore from certificate and CRL stores.

Constructor Summary

Constructors

Constructor and Description

JcaCertStoreBuilder()

Method Summary

Methods

Modifier and Type
Method and Description

JcaCertStoreBuilder
addCertificate(X509CertificateHolder cert)

Add a single certificate.

JcaCertStoreBuilder
addCertificates(org.bouncycastle.util.Store certStore)

Add a store full of X509CertificateHolder objects.

JcaCertStoreBuilder
addCRL(X509CRLHolder crl)

Add a single CRL.

JcaCertStoreBuilder
addCRLs(org.bouncycastle.util.Store crlStore)

Add a store full of X509CRLHolder objects.

java.security.cert.CertStore
build()

Build the CertStore from the current inputs.

JcaCertStoreBuilder
setProvider(java.security.Provider provider)

JcaCertStoreBuilder
setProvider(java.lang.String providerName)

JcaCertStoreBuilder
setType(java.lang.String type)

Set the type of the CertStore generated.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

JcaCertStoreBuilder

public JcaCertStoreBuilder()

Method Detail

addCertificates

public JcaCertStoreBuilder addCertificates(org.bouncycastle.util.Store certStore)

Add a store full of X509CertificateHolder objects.

Parameters:

certStore - a store of X509CertificateHolder objects.

addCertificate

public JcaCertStoreBuilder addCertificate(X509CertificateHolder cert)

Add a single certificate.

Parameters:

cert - the X509 certificate holder containing the certificate.

addCRLs

public JcaCertStoreBuilder addCRLs(org.bouncycastle.util.Store crlStore)

Add a store full of X509CRLHolder objects.

Parameters:

crlStore - a store of X509CRLHolder objects.

addCRL

public JcaCertStoreBuilder addCRL(X509CRLHolder crl)

Add a single CRL.

Parameters:

crl - the X509 CRL holder containing the CRL.

setProvider

public JcaCertStoreBuilder setProvider(java.lang.String providerName)

setProvider

public JcaCertStoreBuilder setProvider(java.security.Provider provider)

setType

public JcaCertStoreBuilder setType(java.lang.String type)

Set the type of the CertStore generated. By default it is "Collection".

Parameters:

type - type of CertStore passed to CertStore.getInstance().

Returns:

the current builder.

build

public java.security.cert.CertStore build()
                                   throws java.security.GeneralSecurityException

Build the CertStore from the current inputs.

Returns:

a CertStore.

Throws:

java.security.GeneralSecurityException

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.52

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `C:\Users\Chrilieb\.cargo\registry\src\github.com-1ecc6299db9ec823\crossbeam-0.2.10\src\mem\epoch\atomic.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>atomic.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../../../main.css">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

use std::marker::PhantomData;
use std::mem;
use std::ptr;
use std::sync::atomic::{self, Ordering};

use super::{Owned, Shared, Guard};

/// Like `std::sync::atomic::AtomicPtr`.
///
/// Provides atomic access to a (nullable) pointer of type `T`, interfacing with
/// the `Owned` and `Shared` types.
#[derive(Debug)]
pub struct Atomic<T> {
    ptr: atomic::AtomicPtr<T>,
    _marker: PhantomData<*const ()>,
}

unsafe impl<T: Sync> Send for Atomic<T> {}
unsafe impl<T: Sync> Sync for Atomic<T> {}

fn opt_shared_into_raw<T>(val: Option<Shared<T>>) -> *mut T {
    val.map(|p| p.as_raw()).unwrap_or(ptr::null_mut())
}

fn opt_owned_as_raw<T>(val: &Option<Owned<T>>) -> *mut T {
    val.as_ref().map(Owned::as_raw).unwrap_or(ptr::null_mut())
}

fn opt_owned_into_raw<T>(val: Option<Owned<T>>) -> *mut T {
    let ptr = val.as_ref().map(Owned::as_raw).unwrap_or(ptr::null_mut());
    mem::forget(val);
    ptr
}

impl<T> Atomic<T> {
    /// Create a new, null atomic pointer.
    #[cfg(feature = "nightly")]
    pub const fn null() -> Atomic<T> {
        Atomic {
            ptr: atomic::AtomicPtr::new(0 as *mut _),
            _marker: PhantomData
        }
    }

    #[cfg(not(feature = "nightly"))]
    pub fn null() -> Atomic<T> {
        Atomic {
            ptr: atomic::AtomicPtr::new(0 as *mut _),
            _marker: PhantomData
        }
    }

    /// Create a new atomic pointer
    pub fn new(data: T) -> Atomic<T> {
        Atomic {
            ptr: atomic::AtomicPtr::new(Box::into_raw(Box::new(data))),
            _marker: PhantomData
        }
    }

    /// Do an atomic load with the given memory ordering.
    ///
    /// In order to perform the load, we must pass in a borrow of a
    /// `Guard`. This is a way of guaranteeing that the thread has pinned the
    /// epoch for the entire lifetime `'a`. In return, you get an optional
    /// `Shared` pointer back (`None` if the `Atomic` is currently null), with
    /// lifetime tied to the guard.
    ///
    /// # Panics
    ///
    /// Panics if `ord` is `Release` or `AcqRel`.
    pub fn load<'a>(&self, ord: Ordering, _: &'a Guard) -> Option<Shared<'a, T>> {
        unsafe { Shared::from_raw(self.ptr.load(ord)) }
    }

    /// Do an atomic store with the given memory ordering.
    ///
    /// Transfers ownership of the given `Owned` pointer, if any. Since no
    /// lifetime information is acquired, no `Guard` value is needed.
    ///
    /// # Panics
    ///
    /// Panics if `ord` is `Acquire` or `AcqRel`.
    pub fn store(&self, val: Option<Owned<T>>, ord: Ordering) {
        self.ptr.store(opt_owned_into_raw(val), ord)
    }

    /// Do an atomic store with the given memory ordering, immediately yielding
    /// a shared reference to the pointer that was stored.
    ///
    /// Transfers ownership of the given `Owned` pointer, yielding a `Shared`
    /// reference to it. Since the reference is valid only for the curent epoch,
    /// it's lifetime is tied to a `Guard` value.
    ///
    /// # Panics
    ///
    /// Panics if `ord` is `Acquire` or `AcqRel`.
    pub fn store_and_ref<'a>(&self, val: Owned<T>, ord: Ordering, _: &'a Guard)
                             -> Shared<'a, T>
    {
        unsafe {
            let shared = Shared::from_owned(val);
            self.store_shared(Some(shared), ord);
            shared
        }
    }

    /// Do an atomic store of a `Shared` pointer with the given memory ordering.
    ///
    /// This operation does not require a guard, because it does not yield any
    /// new information about the lifetime of a pointer.
    ///
    /// # Panics
    ///
    /// Panics if `ord` is `Acquire` or `AcqRel`.
    pub fn store_shared(&self, val: Option<Shared<T>>, ord: Ordering) {
        self.ptr.store(opt_shared_into_raw(val), ord)
    }

    /// Do a compare-and-set from a `Shared` to an `Owned` pointer with the
    /// given memory ordering.
    ///
    /// As with `store`, this operation does not require a guard; it produces no new
    /// lifetime information. The `Result` indicates whether the CAS succeeded; if
    /// not, ownership of the `new` pointer is returned to the caller.
    pub fn cas(&self, old: Option<Shared<T>>, new: Option<Owned<T>>, ord: Ordering)
               -> Result<(), Option<Owned<T>>>
    {
        if self.ptr.compare_and_swap(opt_shared_into_raw(old),
                                     opt_owned_as_raw(&new),
                                     ord) == opt_shared_into_raw(old)
        {
            mem::forget(new);
            Ok(())
        } else {
            Err(new)
        }
    }

    /// Do a compare-and-set from a `Shared` to an `Owned` pointer with the
    /// given memory ordering, immediatley acquiring a new `Shared` reference to
    /// the previously-owned pointer if successful.
    ///
    /// This operation is analogous to `store_and_ref`.
    pub fn cas_and_ref<'a>(&self, old: Option<Shared<T>>, new: Owned<T>,
                           ord: Ordering, _: &'a Guard)
                           -> Result<Shared<'a, T>, Owned<T>>
    {
        if self.ptr.compare_and_swap(opt_shared_into_raw(old), new.as_raw(), ord)
            == opt_shared_into_raw(old)
        {
            Ok(unsafe { Shared::from_owned(new) })
        } else {
            Err(new)
        }
    }

    /// Do a compare-and-set from a `Shared` to another `Shared` pointer with
    /// the given memory ordering.
    ///
    /// The boolean return value is `true` when the CAS is successful.
    pub fn cas_shared(&self, old: Option<Shared<T>>, new: Option<Shared<T>>, ord: Ordering)
                      -> bool
    {
        self.ptr.compare_and_swap(opt_shared_into_raw(old),
                                  opt_shared_into_raw(new),
                                  ord) == opt_shared_into_raw(old)
    }

    /// Do an atomic swap with an `Owned` pointer with the given memory ordering.
    pub fn swap<'a>(&self, new: Option<Owned<T>>, ord: Ordering, _: &'a Guard)
                    -> Option<Shared<'a, T>> {
        unsafe { Shared::from_raw(self.ptr.swap(opt_owned_into_raw(new), ord)) }
    }

    /// Do an atomic swap with a `Shared` pointer with the given memory ordering.
    pub fn swap_shared<'a>(&self, new: Option<Shared<T>>, ord: Ordering, _: &'a Guard)
                           -> Option<Shared<'a, T>> {
        unsafe { Shared::from_raw(self.ptr.swap(opt_shared_into_raw(new), ord)) }
    }
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
package org.jabref.logic.formatter.bibtexfields;

import java.util.Objects;

import org.jabref.logic.l10n.Localization;
import org.jabref.model.cleanup.Formatter;

public class RemoveBracesFormatter extends Formatter {

    @Override
    public String getName() {
        return Localization.lang("Remove enclosing braces");
    }

    @Override
    public String getKey() {
        return "remove_braces";
    }

    @Override
    public String format(String value) {
        Objects.requireNonNull(value);

        String formatted = value;
        while ((formatted.length() >= 2) && (formatted.charAt(0) == '{') && (formatted.charAt(formatted.length() - 1)
                == '}')) {
            String trimmed = formatted.substring(1, formatted.length() - 1);

            // It could be that the removed braces were not matching
            // For example, "{A} test {B}" results in "A} test {B"
            // In this case, trimmed has a closing } without an opening { before that
            if (hasNegativeBraceCount(trimmed)) {
                return formatted;
            } else {
                formatted = trimmed;
            }
        }
        return formatted;
    }

    @Override
    public String getDescription() {
        return Localization.lang("Removes braces encapsulating the complete field content.");
    }

    @Override
    public String getExampleInput() {
        return "{In CDMA}";
    }

    /**
     * Check if a string at any point has had more ending } braces than opening { ones.
     * Will e.g. return true for the string "DNA} blahblal {EPA"
     *
     * @param value The string to check.
     * @return true if at any index the brace count is negative.
     */
    private boolean hasNegativeBraceCount(String value) {
        int braceCount = 0;
        for (int index = 0; index < value.length(); index++) {
            char charAtIndex = value.charAt(index);
            if (charAtIndex == '{') {
                braceCount++;
            } else if (charAtIndex == '}') {
                braceCount--;
            }
            if (braceCount < 0) {
                return true;
            }
        }
        return false;
    }
}


text:
//
//  MAOfflineCity.h
//
//  Copyright (c) 2013年 AutoNavi. All rights reserved.
//

#if MA_INCLUDE_OFFLINE

#import <Foundation/Foundation.h>
#import "MAOfflineItem.h"

typedef enum{
    MAOfflineCityStatusNone      __attribute__((deprecated("use MAOfflineItemStatusNone instead")))         = MAOfflineItemStatusNone,      //!< 不存在
    MAOfflineCityStatusCached    __attribute__((deprecated("use MAOfflineItemStatusCached instead")))       = MAOfflineItemStatusCached,    //!< 缓存状态
    MAOfflineCityStatusInstalled __attribute__((deprecated("use MAOfflineItemStatusInstalled instead")))    = MAOfflineItemStatusInstalled, //!< 已安装
    MAOfflineCityStatusExpired   __attribute__((deprecated("use MAOfflineItemStatusExpired instead")))      = MAOfflineItemStatusExpired    //!< 已过期
}MAOfflineCityStatus;

@interface MAOfflineCity : MAOfflineItem

/**
*  城市编码
*/
@property (nonatomic, copy, readonly) NSString *cityCode;

/**
 *  城市名称
 */
@property (nonatomic, copy, readonly) NSString *cityName __attribute__ ((deprecated("use name instead")));

/**
 *  下载地址
 */
@property (nonatomic, copy, readonly) NSString *urlString __attribute__ ((deprecated("Not supported in future version")));

/**
 *  离线数据状态
 */
@property (nonatomic, assign, readonly) MAOfflineCityStatus status __attribute__ ((deprecated("use itemStatus instead")));

@end

#endif


text:
The driver's configuration is composed of options, organized in a hierarchical manner. Optionally,
it can define *profiles* that customize a set of options for a particular kind of request.

* the default implementation is based on the Typesafe Config framework:
  * the driver JAR comes with a [reference.conf] file that defines the defaults.
  * you can add an `application.conf` file in the classpath (or an absolute path, or an URL). It
    only needs to contain the options that you override.
  * hot reloading is supported out of the box.
* the config mechanism can be completely overridden by implementing a set of driver interfaces
  ([DriverConfig], [DriverExecutionProfile] and [DriverConfigLoader])

-----

### Concepts

#### Options

Essentially, an option is a path in the configuration with an expected type, for example
`basic.request.timeout`, representing a duration.

#### Execution profiles

Imagine an application that does both transactional and analytical requests. Transactional requests
are simpler and must return quickly, so they will typically use a short timeout, let's say 100
milliseconds; analytical requests are more complex and less frequent so a higher SLA is acceptable,
for example 5 seconds. In addition, maybe you want to use a different consistency level.

Instead of manually adjusting the options on every request, you can create execution profiles:

```
datastax-java-driver {
  profiles {
    oltp {
      basic.request.timeout = 100 milliseconds
      basic.request.consistency = ONE
    }
    olap {
      basic.request.timeout = 5 seconds
      basic.request.consistency = QUORUM
    }
}
```

Now each request only needs a profile name:

```java
SimpleStatement s =
  SimpleStatement.builder("SELECT name FROM user WHERE id = 1")
      .setExecutionProfileName("oltp")
      .build();
session.execute(s);
```

The configuration has an anonymous *default profile* that is always present. It can define an
arbitrary number of named profiles. They inherit from the default profile, so you only need to
override the options that have a different value.

### Default implementation: Typesafe Config

Out of the box, the driver uses [Typesafe Config].

It looks at the following locations, according to the [standard behavior][config standard behavior]
of that library:

* system properties
* `application.conf` (all resources on the classpath with this name)
* `application.json` (all resources on the classpath with this name)
* `application.properties` (all resources on the classpath with this name)
* `reference.conf` (all resources on the classpath with this name)

The driver ships with a [reference.conf] that defines sensible defaults for all the options. That
file is heavily documented, so refer to it for details about each option. It is included in the core
driver JAR, so it is in your application's classpath. If you need to customize something, add an
`application.conf` to the classpath. There are various ways to do it:

* place the file in a directory that is on your application or application server's classpath
  ([example for Apache Tomcat](https://stackoverflow.com/questions/1300780/adding-a-directory-to-tomcat-classpath));
* if you use Maven, place it in the `src/main/resources` directory.

Since `application.conf` inherits from `reference.conf`, you only need to redeclare what you
override:

```
# Sample application.conf: overrides one option and adds a profile
datastax-java-driver {
  advanced.protocol.version = V4
  profiles {
    slow {
      basic.request.timeout = 10 seconds
    }
  }
}
```

`.conf` files are in the *HOCON* format, an improved superset of JSON; refer to the
[HOCON spec][HOCON] for details.

By default, configuration files are reloaded regularly, and the driver will adjust to the new values
(on a "best effort" basis: some options, like protocol version and policy configurations, cannot be
changed at runtime and will be ignored). The reload interval is defined in the configuration:

```
# To disable periodic reloading, set this to 0.
datastax-java-driver.basic.config-reload-interval = 5 minutes
```

As mentioned previously, system properties can also be used to override individual options. This is
great for temporary changes, for example in your development environment:

```
# Increase heartbeat interval to limit the amount of debug logs:
java -Ddatastax-java-driver.advanced.heartbeat.interval="5 minutes" ...
```

For array options, provide each element separately by appending an index to the path:

```
-Ddatastax-java-driver.basic.contact-points.0="127.0.0.1:9042"
-Ddatastax-java-driver.basic.contact-points.1="127.0.0.2:9042"
```

We recommend reserving system properties for the early phases of the project; in production, having
all the configuration in one place will make it easier to manage and review.

As shown so far, all options live under a `datastax-java-driver` prefix. This can be changed, for
example if you need multiple driver instances in the same VM with different configurations. See the
[Advanced topics](#changing-the-config-prefix) section.

#### Alternate application config locations

If loading `application.conf` from the classpath doesn't work for you, other loader implementations
are available:

* [DriverConfigLoader.fromClasspath]: still load from the classpath, but use a different resource
  name. For example "config" will try to load `config.conf`, `config.json` or `config.properties`.
* [DriverConfigLoader.fromFile]: load from a file on the local filesystem.
* [DriverConfigLoader.fromUrl]: load from a URL.

To use any of those loaders, pass it to the session builder:

```java
File file = new File("/path/to/application.conf");
CqlSession session = CqlSession.builder()
    .withConfigLoader(DriverConfigLoader.fromFile(file))
    .build();
```

Apart from application-specific configuration, they work exactly like the default loader: they
fall back to the driver's built-in `reference.conf` for defaults, accept overrides via system
properties, and reload at the interval specified by the `basic.config-reload-interval` option.

#### Programmatic application config

Alternatively, you can use [DriverConfigLoader.programmaticBuilder] to specify configuration options
programmatically instead of loading them from a static resource:

```java
DriverConfigLoader loader =
    DriverConfigLoader.programmaticBuilder()
        .withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofSeconds(5))
        .startProfile("slow")
        .withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofSeconds(30))
        .endProfile()
        .build();
CqlSession session = CqlSession.builder().withConfigLoader(loader).build();
```

This is useful for frameworks and tools that already have their own configuration mechanism.

### The configuration API

You don't need the configuration API for everyday usage of the driver, but it can be useful if:

* you're writing custom policies or a custom config implementation;
* use dynamic profiles (see below);
* or simply want to read configuration options at runtime.

#### Basics

The driver's context exposes a [DriverConfig] instance:

```java
DriverConfig config = session.getContext().getConfig();
DriverExecutionProfile defaultProfile = config.getDefaultProfile();
DriverExecutionProfile olapProfile = config.getProfile("olap");

config.getProfiles().forEach((name, profile) -> ...);
```

[DriverExecutionProfile] has typed option getters:

```java
Duration requestTimeout = defaultProfile.getDuration(DefaultDriverOption.REQUEST_TIMEOUT);
int maxRequestsPerConnection = defaultProfile.getInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS);
```

#### Manual reloading

In addition to periodic reloading, you can trigger a reload programmatically. This returns a
`CompletionStage` that you can use for example to register a callback when the reload is complete:

```java
DriverConfigLoader loader = session.getContext().getConfigLoader();
if (loader.supportsReloading()) {
  CompletionStage<Boolean> reloaded = loader.reload();
  reloaded.whenComplete(
      (configChanged, error) -> {
        if (error != null) {
          // handle error
        } else if (configChanged) {
          // do something after the config change
        }
      });
}
```

Manual reloading is optional, this can be checked with `supportsReloading()`; the driver's built-in
loader supports it.

#### Derived profiles

Execution profiles are hard-coded in the configuration, and can't be changed at runtime (except
by modifying and reloading the files). What if you want to adjust an option for a single request,
without having a dedicated profile for it?

To allow this, you start from an existing profile in the configuration and build a *derived profile*
that overrides a subset of options:

```java
DriverExecutionProfile defaultProfile = session.getContext().getConfig().getDefaultProfile();
DriverExecutionProfile dynamicProfile =
  defaultProfile.withString(
      DefaultDriverOption.REQUEST_CONSISTENCY, DefaultConsistencyLevel.EACH_QUORUM.name());
SimpleStatement s =
    SimpleStatement.builder("SELECT name FROM user WHERE id = 1")
        .setExecutionProfile(dynamicProfile)
        .build();
session.execute(s);
```

A derived profile keeps a reference to its base profile, and reflects the change if the
configuration gets reloaded.

Do not overuse derived profiles, as they can have an impact on performance: each `withXxx` method
creates a new copy, and propagating the changes from the base profile also has an overhead. We
strongly suggest defining all your profiles ahead of time in the configuration file; at the very
least, try to cache derived profiles if you reuse them multiple times.

### Advanced topics

*Note: all the features described in this section use the driver's internal API, which is subject to
the restrictions explained in [API conventions]*.

#### Changing the config prefix

As mentioned earlier, all configuration options are looked up under the `datastax-java-driver`
prefix. This might be a problem if you have multiple instances of the driver executing in the same
VM, but with different configurations. What you want instead is separate option trees, like this:

```
# application.conf
session1 {
  basic.session-name = "session1"
  advanced.protocol-version = V4
  // etc.
}
session2 {
  basic.session-name = "session2"
  advanced.protocol-version = V3
  // etc.
}
```

To achieve that, first write a method that loads the configuration under your prefix, and uses the
driver's `reference.conf` as a fallback:

```java
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

private static Config loadConfig(String prefix) {
  // Make sure we see the changes when reloading:
  ConfigFactory.invalidateCaches();

  // Every config file in the classpath, without stripping the prefixes
  Config root = ConfigFactory.load();

  // The driver's built-in defaults, under the default prefix in reference.conf:
  Config reference = root.getConfig("datastax-java-driver");

  // Everything under your custom prefix in application.conf:
  Config application = root.getConfig(prefix);

  return application.withFallback(reference);
}
```

Next, create a `DriverConfigLoader`. This is the component that abstracts the configuration
implementation to the rest of the driver. Here we use the built-in class, but tell it to load the
Typesafe Config object with the previous method:

```java
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.internal.core.config.typesafe.DefaultDriverConfigLoader;

DriverConfigLoader session1ConfigLoader =
    new DefaultDriverConfigLoader(
        () -> loadConfig("session1"), DefaultDriverOption.values());
```

Finally, pass the config loader when building the driver:

```java
CqlSession session1 =
    CqlSession.builder()
        .withConfigLoader(session1ConfigLoader)
        .build();
```

#### Loading from a different source

If you don't want to use a config file, you can write custom code to create the Typesafe `Config`
object (refer to the [documentation][Typesafe Config] for more details).

Then reuse the examples from the previous section to merge it with the driver's reference file, and
pass it to the driver. Here's a contrived example that loads the configuration from a string:

```java
String configSource = "protocol.version = V3";
DriverConfigLoader loader =
    new DefaultDriverConfigLoader(
        () -> {
          ConfigFactory.invalidateCaches();
          Config reference = ConfigFactory.load().getConfig("datastax-java-driver");
          Config application = ConfigFactory.parseString(configSource);
          return application.withFallback(reference);
        },
        DefaultDriverOption.values());

CqlSession session = CqlSession.builder().withConfigLoader(loader).build();
```

#### Bypassing Typesafe Config

If Typesafe Config doesn't work for you, it is possible to get rid of it entirely.

Start by excluding Typesafe Config from the list of dependencies required by the driver; if you are
using Maven, this can be achieved as follows:

```xml
<dependencies>
    <dependency>
        <groupId>com.datastax.oss</groupId>
        <artifactId>java-driver-core</artifactId>
        <version>...</version>
        <exclusions>
            <exclusion>
                <groupId>com.typesafe</groupId>
                <artifactId>config</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

```
Next, you will need to provide your own implementations of [DriverConfig] and
[DriverExecutionProfile]. Then write a [DriverConfigLoader] and pass it to the session at
initialization, as shown in the previous sections. Study the built-in implementation (package
`com.datastax.oss.driver.internal.core.config.typesafe`) for reference.

Reloading is not mandatory: you can choose not to implement it, and the driver will simply keep
using the initial configuration.

Note that the option getters (`DriverExecutionProfile.getInt` and similar) are invoked very
frequently on the hot code path; if your implementation is slow, consider caching the results
between reloads.

#### Configuration change event

If you're writing your own policies, you might want them to be reactive to configuration changes.
You can register a callback to `ConfigChangeEvent`, which gets emitted any time a manual or periodic
reload detects changes since the last reload:

```java
import com.datastax.oss.driver.internal.core.context.InternalDriverContext;
import com.datastax.oss.driver.internal.core.config.ConfigChangeEvent;

InternalDriverContext context = (InternalDriverContext) session.getContext();

Object key =
    eventBus.register(
        ConfigChangeEvent.class, (e) -> {
          System.out.println("The configuration changed");
          // re-read the config option(s) you're interested in, and apply changes if needed
        });

// If your component has a shorter lifecycle than the driver, make sure to unregister when it closes
eventBus.unregister(key, ConfigChangeEvent.class);
```

For example, the driver uses this mechanism internally to resize connection pools if you change the
options in `advanced.connection.pool`.

The event is emitted by the config loader. If you write a custom loader, study the source of
`DefaultDriverConfigLoader` to reproduce the behavior.

#### Policies

The preferred way to instantiate policies (load balancing policy, retry policy, etc.) is via the
configuration:

```
datastax-java-driver {
  basic.load-balancing-policy.class = DefaultLoadBalancingPolicy
  advanced.reconnection-policy {
    class = ExponentialReconnectionPolicy
    base-delay = 1 second
    max-delay = 60 seconds
  }
}
```

When the driver encounters such a declaration, it will load the class and use reflection to invoke a
constructor with the following signature:

* for policies that can be overridden in a profile (load balancing policy, retry policy, speculative
  execution policy):

    ```java
    public DefaultLoadBalancingPolicy(DriverContext context, String profileName)
    ```

* for session-wide policies (all the others):

    ```java
    public ExponentialReconnectionPolicy(DriverContext context)
    ```

Where [DriverContext] is the object returned by `session.getContext()`, which allows the policy to
access other driver components (for example the configuration).

If you write custom policy implementations, you should follow that same pattern; it provides an
elegant way to switch policies without having to recompile the application (if your policy needs
custom options, see the next section). Study the built-in implementations for reference.

If for some reason you really can't use reflection, there is a way out; subclass
`DefaultDriverContext` and override the corresponding method:

```java
import com.datastax.oss.driver.internal.core.context.DefaultDriverContext;

public class MyDriverContext extends DefaultDriverContext {

  public MyDriverContext(DriverConfigLoader configLoader, List<TypeCodec<?>> typeCodecs) {
    super(configLoader, typeCodecs);
  }

  @Override
  protected ReconnectionPolicy buildReconnectionPolicy() {
    return myReconnectionPolicy;
  }
}
```

Then you'll need to pass an instance of this context to `DefaultSession.init`. You can either do so
directly, or subclass `SessionBuilder` and override the `buildContext` method.

#### Custom options

You can add your own options to the configuration. This is useful for custom components, or even as
a way to associate arbitrary key/value pairs with the session instance.

First, write an enum that implements [DriverOption]:

```java
public enum MyCustomOption implements DriverOption {

  ADMIN_NAME("admin.name"),
  ADMIN_EMAIL("admin.email"),
  AWESOMENESS_FACTOR("awesomeness-factor"),
  ;

  private final String path;

  MyCustomOption(String path) {
    this.path = path;
  }

  @Override
  public String getPath() {
    return path;
  }
}
```

You can now add the options to your configuration:

```
datastax-java-driver {
  admin {
    name = "Bob"
    email = "bob@example.com"
  }
  awesomeness-factor = 11
}
```

And access them from the code:

```java
DriverConfig config = session.getContext().getConfig();
config.getDefaultProfile().getString(MyCustomOption.ADMIN_EMAIL);
config.getDefaultProfile().getInt(MyCustomOption.AWESOMENESS_FACTOR);
```

[DriverConfig]:                           https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DriverConfig.html
[DriverExecutionProfile]:                 https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DriverExecutionProfile.html
[DriverContext]:                          https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/context/DriverContext.html
[DriverOption]:                           https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DriverOption.html
[DefaultDriverOption]:                    https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DefaultDriverOption.html
[DriverConfigLoader]:                     https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html
[DriverConfigLoader.fromClasspath]:       https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromClasspath-java.lang.String-
[DriverConfigLoader.fromFile]:            https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromFile-java.io.File-
[DriverConfigLoader.fromUrl]:             https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromUrl-java.net.URL-
[DriverConfigLoader.programmaticBuilder]: https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#programmaticBuilder--

[Typesafe Config]: https://github.com/typesafehub/config
[config standard behavior]: https://github.com/typesafehub/config#standard-behavior
[reference.conf]: reference/
[HOCON]: https://github.com/typesafehub/config/blob/master/HOCON.md
[API conventions]: ../../api_conventions


text:
package com.shipdream.lib.android.mvc.controller;

import com.shipdream.lib.android.mvc.controller.internal.NavigationControllerImpl;

import org.junit.Before;

public class BaseNavigationControllerTest extends BaseControllerTest{
    protected NavigationController navigationController;

    @Before
    public void setUp() throws Exception {
        super.setUp();
        navigationController = new NavigationControllerImpl();
        graph.inject(navigationController);
        navigationController.init();
    }
}


text: """Initializes the module."""


text:
package hr.unidu.oop.p05;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PrimjerInicijalizacijeKolekcije {
	@SuppressWarnings("serial")
	private List<String> l1 = new ArrayList<>(){ // anonimna unutarnja klasa tipa ArrayList<String>
        { // inicijalizator instance objekta
            add("prvi");
            add("drugi");
            add("treći");
            add("četvrti");
        }
    };
    // Inicijalizacija korištenjem metode asList() klase Arrays
    private List<String> l2 = Arrays.asList("prvi", "drugi" ,"treći", "četvrti");

	public static void main(String[] args) {
		PrimjerInicijalizacijeKolekcije p = new PrimjerInicijalizacijeKolekcije();
		for(String s: p.l1)
			System.out.println(s);
		for(String s: p.l2)
			System.out.println(s);
	}
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\Category */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'category_name') ?>

    <?= $form->field($model, 'description') ?>

    <?= $form->field($model, 'status') ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
var Characteristic = require("hap-nodejs").Characteristic;

function fahrenheitToCelsius(temperature) {
  return (temperature - 32) / 1.8
}

function celsiusToFahrenheit(temperature) {
  return (temperature * 1.8) + 32
}

module.exports = {
  "unit": {
    "characteristic" : Characteristic.TemperatureDisplayUnits,
    "readOnly": true,
    fromConverter: function(value) {
      if (value === "FAHRENHEIT") {
        return Characteristic.TemperatureDisplayUnits.FAHRENHEIT;
      } else {
        return Characteristic.TemperatureDisplayUnits.CELSIUS;
      }
    },
    toConverter: function(value) {
      return value;
    }
  },
  "current_state": {
    "characteristic" : Characteristic.CurrentHeatingCoolingState,
    "readOnly": true,
    fromConverter: function(value) {
      switch (value) {
        case "Heat":
          return Characteristic.CurrentHeatingCoolingState.HEAT;
        case "Cool":
          return Characteristic.CurrentHeatingCoolingState.COOL;
        default:
          return Characteristic.CurrentHeatingCoolingState.OFF;
      }
    },
    toConverter: function(value) {
      return value;
    }
  },
  "target_state": {
    "characteristic" : Characteristic.TargetHeatingCoolingState,
    fromConverter: function(value) {
      switch (value) {
        case "Heat":
          return Characteristic.TargetHeatingCoolingState.HEAT;
        case "Cool":
          return Characteristic.TargetHeatingCoolingState.COOL;
        case "Auto":
          return Characteristic.TargetHeatingCoolingState.AUTO;
        default:
          return Characteristic.TargetHeatingCoolingState.OFF;
      }
    },
    toConverter: function(value) {
      switch (value) {
        case Characteristic.TargetHeatingCoolingState.HEAT:
          return "Heat";
        case Characteristic.TargetHeatingCoolingState.COOL:
          return "Cool";
        case Characteristic.TargetHeatingCoolingState.AUTO:
          return "Auto";
        default:
          return "Off";
      }
    }
  },
  "current_temperature": {
    "characteristic" : Characteristic.CurrentTemperature,
    "readOnly": true,
    "props": {
      format: Characteristic.Formats.INT,
      unit: Characteristic.Units.CELSIUS,
      minStep: 0.5,
      minValue: 0,
      maxValue: 100
    },
    fromConverter: function(value) {
      return fahrenheitToCelsius(parseInt(value));
    },
    toConverter: function(value) {
      return Math.round(celsiusToFahrenheit(value));
    }
  },
  "heatpoint": {
    "characteristic" : Characteristic.HeatingThresholdTemperature,
    "props": {
      format: Characteristic.Formats.INT,
      unit: Characteristic.Units.CELSIUS,
      minStep: 0.5,
      minValue: 15,
      maxValue: 30
    },
    fromConverter: function(value) {
      return fahrenheitToCelsius(parseInt(value));
    },
    toConverter: function(value) {
      return Math.round(celsiusToFahrenheit(value));
    }
  },
  "coolpoint": {
    "characteristic" : Characteristic.CoolingThresholdTemperature,
    "props": {
      format: Characteristic.Formats.INT,
      unit: Characteristic.Units.CELSIUS,
      minStep: 0.5,
      minValue: 15,
      maxValue: 30
    },
    fromConverter: function(value) {
      return fahrenheitToCelsius(parseInt(value));
    },
    toConverter: function(value) {
      return Math.round(celsiusToFahrenheit(value));
    }
  },
  "target_temperature": {
    "characteristic" : Characteristic.TargetTemperature,
    "derived": true,
    "props": {
      format: Characteristic.Formats.INT,
      unit: Characteristic.Units.CELSIUS,
      minStep: 0.5,
      minValue: 15,
      maxValue: 30
    },
    fromConverter: function(value, result) {
      if (!result) {
        console.log('from converted undefined result')
        return;
      }
      var targetTemperature = null;
      var high = result["coolpoint"];
      var low = result["heatpoint"];
      var current = result["current_temperature"];
      switch (result.target_state) {
        case Characteristic.TargetHeatingCoolingState.HEAT:
          targetTemperature = low;
          break;
        case Characteristic.TargetHeatingCoolingState.COOL:
          targetTemperature = high;
          break;
        case Characteristic.TargetHeatingCoolingState.AUTO:
        case Characteristic.TargetHeatingCoolingState.OFF:
          if (current <= low) {
            targetTemperature = low;
          } else if (current >= high) {
            targetTemperature = high;
          } else {
            // set to nearest
            targetTemperature =  Math.abs(high - current) < Math.abs(current - low) ? high : low;
          }
          break;
      }
      if (!targetTemperature) {
        return;
      }
      return targetTemperature;
    },
    toConverter: function(value) {
      return Math.round(celsiusToFahrenheit(value));
    },
    getVariableIDForSet: function(value, result, variableIDs) {
      var targetTemperature = null;
      var high = result["coolpoint"];
      var low = result["heatpoint"];
      var current = result["current_temperature"];
      switch (result.target_state) {
        case Characteristic.TargetHeatingCoolingState.HEAT:
          return variableIDs["heatpoint"];
        case Characteristic.TargetHeatingCoolingState.COOL:
          return variableIDs["coolpoint"];
        case Characteristic.TargetHeatingCoolingState.AUTO:
        case Characteristic.TargetHeatingCoolingState.OFF:
          if (Math.abs(high - current) < Math.abs(current - low)) {
            return variableIDs["coolpoint"];
          } else {
            return variableIDs["heatpoint"];
          }
      }
    }
  }
};