text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="True" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="robots" content="index, follow" />

  <link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,400;0,700;1,400&family=Source+Sans+Pro:ital,wght@0,300;0,400;0,700;1,400&display=swap" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="https://ptyagicodecamp.github.io/theme/stylesheet/style.min.css">

    <link id="pygments-light-theme" rel="stylesheet" type="text/css"
          href="https://ptyagicodecamp.github.io/theme/pygments/monokai.min.css">

  <link rel="stylesheet" type="text/css" href="https://ptyagicodecamp.github.io/theme/font-awesome/css/fontawesome.css">
  <link rel="stylesheet" type="text/css" href="https://ptyagicodecamp.github.io/theme/font-awesome/css/brands.css">
  <link rel="stylesheet" type="text/css" href="https://ptyagicodecamp.github.io/theme/font-awesome/css/solid.css">

    <link href="https://ptyagicodecamp.github.io/static/custom.css" rel="stylesheet">

    <link href="https://ptyagicodecamp.github.io/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="tech&Life Atom">

    <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/images/favicon.ico" type="image/x-icon">

    <meta name="theme-color" content="#333333">

    <meta name="msapplication-navbutton-color" content="#333333">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <meta name="msapplication-TileColor" content="#333333">

<meta name="author" content="ptyagi" />
<meta name="description" content="Implementing switching from light to dark theme and vice versa using Provider plugin for dependency injection and state management." />
<meta name="keywords" content="Provider, Cross-platform, Flutter, Code-recipes, Android, Android Studio, iOS, development">

<meta property="og:site_name" content="tech&Life"/>
<meta property="og:title" content="Implement Flutter themes using Provider"/>
<meta property="og:description" content="Implementing switching from light to dark theme and vice versa using Provider plugin for dependency injection and state management."/>
<meta property="og:locale" content="en_US"/>
<meta property="og:url" content="https://ptyagicodecamp.github.io/implement-flutter-themes-using-provider.html"/>
<meta property="og:type" content="article"/>
<meta property="article:published_time" content="2019-09-12 00:00:00-04:00"/>
<meta property="article:modified_time" content=""/>
<meta property="article:author" content="https://ptyagicodecamp.github.io/author/ptyagi.html">
<meta property="article:section" content="Flutter"/>
<meta property="article:tag" content="Provider"/>
<meta property="article:tag" content="Cross-platform"/>
<meta property="article:tag" content="Flutter"/>
<meta property="article:tag" content="Code-recipes"/>
<meta property="article:tag" content="Android"/>
<meta property="article:tag" content="Android Studio"/>
<meta property="article:tag" content="iOS"/>
<meta property="article:tag" content="development"/>
<meta property="og:image" content="https://ptyagicodecamp.github.io/images/profile.jpg">

  <title>tech&Life – Implement Flutter themes using Provider</title>

        tech&Life

Explore | Life | Mobile | Software Engineering

              Support

              Codementor

      Home

      Archives
      Categories
      Tags

      Atom

Implement Flutter themes using Provider

      Posted on September 12, 2019 in Flutter

Checkout related articles:

Persisting theme using SharedPreferences (Android, iOS, and Web)

Persisting theme in LocalDatabase (Moor plugin)

Target Audience: Beginner

Recipe: Toggle Flutter themes from one type to another using Provider dependency injection and state management package.

Focus Widget: Provider plugin

Goal: Implementing themes using Provider plugin. Implement a simple UI with an image, text and a button to switch themes. Page's default theme is light. Clicking on "Switch Theme" button will apply dark theme to page, and vice versa.

Light Theme:

Dark Theme:

Checkout the companion video tutorial:

What is Provider

Provider is a plugin/package that provides dependency injection and state management solution for a Flutter App. It's built with robust and scalable Flutter widgets.

Step #1. pubspec.yaml

Add package dependency in pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter

  #Dependency for Provider plugin
  provider: ^3.1.0 #ChangeNotifier, Consumer, Providers

Step #2. Implement theme ChangeNotifier

I'll be using two themes: Light and Dark. Let's use enum to declare these two themes:

enum MyThemes { light, dark }

Now, I need a ChangeNotifier that'll notify my app about the change occurred in theme preference.

class ThemesNotifier with ChangeNotifier {}

Next comes defining ThemeData for light and dark themes:

static final List<ThemeData> themeData = [
  ThemeData(
      brightness: Brightness.light,
      primaryColor: Colors.blue,
      accentColor: Colors.lightBlueAccent),
  ThemeData(
      brightness: Brightness.dark,
      primaryColor: Colors.orange,
      accentColor: Colors.yellowAccent)
];

Let's initialize default MyThemes and ThemeData:

MyThemes _currentTheme = MyThemes.light;
ThemeData _currentThemeData = themeData[0];

Lastly, setters and getters to update and access MyThemes and ThemeData:

void switchTheme() => currentTheme == MyThemes.light
    ? currentTheme = MyThemes.dark
    : currentTheme = MyThemes.light;

set currentTheme(MyThemes theme) {
  if (theme != null) {
    _currentTheme = theme;
    _currentThemeData =
        currentTheme == MyThemes.light ? themeData[0] : themeData[1];

    //Notifies the theme change to app
    notifyListeners();
  }
}

get currentTheme => _currentTheme;
get currentThemeData => _currentThemeData;

Step #3. Notifying theme change to App

Sample App 'Themes Demo''s build(...) method uses theme attribute to assign ThemeData to app like below. Provider.of<ThemesNotifier>(context).currentThemeData is notified about a theme change happened in ThemesNotifier's switchTheme() method.

@override
Widget build(BuildContext context) {
  return MaterialApp(
      theme: Provider.of<ThemesNotifier>(context).currentThemeData,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Themes Demo"),
        ),
        body: body(),
      ));
}

Theme change is requested from Switch Theme button :

RaisedButton(
  child: Text("Switch Theme"),
  onPressed: () {
    Provider.of<ThemesNotifier>(context).switchTheme();
  },
),

That's all !

Running on Flutter Web

Note: Flutter Web project setup has been changed since Flutter 1.9 release.

Please follow the direction on setting up Flutter Web project here.

Source code repo:
Recipe source code is available here

References:

Provider Package

Flutter web

Open Issue about Flutter-Web merging Flutter

Happy cooking with Flutter :)

Liked the article ?
Couldn't find a topic of your interest ? Please leave comments or email me about topics you would like me to write !
BTW I love cupcakes and coffee both :)

Follow me at twitter

      Provider
      Cross-platform
      Flutter
      Code-recipes
      Android
      Android Studio
      iOS
      development

Like this article? Share it with your friends!

    Please enable JavaScript to view comments.

  © 2022  - This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License

Built with Pelican using Flex theme

    <svg width="80"
         height="80"
         viewBox="0 0 250 250"
         style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;"
         aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor"
              style="transform-origin: 130px 106px;"
              class="octo-arm">
        </path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor"
              class="octo-body">
        </path>
    </svg>


text:
FROM python:3.7
LABEL maintainer="marcus@punchcyber.com"

ENV USER stoq
ENV GROUP stoq
ENV STOQ_HOME /home/$USER/.stoq
ENV STOQ_TMP /tmp/stoq
ENV XORSEARCH_VER 1_11_3
ENV EXIFTOOL_VER 12.00

RUN groupadd -r $GROUP && \
    useradd -r -g $GROUP $USER && \
    install -d $STOQ_HOME -d $STOQ_HOME/plugins -o $USER -g $GROUP

RUN apt-get update && \
    apt-get install -y software-properties-common && \
    apt-add-repository -y non-free && \
    apt-get update && \
    apt-get -y install \
    automake \
    build-essential \
    libyaml-dev \
    git-core \
    p7zip-full \
    unace-nonfree \
    unzip \
    wget \
    curl \
    libfuzzy-dev \
    libc6-i386 \
    libssl-dev \
    swig \
    lib32ncurses6 && \
    apt-get clean -y && \
    rm -rf /var/lib/apt/lists/*

COPY . ${STOQ_TMP}

WORKDIR ${STOQ_TMP}

# Install stoQ and plugins
RUN pip install --no-cache-dir six asynctest && \
    python3 setup.py install && \
    git clone --depth 1 -b v3 https://github.com/PUNCH-Cyber/stoq-plugins-public ${STOQ_TMP}/stoq-plugins-public && \
    cd ${STOQ_TMP}/stoq-plugins-public && \
    for plugin in $(ls -d */); do stoq install $plugin; done

# Ensure the latest version of the IANA TLDs are in the appropriate place for the iocextract plugin
ADD https://data.iana.org/TLD/tlds-alpha-by-domain.txt $STOQ_HOME/plugins/iocextract/

RUN chmod 644 $STOQ_HOME/plugins/iocextract/tlds-alpha-by-domain.txt

# Install xorsearch
RUN wget -O XORSearch.zip "https://github.com/DidierStevens/FalsePositives/blob/master/XORSearch_V${XORSEARCH_VER}.zip?raw=true" && \
    unzip -qq XORSearch -d XORSearch && \
    gcc -o /usr/local/bin/xorsearch XORSearch/XORSearch.c

# Install exiftool
RUN wget -O exif.tgz "https://exiftool.org/Image-ExifTool-${EXIFTOOL_VER}.tar.gz" && \
    tar -xvf exif.tgz && \
    cd Image-ExifTool-${EXIFTOOL_VER} && \
    perl Makefile.PL && \
    make && \
    make test && \
    make install

# Install TRiD
RUN wget -O trid_linux_64.zip "http://mark0.net/download/trid_linux_64.zip" && \
    unzip -qq trid_linux_64 -d /usr/local/bin && \
    chmod +x /usr/local/bin/trid && \
    wget -O triddefs.zip "http://mark0.net/download/triddefs.zip" && \
    unzip -qq triddefs -d $STOQ_HOME/plugins/trid

# Clean up
RUN rm -rf $STOQ_TMP /tmp/* /var/tmp/*

WORKDIR /home/$USER
USER $USER
ENTRYPOINT ["stoq"]

redpajama_set_name: RedPajamaGithub


text:
import { bindable, bindingMode, customElement, inlineView } from "aurelia-framework";

@customElement("ui-slider")
@inlineView(`<template class="ui-slider" css.bind="{'--slider-pos': (value-min)/(max-min)}">

\${value}

\${min}
\${max}

  <input type="range" value.bind="value" step.bind="step" min.bind="min" max.bind="max" />

</template>`)
export class UISlider {
  @bindable({ defaultBindingMode: bindingMode.twoWay })
  public value: number = 0;
  @bindable()
  public min: number = 0;
  @bindable()
  public max: number = 100;
  @bindable()
  public step: number = 1;

  @bindable()
  public disabled: boolean = false;
}


text: While This is a sample paragraph that will be used for tests.


text:
import math

import pandas as pd

import linear_program
import opt_helpers as oh

def generate_containers(source_num, dest_num, sent=1):
    cont = {}
    for i in range(0,dest_num):
        cont[i] = []
        for j in range(0, source_num):
            cont[i].append(sent)
    return pd.DataFrame(cont)

def generate_distances(source_num, dest_num, dist=1):
    distances = {}
    for i in range(0,source_num + dest_num):
        distances[i] = []
        for j in range(0, source_num + dest_num):
            if i == j:
                distances[i].append(0)
            else:
                distances[i].append(dist)
    return pd.DataFrame(distances)

def run_exhaustive_n(n, scanner_cost=100):
    source = n
    dest = int(math.ceil(n / 4.0))
    containers = generate_containers(source, dest)
    distances = generate_distances(source, dest)
    sps = list(containers.index)
    return oh.exhaustive_optimization(distances, containers, sps,
                               scanner_cost)

def run_setup_n(n, sample=None, setup=linear_program.setup_variable):
    source = n
    dest = int(math.ceil(n / 4.0))
    containers = generate_containers(source, dest)
    distances = generate_distances(source, dest)
    sps = range(0, source)
    dp = range(source, source + dest)
    return setup(distances[sps][:-dest], distances[dp][:-dest], containers[0], port_capacities=[1000]*source,
                 dest_capacities=[1000]*dest, n=sample)

def run_gurobi_setup_n(n, sample=None):
    source = n
    dest = int(math.ceil(n / 4.0))
    containers = generate_containers(source, dest, sent=400)
    distances = generate_distances(source, dest)
    sps = range(0, source)
    dp = range(source, source + dest)
    cost_f = pd.DataFrame(distances[sps][:-dest].values)
    cost_d = pd.DataFrame(distances[dp][:-dest].values)
    return linear_program.setup_gurobi(cost_f,
                                       cost_d,
                                       containers[0],
                                       port_capacities=[10000]*source,
                                       dest_capacities=[10000]*dest,
                                       scanner_capacity=1000,
                                       n=sample)


text:
// 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
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

/// <summary>
/// <c>CubemapCaptureEdtior</c> Custom inspector GUI for <c>CubemapCapture.</c>.
/// </summary>
[CustomEditor(typeof(CubemapCapture))]
public class CubemapCaptureEditor : Editor
{
    public override void OnInspectorGUI() {
        base.OnInspectorGUI();

        CubemapCapture myCubemapCapture = (CubemapCapture)target;

        if(myCubemapCapture.Target && GUILayout.Button("Capture")) {
            myCubemapCapture.Capture();
        }
    }
}


text:
package com.alexaut.kroniax.game.scripts;

import com.alexaut.kroniax.game.Camera;
import com.alexaut.kroniax.game.GameController;
import com.alexaut.kroniax.game.level.Level;
import com.alexaut.kroniax.game.player.Player;

public abstract class TimedScript extends Script {
    public float mDuration;
    public float mElapsedTime;

    public TimedScript(float duration) {
        mDuration = duration;
        mElapsedTime = 0;
    }

    @Override
    public void update(float deltaTime, GameController gameController, Level level, Player player, Camera camera) {
        float interp = 0;
        if (mDuration == 0)
            interp = 1;
        else if (mElapsedTime + deltaTime <= mDuration) {
            interp = deltaTime / mDuration;
        } else {
            interp = (mDuration - mElapsedTime) / mDuration;
        }

        mElapsedTime += deltaTime;
        updateWithInterp(interp, gameController, level, player, camera);
        if (mElapsedTime >= mDuration)
            stop();
    }

    @Override
    public void reset() {
        super.reset();
        mElapsedTime = 0;
    }

    protected abstract void updateWithInterp(float interp, GameController gameController, Level level, Player player,
            Camera camera);

    public float getElapsedPercentage() {
        return (1.f - mElapsedTime / mDuration);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<DexEntry>
  <General>
    <Name>Unfezant</Name>
    <SpeciesName>Proud</SpeciesName>
    <GrowthGroup>MediumSlow</GrowthGroup>
    <EggGroup1>Flying</EggGroup1>
    <EggGroup2>Undiscovered</EggGroup2>
  </General>
</DexEntry>


text:
import logging
import os
from typing import TYPE_CHECKING, Optional

from azure.core.credentials import AccessToken
from .._internal import AsyncContextManager
from .._internal.decorators import log_get_token_async
from ... import CredentialUnavailableError
from ..._constants import EnvironmentVariables

if TYPE_CHECKING:
    from azure.core.credentials_async import AsyncTokenCredential

_LOGGER = logging.getLogger(__name__)

class ManagedIdentityCredential(AsyncContextManager):
    """Authenticates with an Azure managed identity in any hosting environment which supports managed identities.

    This credential defaults to using a system-assigned identity. To configure a user-assigned identity, use one of
    the keyword arguments. See `Azure Active Directory documentation
    <https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview>`_ for more
    information about configuring managed identity for applications.

    :keyword str client_id: a user-assigned identity's client ID or, when using Pod Identity, the client ID of an Azure
        AD app registration. This argument is supported in all hosting environments.
    :keyword identity_config: a mapping ``{parameter_name: value}`` specifying a user-assigned identity by its object
        or resource ID, for example ``{"object_id": "..."}``. Check the documentation for your hosting environment to
        learn what values it expects.
    :paramtype identity_config: Mapping[str, str]
    """

    def __init__(self, **kwargs) -> None:
        self._credential = None  # type: Optional[AsyncTokenCredential]

        if os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT):
            if os.environ.get(EnvironmentVariables.IDENTITY_HEADER):
                if os.environ.get(EnvironmentVariables.IDENTITY_SERVER_THUMBPRINT):
                    _LOGGER.info("%s will use Service Fabric managed identity", self.__class__.__name__)
                    from .service_fabric import ServiceFabricCredential

                    self._credential = ServiceFabricCredential(**kwargs)
                else:
                    _LOGGER.info("%s will use App Service managed identity", self.__class__.__name__)
                    from .app_service import AppServiceCredential

                    self._credential = AppServiceCredential(**kwargs)
            elif os.environ.get(EnvironmentVariables.IMDS_ENDPOINT):
                _LOGGER.info("%s will use Azure Arc managed identity", self.__class__.__name__)
                from .azure_arc import AzureArcCredential

                self._credential = AzureArcCredential(**kwargs)
            else:
                _LOGGER.info("%s will use Cloud Shell managed identity", self.__class__.__name__)
                from .cloud_shell import CloudShellCredential

                self._credential = CloudShellCredential(**kwargs)
        elif os.environ.get(EnvironmentVariables.MSI_ENDPOINT):
            if os.environ.get(EnvironmentVariables.MSI_SECRET):
                _LOGGER.info("%s will use Azure ML managed identity", self.__class__.__name__)
                from .azure_ml import AzureMLCredential

                self._credential = AzureMLCredential(**kwargs)
            else:
                _LOGGER.info("%s will use Cloud Shell managed identity", self.__class__.__name__)
                from .cloud_shell import CloudShellCredential

                self._credential = CloudShellCredential(**kwargs)
        elif all(os.environ.get(var) for var in EnvironmentVariables.TOKEN_EXCHANGE_VARS):
            _LOGGER.info("%s will use token exchange", self.__class__.__name__)
            from .token_exchange import TokenExchangeCredential

            client_id = kwargs.pop("client_id", None) or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID)
            if not client_id:
                raise ValueError('Configure the environment with a client ID or pass a value for "client_id" argument')

            self._credential = TokenExchangeCredential(
                tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID],
                client_id=client_id,
                token_file_path=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE],
                **kwargs
            )
        else:
            from .imds import ImdsCredential

            _LOGGER.info("%s will use IMDS", self.__class__.__name__)
            self._credential = ImdsCredential(**kwargs)

    async def __aenter__(self):
        if self._credential:
            await self._credential.__aenter__()
        return self

    async def close(self):
        """Close the credential's transport session."""
        if self._credential:
            await self._credential.__aexit__()

    @log_get_token_async
    async def get_token(self, *scopes: str, **kwargs) -> AccessToken:
        """Asynchronously request an access token for `scopes`.

        This method is called automatically by Azure SDK clients.

        :param str scopes: desired scope for the access token. This credential allows only one scope per request.
        :rtype: :class:`azure.core.credentials.AccessToken`
        :raises ~azure.identity.CredentialUnavailableError: managed identity isn't available in the hosting environment
        """
        if not self._credential:
            raise CredentialUnavailableError(
                message="No managed identity endpoint found. \n"
                        "The Target Azure platform could not be determined from environment variables. "
                        "Visit https://aka.ms/azsdk/python/identity/managedidentitycredential/troubleshoot to "
                        "troubleshoot this issue."
            )
        return await self._credential.get_token(*scopes, **kwargs)


text:
  <md-dialog aria-label="New Path" style="width:50%;" ng-cloak>
    <form name="editParam">
      <md-toolbar style="background-color:#3F1C3E;">

Parameter Options

      </md-toolbar>
      <md-dialog-content>

                  <md-input-container style="display:flex; flex-flow:column nowrap; flex-grow:2;">
                    Title
                    <input  type="text"
                            name="paramName"
                            ng-model="paramModalControl.tempParam.name"
                            required />

                        Name is required.

                  </md-input-container>
                  <md-input-container style="display:flex; flex-flow:column nowrap; flex-grow:2;">
                    Parameter Location
                    <md-select ng-model="paramModalControl.tempParam.inLocation">
                      <md-option ng-repeat="locationType in paramModalControl.locationTypes" value="{{locationType}}">
                        {{locationType}}
                      </md-option>
                    </md-select>
                  </md-input-container>

                    <md-input-container style="display:flex; flex-grow:2;">
                      Description
                      <input  type="text"
                              name="paramDescription"
                              ng-model="paramModalControl.tempParam.description">
                    </md-input-container>

                    <md-checkbox

                        ng-model="paramModalControl.tempParam.allowEmptyValue"
                        aria-label="Allow Empty Value">
                      Allow Empty Value
                    </md-checkbox>

                    <md-checkbox

                        ng-if="paramModalControl.tempParam.inLocation !== 'path'"
                        ng-model="paramModalControl.tempParam.required"
                        aria-label="required">
                      required
                    </md-checkbox>

                    <sg-dropdown sg-label="Format" ng-model="paramModalControl.tempParam.format" sg-choices="paramModalControl.paramOptions.format"></sg-dropdown>
                    <sg-dropdown sg-label="Type" ng-model="paramModalControl.tempParam.type" sg-choices="paramModalControl.paramOptions.type"></sg-dropdown>
                    <md-input-container>
                      Collection Format
                      <md-select ng-model="paramModalControl.tempParam.collectionFormat">
                        <md-option ng-repeat="colFormat in paramModalControl.paramOptions.collectionFormat" value="{{colFormat}}"
                        ng-if="(colFormat === 'multi' && (paramModalControl.tempParam.inLocation === 'query' || paramModalControl.tempParam.inLocation === 'formData')) || colFormat !== 'multi' ">
                          {{colFormat}}
                        </md-option>
                      </md-select>
                    </md-input-container>

Schema

                  <sg-schema-editor sg-schema-object="paramModalControl.tempParam.schema" sg-restrict-type-to-object="false"></sg-schema-editor>

      </md-dialog-content>
      <md-dialog-actions layout="row">

        <md-button ng-click="paramModalControl.deleteParameter()">
          delete
        </md-button>
        <md-button ng-click="paramModalControl.cancel()">
         Cancel
        </md-button>
        <md-button ng-click="paramModalControl.updateParameter(paramModalControl.tempParam)" style="margin-right:20px;">
          Update
        </md-button>
      </md-dialog-actions>
    </form>
  </md-dialog>


text:
[Jiacheng Park](http://jiachengpark.com)
=====================

personal blog:

Records normal daily life and sketches crazy future journey ***:p***


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class opencl_executor_LocalArg */

#ifndef _Included_opencl_executor_LocalArg
#define _Included_opencl_executor_LocalArg
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     opencl_executor_LocalArg
 * Method:    create
 * Signature: (J)Lopencl/executor/LocalArg;
 */
JNIEXPORT jobject JNICALL Java_opencl_executor_LocalArg_create
  (JNIEnv *, jclass, jlong);

#ifdef __cplusplus
}
#endif
#endif


text:
using std::string;

#include <systemc.h>
#include <tlm.h>
using namespace sc_core;
using namespace tlm;

#include "packet.h"

class consumer : public sc_module,
                 public tlm_blocking_put_if<packet>
{

  public:
  sc_export<tlm_blocking_put_if<packet> > in;
  tlm_analysis_port<packet> ap;

  consumer(sc_module_name nm) : in("in"), ap("ap")
  {
    in.bind(*this);
  }

  virtual void put(const packet &pkt) {
    char unsigned *data;
    int len;
    len = pkt.data.size();
    cout << sc_time_stamp() << " [CONSUMER/PKT/RECV] " << pkt << endl;
    wait(10,SC_NS);
    ap.write(pkt);
  }
};


text:
package main

import (
	"io"
	"net"
	"os"
)

var (
	cmdFDForward = &Command{
		Name:        "fd-forward",
		Summary:     "Proxy stdin and stdout to a unix domain socket",
		Usage:       "SOCKET",
		Description: `fleetctl utilizes fd-forward when --tunnel is used and --endpoint is a unix socket. This command is not intended to be called by users directly.`,
		Run:         runFDForward,
	}
)

func runFDForward(args []string) (exit int) {
	if len(args) != 1 {
		stderr("Provide a single argument")
		return 1
	}

	to := args[0]

	raddr, err := net.ResolveUnixAddr("unix", to)
	if err != nil {
		stderr("Unable to use %q as unix address: %v", to, err)
		return 1
	}

	sock, err := net.DialUnix("unix", nil, raddr)
	if err != nil {
		stderr("Failed dialing remote address: %v", err)
		return
	}
	defer sock.Close()

	errchan := make(chan error)
	go cp(os.Stdout, sock, errchan)
	go cp(sock, os.Stdin, errchan)

	select {
	case err := <-errchan:
		if err != nil {
			stderr("Encountered error during copy: %v", err)
			return 1
		}
	}

	return
}

func cp(to io.Writer, from io.Reader, errchan chan error) {
	_, err := io.Copy(to, from)
	errchan <- err
}


text:
Idiomatic vim text objects that work on the whole buffer.

### Text objects

* `a<Enter>` all lines in the buffer
* `i<Enter>` inside lines - all lines, except leading and trailing empty lines

### Examples

**a\<Enter>**

* `ya<Enter>` yank all lines in the buffer
* `da<Enter>` delete the whole buffer

**i\<Enter>**

* `vi<Enter>` visually select all non empty lines
* `yi<Enter>` yank all non empty lines

### Why?

Instead of using this plugin you can type `ggVG` + `operator` to get similar
behavior.

This plugin brings you:
* "vim idiomatic" mappings
* less keystrokes to type
* speed

### Installation

* Vundle

`Plugin 'bruno-/vim-all'`

* Pathogen

`git clone git://github.com/bruno-/vim-all.git ~/.vim/bundle/vim-all`

### Other

[vim-textobj-entire](https://github.com/kana/vim-textobj-entire) seems to do the
same thing, but has different mappings.

### License

[MIT](LICENSE.md)


text:
<?php

/**
 * Highlighting per-field settings
 *
 * @link http://wiki.apache.org/solr/HighlightingParameters
 *
 * @package Solarium
 * @subpackage Query
 */
class Solarium_Query_Select_Component_Highlighting_Field extends Solarium_Query_Select_Component
{
    /**
     * Value for fragmenter option gap
     */
    const FRAGMENTER_GAP = 'gap';

    /**
     * Value for fragmenter option regex
     */
    const FRAGMENTER_REGEX = 'regex';

    /**
     * Get name option
     *
     * @return string|null
     */
    public function getName()
    {
        return $this->getOption('name');
    }

    /**
     * Set name option
     *
     * @param string $name
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setName($name)
    {
        return $this->_setOption('name', $name);
    }

    /**
     * Set snippets option
     *
     * Maximum number of snippets per field
     *
     * @param int $maximum
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setSnippets($maximum)
    {
        return $this->_setOption('snippets', $maximum);
    }

    /**
     * Get snippets option
     *
     * @return int|null
     */
    public function getSnippets()
    {
        return $this->getOption('snippets');
    }

    /**
     * Set fragsize option
     *
     * The size, in characters, of fragments to consider for highlighting
     *
     * @param int $size
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setFragSize($size)
    {
        return $this->_setOption('fragsize', $size);
    }

    /**
     * Get fragsize option
     *
     * @return int|null
     */
    public function getFragSize()
    {
        return $this->getOption('fragsize');
    }

    /**
     * Set mergeContiguous option
     *
     * Collapse contiguous fragments into a single fragment
     *
     * @param boolean $merge
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setMergeContiguous($merge)
    {
        return $this->_setOption('mergecontiguous', $merge);
    }

    /**
     * Get mergeContiguous option
     *
     * @return boolean|null
     */
    public function getMergeContiguous()
    {
        return $this->getOption('mergecontiguous');
    }

    /**
     * Set alternatefield option
     *
     * @param string $field
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setAlternateField($field)
    {
        return $this->_setOption('alternatefield', $field);
    }

    /**
     * Get alternatefield option
     *
     * @return string|null
     */
    public function getAlternateField()
    {
        return $this->getOption('alternatefield');
    }

    /**
     * Set formatter option
     *
     * @param string $formatter
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setFormatter($formatter = 'simple')
    {
        return $this->_setOption('formatter', $formatter);
    }

    /**
     * Get formatter option
     *
     * @return string|null
     */
    public function getFormatter()
    {
        return $this->getOption('formatter');
    }

    /**
     * Set simple prefix option
     *
     * Solr option h1.simple.pre
     *
     * @param string $prefix
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setSimplePrefix($prefix)
    {
        return $this->_setOption('simpleprefix', $prefix);
    }

    /**
     * Get simple prefix option
     *
     * Solr option hl.simple.pre
     *
     * @return string|null
     */
    public function getSimplePrefix()
    {
        return $this->getOption('simpleprefix');
    }

    /**
     * Set simple postfix option
     *
     * Solr option h1.simple.post
     *
     * @param string $postfix
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setSimplePostfix($postfix)
    {
        return $this->_setOption('simplepostfix', $postfix);
    }

    /**
     * Get simple postfix option
     *
     * Solr option hl.simple.post
     *
     * @return string|null
     */
    public function getSimplePostfix()
    {
        return $this->getOption('simplepostfix');
    }

    /**
     * Set fragmenter option
     *
     * Use one of the constants as value.
     *
     * @param string $fragmenter
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setFragmenter($fragmenter)
    {
        return $this->_setOption('fragmenter', $fragmenter);
    }

    /**
     * Get fragmenter option
     *
     * @return string|null
     */
    public function getFragmenter()
    {
        return $this->getOption('fragmenter');
    }

    /**
     * Set useFastVectorHighlighter option
     *
     * @param boolean $use
     * @return Solarium_Query_Select_Component_Highlighting Provides fluent interface
     */
    public function setUseFastVectorHighlighter($use)
    {
        return $this->_setOption('usefastvectorhighlighter', $use);
    }

    /**
     * Get useFastVectorHighlighter option
     *
     * @return boolean|null
     */
    public function getUseFastVectorHighlighter()
    {
        return $this->getOption('usefastvectorhighlighter');
    }

}


text:
class YarmoukAIModule : public BWAPI::AIModule
{
public:
    YarmoukAIModule() :
        m_pAiEngine(nullptr),
        m_pGameModel(nullptr)
    {}

    // Virtual functions for callbacks, leave these as they are.
    virtual void onStart();
    virtual void onEnd(bool isWinner);
    virtual void onFrame();
    virtual void onSendText(std::string text);
    virtual void onReceiveText(BWAPI::Player player, std::string text) {}
    virtual void onPlayerLeft(BWAPI::Player player) {}
    virtual void onNukeDetect(BWAPI::Position target) {}
    virtual void onUnitDiscover(BWAPI::Unit unit) {}
    virtual void onUnitEvade(BWAPI::Unit unit) {}
    virtual void onUnitShow(BWAPI::Unit unit);
    virtual void onUnitHide(BWAPI::Unit unit);
    virtual void onUnitCreate(BWAPI::Unit unit);
    virtual void onUnitDestroy(BWAPI::Unit unit);
    virtual void onUnitMorph(BWAPI::Unit unit) {}
    virtual void onUnitRenegade(BWAPI::Unit unit);
    virtual void onSaveGame(std::string gameName) {}
    virtual void onUnitComplete(BWAPI::Unit unit) {}
    virtual IStrategizer::IRtsAiEngine* Engine() { return m_pAiEngine; }
    // Everything below this line is safe to modify.

protected:
    void OnEntityMessage(BWAPI::Unit unit, IStrategizer::MessageType msgType);
    void InitIStrategizer();
    void FinalizeIStrategizer();
    bool ExportGameIds(std::string p_exportPath);
    bool ExportAllIds(std::string p_exportPath);

    IStrategizer::IRtsAiEngine* m_pAiEngine;
    IStrategizer::IRtsGame* m_pGameModel;
};


text:
function disown123() {
    echo 123
}

disown<caret>

function disown123DefinedLater() {
    echo 123
}


text:
using namespace YoungNet;

int main()
{
	Mutex mtx;
	assert(mtx.IsLocked() == false);

	{
		MutexGuard lock(mtx);
		assert(mtx.IsLocked() == true);

	}
	assert(mtx.IsLocked() == false);

	printf("all tests passed\n");
	return 0;
}


text:
package org.zmpp.glk.events;

import org.zmpp.glk.*;
import org.zmpp.glk.windows.*;

public final class LineInputRequest extends WindowEventRequest {
    public int buffer;
    public int maxlen;
    public int initlen;
    public boolean useUnicode;
    private boolean runOnce;

    public LineInputRequest(int winId, int buffer, int maxlen,
                            int initlen, boolean useUnicode) {
        super(winId, GlkEventType.LineInput);
        this.buffer     = buffer;
        this.maxlen     = maxlen;
        this.initlen    = initlen;
        this.useUnicode = useUnicode;
    }

    @Override public boolean equals(Object that) {
        if (that instanceof LineInputRequest) {
            return winId == ((LineInputRequest) that).winId;
        } else {
            return false;
        }
    }

    public void prepareWindow(GlkScreenUI screenUI) {
        // Line input requests can interfere with timed input interrupts.
        // We need to save the mark until the program prints out input
        if (runOnce) {
            screenUI.requestPreviousLineInput(winId);
        } else {
            screenUI.requestLineInput(winId);
            runOnce = true;
        }
    }

    @Override public int hashCode() { return winId; }
}


text:
package org.apache.spark.sql

import org.apache.spark.sql.execution.command.management.CarbonLoadDataCommand
import org.apache.spark.sql.types._
import org.apache.spark.sql.util.CarbonException

import org.apache.carbondata.common.exceptions.sql.MalformedCarbonCommandException
import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.metadata.datatype.{DataTypes => CarbonType}
import org.apache.carbondata.spark.CarbonOption

class CarbonDataFrameWriter(sqlContext: SQLContext, val dataFrame: DataFrame) {

  private val LOGGER = LogServiceFactory.getLogService(this.getClass.getCanonicalName)

  def saveAsCarbonFile(parameters: Map[String, String] = Map()): Unit = {
    // create a new table using dataframe's schema and write its content into the table
    sqlContext.sparkSession.sql(
      makeCreateTableString(dataFrame.schema, new CarbonOption(parameters)))
    writeToCarbonFile(parameters)
  }

  def appendToCarbonFile(parameters: Map[String, String] = Map()): Unit = {
    writeToCarbonFile(parameters)
  }

  private def writeToCarbonFile(parameters: Map[String, String] = Map()): Unit = {
    val options = new CarbonOption(parameters)
    loadDataFrame(options)
  }
  /**
   * Loading DataFrame directly without saving DataFrame to CSV files.
   * @param options
   */
  private def loadDataFrame(options: CarbonOption): Unit = {
    val header = dataFrame.columns.mkString(",")
    CarbonLoadDataCommand(
      Some(CarbonEnv.getDatabaseName(options.dbName)(sqlContext.sparkSession)),
      options.tableName,
      null,
      Seq(),
      Map("fileheader" -> header) ++ options.toMap,
      isOverwriteTable = options.overwriteEnabled,
      null,
      Some(dataFrame)).run(sqlContext.sparkSession)
  }

  private def convertToCarbonType(sparkType: DataType): String = {
    sparkType match {
      case StringType => CarbonType.STRING.getName
      case IntegerType => CarbonType.INT.getName
      case ShortType => CarbonType.SHORT.getName
      case LongType => CarbonType.LONG.getName
      case FloatType => CarbonType.FLOAT.getName
      case DoubleType => CarbonType.DOUBLE.getName
      case TimestampType => CarbonType.TIMESTAMP.getName
      case DateType => CarbonType.DATE.getName
      case decimal: DecimalType => s"decimal(${decimal.precision}, ${decimal.scale})"
      case BooleanType => CarbonType.BOOLEAN.getName
      case other => CarbonException.analysisException(s"unsupported type: $other")
    }
  }

  private def makeCreateTableString(schema: StructType, options: CarbonOption): String = {
    val property = Map(
      "SORT_COLUMNS" -> options.sortColumns,
      "SORT_SCOPE" -> options.sortScope,
      "DICTIONARY_INCLUDE" -> options.dictionaryInclude,
      "DICTIONARY_EXCLUDE" -> options.dictionaryExclude,
      "LONG_STRING_COLUMNS" -> options.longStringColumns,
      "TABLE_BLOCKSIZE" -> options.tableBlockSize,
      "TABLE_BLOCKLET_SIZE" -> options.tableBlockletSize,
      "STREAMING" -> Option(options.isStreaming.toString)
    ).filter(_._2.isDefined)
      .map(property => s"'${property._1}' = '${property._2.get}'").mkString(",")

    val partition: Seq[String] = if (options.partitionColumns.isDefined) {
      if (options.partitionColumns.get.toSet.size != options.partitionColumns.get.length) {
        throw new MalformedCarbonCommandException(s"repeated partition column")
      }
      options.partitionColumns.get.map { column =>
        val field = schema.fields.find(_.name.equalsIgnoreCase(column))
        if (field.isEmpty) {
          throw new MalformedCarbonCommandException(s"invalid partition column: $column")
        }
        s"$column ${field.get.dataType.typeName}"
      }
    } else {
      Seq()
    }

    val schemaWithoutPartition = if (options.partitionColumns.isDefined) {
      val partitionCols = options.partitionColumns.get
      val fields = schema.filterNot {
        field => partitionCols.exists(_.equalsIgnoreCase(field.name))
      }
      StructType(fields)
    } else {
      schema
    }

    val carbonSchema = schemaWithoutPartition.map { field =>
      s"${ field.name } ${ convertToCarbonType(field.dataType) }"
    }

    val dbName = CarbonEnv.getDatabaseName(options.dbName)(sqlContext.sparkSession)

    s"""
       | CREATE TABLE IF NOT EXISTS $dbName.${options.tableName}
       | (${ carbonSchema.mkString(", ") })
       | ${ if (partition.nonEmpty) s"PARTITIONED BY (${partition.mkString(", ")})" else ""}
       | STORED BY 'carbondata'
       | ${ if (options.tablePath.nonEmpty) s"LOCATION '${options.tablePath.get}'" else ""}
       |  ${ if (property.nonEmpty) "TBLPROPERTIES (" + property + ")" else "" }
       |
     """.stripMargin
  }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.TestFramework;
using NUnit.Framework;
using Azure.Security.Attestation;
using System.Security.Cryptography;
using System.Text;
using System.Security.Cryptography.X509Certificates;

namespace Azure.Security.Attestation.Tests
{
    public class PolicyGetSetTests : RecordedTestBase<AttestationClientTestEnvironment>
    {
        public PolicyGetSetTests(bool isAsync) : base(isAsync)
        {
        }

        [RecordedTest]
        public async Task GetPolicyShared()
        {
            var adminclient = TestEnvironment.GetSharedAdministrationClient(this);

            string policy = await adminclient.GetPolicyAsync(AttestationType.SgxEnclave);

            Assert.IsTrue(policy.StartsWith("version"));
        }

        [RecordedTest]
        public async Task GetPolicyAad()
        {
            var adminclient = TestEnvironment.GetAadAdministrationClient(this);

            string policy = await adminclient.GetPolicyAsync(AttestationType.SgxEnclave);

            Assert.IsTrue(policy.StartsWith("version"));
        }

        [RecordedTest]
        public async Task GetPolicyIsolated()
        {
            var adminclient = TestEnvironment.GetIsolatedAdministrationClient(this);

            string policy = await adminclient.GetPolicyAsync(AttestationType.SgxEnclave);

            Assert.IsTrue(policy.StartsWith("version"));
        }

        public const string disallowDebugging = "version=1.0;" +
"authorizationrules {" +
"c:[type==\"$is-debuggable\"] && [value==true] => deny();" +
"=> permit();" +
"};"+
"issuancerules {" +
"    c:[type==\"$is-debuggable\"] => issue(type=\"NotDebuggable\", value=c.value);"+
"    c:[type==\"$is-debuggable\"] => issue(type=\"is-debuggable\", value=c.value);"+
"    c:[type==\"$sgx-mrsigner\"] => issue(type=\"sgx-mrsigner\", value=c.value);"+
"    c:[type==\"$sgx-mrenclave\"] => issue(type=\"sgx-mrenclave\", value=c.value);"+
"    c:[type==\"$product-id\"] => issue(type=\"product-id\", value=c.value);"+
"    c:[type==\"$svn\"] => issue(type=\"svn\", value=c.value);"+
"    c:[type==\"$tee\"] => issue(type=\"tee\", value=c.value);"+
"};";

        private async Task ResetAttestationPolicy(AttestationAdministrationClient adminClient, AttestationType attestationType, bool isSecuredToken, bool isIsolated)
        {
            X509Certificate2 x509Certificate = null;
            RSA rsaKey = null;
            if (isSecuredToken)
            {
                if (isIsolated)
                {
                    x509Certificate = TestEnvironment.PolicyManagementCertificate;

                    rsaKey = TestEnvironment.PolicyManagementKey;
                }
                else
                {
                    x509Certificate = TestEnvironment.PolicyCertificate0;

                    rsaKey = TestEnvironment.PolicySigningKey0;
                }
            }
            else
            {
            }

            var policySetResult = await adminClient.ResetPolicyAsync(AttestationType.OpenEnclave, (rsaKey != null ? new TokenSigningKey(rsaKey, x509Certificate) : null));
            Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
            Assert.AreEqual(PolicyModification.Removed, policySetResult.Value.PolicyResolution);
        }

        [RecordedTest]
        public async Task SetPolicyUnsecuredAad()
        {
            var adminclient = TestEnvironment.GetAadAdministrationClient(this);

            // Reset the current attestation policy to a known state. Necessary if there were previous runs that failed.
            await ResetAttestationPolicy(adminclient, AttestationType.OpenEnclave, false, false);

            string originalPolicy;
            {
                originalPolicy = await adminclient.GetPolicyAsync(AttestationType.OpenEnclave);
            }

            byte[] disallowDebuggingHash;
            {
                var policySetResult = await adminclient.SetPolicyAsync(AttestationType.OpenEnclave, disallowDebugging);

                // The SetPolicyAsync API will create an UnsecuredAttestationToken to transmit the policy.
                var shaHasher = SHA256Managed.Create();
                var policySetToken = new AttestationToken(new StoredAttestationPolicy { AttestationPolicy = disallowDebugging });

                disallowDebuggingHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.ToString()));

                Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
                Assert.AreEqual(PolicyModification.Updated, policySetResult.Value.PolicyResolution);
                CollectionAssert.AreEqual(disallowDebuggingHash, policySetResult.Value.PolicyTokenHash);
            }

            {
                string policyResult = await adminclient.GetPolicyAsync(AttestationType.OpenEnclave);

                Assert.AreEqual(disallowDebugging, policyResult);
            }
            {
                var policySetResult = await adminclient.ResetPolicyAsync(AttestationType.OpenEnclave);
                Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
                Assert.AreEqual(PolicyModification.Removed, policySetResult.Value.PolicyResolution);
            }

            {
                var policyResult = await adminclient.GetPolicyAsync(AttestationType.OpenEnclave);

                // And when we're done, policy should be reset to the original value.
                Assert.AreEqual(originalPolicy, policyResult.Value);
            }
        }

        [RecordedTest]
        public async Task SetPolicyUnsecuredIsolated()
        {
            var adminclient = TestEnvironment.GetIsolatedAdministrationClient(this);

            var error = Assert.ThrowsAsync<Azure.RequestFailedException>(async () => await adminclient.SetPolicyAsync(AttestationType.OpenEnclave, disallowDebugging));
            Assert.AreEqual(400, error.Status);
            await Task.Yield();
        }

        public async Task SetPolicySecured(AttestationAdministrationClient adminClient, bool isIsolated)
        {
            // Reset the current attestation policy to a known state. Necessary if there were previous runs that failed.
            await ResetAttestationPolicy(adminClient, AttestationType.OpenEnclave, true, isIsolated);

            string originalPolicy = await adminClient.GetPolicyAsync(AttestationType.OpenEnclave);

            X509Certificate2 x509Certificate;
            RSA rsaKey;

            if (isIsolated)
            {
                x509Certificate = TestEnvironment.PolicyManagementCertificate;

                rsaKey = TestEnvironment.PolicyManagementKey;
            }
            else
            {
                x509Certificate = TestEnvironment.PolicyCertificate0;

                rsaKey = TestEnvironment.PolicySigningKey0;
            }

            byte[] disallowDebuggingHash;
            {
                var policySetResult = await adminClient.SetPolicyAsync(AttestationType.OpenEnclave, disallowDebugging, new TokenSigningKey(rsaKey, x509Certificate));

                var shaHasher = SHA256Managed.Create();

                var policySetToken = new AttestationToken(
                    new StoredAttestationPolicy { AttestationPolicy = disallowDebugging }, new TokenSigningKey(rsaKey, x509Certificate));
                disallowDebuggingHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.ToString()));

                Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
                Assert.AreEqual(PolicyModification.Updated, policySetResult.Value.PolicyResolution);
                CollectionAssert.AreEqual(disallowDebuggingHash, policySetResult.Value.PolicyTokenHash);
                Assert.AreEqual(x509Certificate, policySetResult.Value.PolicySigner.SigningCertificates[0]);
            }

            {
                var policyResult = await adminClient.GetPolicyAsync(AttestationType.OpenEnclave);

                Assert.AreEqual(disallowDebugging, policyResult.Value);
            }
            {
                var policySetResult = await adminClient.ResetPolicyAsync(AttestationType.OpenEnclave, new TokenSigningKey(rsaKey, x509Certificate));
                Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
                Assert.AreEqual(PolicyModification.Removed, policySetResult.Value.PolicyResolution);
            }

            {
                var policyResult = await adminClient.GetPolicyAsync(AttestationType.OpenEnclave);

                // And when we're done, policy should be reset to the original value.
                Assert.AreEqual(originalPolicy, policyResult.Value);
            }
        }

        [RecordedTest]
        public async Task SetPolicySecuredAad()
        {
            var adminclient = TestEnvironment.GetAadAdministrationClient(this);

            await SetPolicySecured(adminclient, false);
        }

        [RecordedTest]
        public async Task SetPolicySecuredIsolated()
        {
            var adminclient = TestEnvironment.GetIsolatedAdministrationClient(this);

            await SetPolicySecured(adminclient, true);
        }

        [RecordedTest]
        public async Task GetPolicyManagementCertificatesIsolated()
        {
            var adminclient = TestEnvironment.GetIsolatedAdministrationClient(this);
            {
                var certificateResult = await adminclient.GetPolicyManagementCertificatesAsync();
                Assert.AreNotEqual(0, certificateResult.Value.GetPolicyCertificates().Count);

                bool foundInitialRoot = false;
                foreach (var cert in certificateResult.Value.GetPolicyCertificates())
                {
                    if (cert.Thumbprint == TestEnvironment.PolicyManagementCertificate.Thumbprint)
                    {
                        foundInitialRoot = true;
                        break;
                    }
                }
                Assert.IsTrue(foundInitialRoot);
            }
        }

        [RecordedTest]
        public async Task GetPolicyManagementCertificatesShared()
        {
            var adminclient = TestEnvironment.GetSharedAdministrationClient(this);
            {
                var certificateResult = await adminclient.GetPolicyManagementCertificatesAsync();
                Assert.AreEqual(0, certificateResult.Value.GetPolicyCertificates().Count);
            }
        }

        [RecordedTest]
        public async Task AddRemovePolicyManagementCertificate()
        {
            var adminClient = TestEnvironment.GetIsolatedAdministrationClient(this);

            var x509Certificate = TestEnvironment.PolicyManagementCertificate;
            var rsaKey = TestEnvironment.PolicyManagementKey;
            {
                var modificationResult = await adminClient.AddPolicyManagementCertificateAsync(
                    TestEnvironment.PolicyCertificate2,
                    new TokenSigningKey(rsaKey, x509Certificate));
                Assert.AreEqual(CertificateModification.IsPresent, modificationResult.Value.CertificateResolution);
                Assert.AreEqual(TestEnvironment.PolicyCertificate2.Thumbprint, modificationResult.Value.CertificateThumbprint);

                // Verify that the certificate we got back was in fact added.
                var certificateResult = await adminClient.GetPolicyManagementCertificatesAsync();
                bool foundAddedCertificate = false;
                foreach (var cert in certificateResult.Value.GetPolicyCertificates())
                {
                    if (cert.Thumbprint == TestEnvironment.PolicyCertificate2.Thumbprint)
                    {
                        foundAddedCertificate = true;
                        break;
                    }
                }
                Assert.IsTrue(foundAddedCertificate);
            }

            // Add the same certificate a second time, that should generate the same result.
            {
                var modificationResult = await adminClient.AddPolicyManagementCertificateAsync(
                    TestEnvironment.PolicyCertificate2,
                    new TokenSigningKey(rsaKey, x509Certificate));
                Assert.AreEqual(CertificateModification.IsPresent, modificationResult.Value.CertificateResolution);
                Assert.AreEqual(TestEnvironment.PolicyCertificate2.Thumbprint, modificationResult.Value.CertificateThumbprint);

                // Verify that the certificate we got back was in fact added.
                var certificateResult = await adminClient.GetPolicyManagementCertificatesAsync();
                bool foundAddedCertificate = false;
                foreach (var cert in certificateResult.Value.GetPolicyCertificates())
                {
                    if (cert.Thumbprint == TestEnvironment.PolicyCertificate2.Thumbprint)
                    {
                        foundAddedCertificate = true;
                        break;
                    }
                }
                Assert.IsTrue(foundAddedCertificate);
            }

            {
                var modificationResult = await adminClient.RemovePolicyManagementCertificateAsync(
                    TestEnvironment.PolicyCertificate2,
                    new TokenSigningKey(rsaKey, x509Certificate));
                Assert.AreEqual(CertificateModification.IsAbsent, modificationResult.Value.CertificateResolution);
                Assert.AreEqual(TestEnvironment.PolicyCertificate2.Thumbprint, modificationResult.Value.CertificateThumbprint);

                // Verify that the certificate we got back was in fact added.
                var certificateResult = await adminClient.GetPolicyManagementCertificatesAsync();
                bool foundAddedCertificate = false;
                foreach (var cert in certificateResult.Value.GetPolicyCertificates())
                {
                    if (cert.Thumbprint == TestEnvironment.PolicyCertificate2.Thumbprint)
                    {
                        foundAddedCertificate = true;
                        break;
                    }
                }
                Assert.IsFalse(foundAddedCertificate);
            }
        }
    }
}


text:
package eu.arima;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JavaWebTemplatesApplication {

	public static void main(String[] args) {
		SpringApplication.run(JavaWebTemplatesApplication.class, args);
	}
}


text:
<?php

//src/Catalog/VideoGalleryBundle/Entity/VideoCategory.php

namespace Catalog\VideoGalleryBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Table(name="video_gallery_category")
 * @ORM\Entity(repositoryClass="Catalog\VideoGalleryBundle\Entity\Repository\VideoCategoryRepository")
 * @ORM\HasLifecycleCallbacks
 * @UniqueEntity(fields="alias", message="Sorry, this alias is already in use.", groups={"videoCategory"})
 */
class VideoCategory {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    protected $sort;

    /**
     * @ORM\Column( type="string", length=100, unique=true)
     * @Assert\NotBlank(message="Please enter alias.", groups={"VideoCategory"})
     * @Assert\Regex(
     *       pattern="/^[a-z,A-Z,\_,\-,0-9]+$/",
     *       message="Alias can contain only letters, numbers and symbols '_' , '-'.",
     *       groups={"VideoCategory"}
     * )
     */
    protected $alias;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $title;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $description;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $is_active = true;

    /**
    * @ORM\OneToMany(
     *   targetEntity="Video",
     *   mappedBy="category",
     *   cascade={"persist", "remove"})
    */
    protected $videos;

    /**
     * @ORM\ManyToMany(targetEntity="Catalog\ContentBundle\Entity\Content", mappedBy="video_gallery")
     */
    protected $join_content;

    /**
     * @ORM\ManyToOne(
     *   targetEntity="Catalog\ProjectBundle\Entity\Project",
     *   inversedBy="videos")
     * @ORM\JoinColumn(
     *   name="project_id",
     *   referencedColumnName="id",
     *   onDelete="CASCADE")
     */
    protected $project;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->videos = new \Doctrine\Common\Collections\ArrayCollection();
        $this->join_content = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set sort
     *
     * @param integer $sort
     * @return VideoCategory
     */
    public function setSort($sort)
    {
        $this->sort = $sort;

        return $this;
    }

    /**
     * Get sort
     *
     * @return integer
     */
    public function getSort()
    {
        return $this->sort;
    }

    /**
     * Set alias
     *
     * @param string $alias
     * @return VideoCategory
     */
    public function setAlias($alias)
    {
        $this->alias = $alias;

        return $this;
    }

    /**
     * Get alias
     *
     * @return string
     */
    public function getAlias()
    {
        return $this->alias;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return VideoCategory
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return VideoCategory
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set is_active
     *
     * @param boolean $isActive
     * @return VideoCategory
     */
    public function setIsActive($isActive)
    {
        $this->is_active = $isActive;

        return $this;
    }

    /**
     * Get is_active
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->is_active;
    }

    /**
     * Add videos
     *
     * @param \Catalog\VideoGalleryBundle\Entity\Video $videos
     * @return VideoCategory
     */
    public function addVideo(\Catalog\VideoGalleryBundle\Entity\Video $videos)
    {
        if (!$this->videos->contains($videos)) {
            $this->videos[] = $videos;
            $videos->setCategory($this);
        }

        return $this;
    }

    /**
     * Remove videos
     *
     * @param \Catalog\VideoGalleryBundle\Entity\Video $videos
     */
    public function removeVideo(\Catalog\VideoGalleryBundle\Entity\Video $videos)
    {
        $this->videos->removeElement($videos);
    }

    /**
     * Get videos
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getVideos()
    {
        return $this->videos;
    }

    /**
     * Add join_content
     *
     * @param \Catalog\ContentBundle\Entity\Content $joinContent
     * @return VideoCategory
     */
    public function addJoinContent(\Catalog\ContentBundle\Entity\Content $joinContent)
    {
        $this->join_content[] = $joinContent;

        return $this;
    }

    /**
     * Remove join_content
     *
     * @param \Catalog\ContentBundle\Entity\Content $joinContent
     */
    public function removeJoinContent(\Catalog\ContentBundle\Entity\Content $joinContent)
    {
        $this->join_content->removeElement($joinContent);
    }

    /**
     * Get join_content
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getJoinContent()
    {
        return $this->join_content;
    }

    public function __toString() {
        return $this->title;
    }

    /**
     * Set project
     *
     * @param \Catalog\ProjectBundle\Entity\Project $project
     * @return VideoCategory
     */
    public function setProject(\Catalog\ProjectBundle\Entity\Project $project = null)
    {
        $this->project = $project;

        return $this;
    }

    /**
     * Get project
     *
     * @return \Catalog\ProjectBundle\Entity\Project
     */
    public function getProject()
    {
        return $this->project;
    }
}


text:
/**
 */

package org.apache.harmony.test.func.api.java.awt.Component;

import java.awt.Component;
import java.awt.ComponentOrientation;
import java.util.Locale;

import org.apache.harmony.test.func.api.java.awt.share.SimpleComponent;
import org.apache.harmony.share.Result;

public class ComponentOrientationTest extends org.apache.harmony.share.Test {

    private interface ComponentOrientationSetter {
        void set(Component c, ComponentOrientation co);
    }

    private class Set implements ComponentOrientationSetter {
        public void set(Component c, ComponentOrientation co) {
            c.setComponentOrientation(co);
        }
    }

    private class Apply implements ComponentOrientationSetter {
        public void set(Component c, ComponentOrientation co) {
            c.applyComponentOrientation(co);
        }
    }

    public int test(ComponentOrientationSetter set) {
        Component component = new SimpleComponent();
        ComponentOrientation cn = ComponentOrientation
                .getOrientation(Locale.JAPAN);
        set.set(component, cn);

        ComponentOrientation cs = component.getComponentOrientation();
        if (!cs.equals(cn)) {
            return fail("ComponentOrientation was not applied properly");
        }
        component.setLocale(Locale.UK);
        ComponentOrientation cu = component.getComponentOrientation();
        if (!(cu.isHorizontal() && cu.isLeftToRight())) {
            return fail("setLocale(Locale) hasn't caused "
                    + "ComponentOrientation to change");
        }
        return pass();
    }

    public static void main(String[] args) {
        ComponentOrientationTest test = new ComponentOrientationTest();
        System.exit(test.test());
    }

    public int test() {
        if (Result.FAIL != test(new Set())) {
            return test(new Apply());
        } else {
            return Result.FAIL;
        }
    }
}


text:
package org.elasticsearch.transport.nio;

import org.apache.logging.log4j.Logger;
import org.elasticsearch.nio.SocketChannelContext;
import org.elasticsearch.nio.SocketEventHandler;

import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.WeakHashMap;

public class TestingSocketEventHandler extends SocketEventHandler {

    public TestingSocketEventHandler(Logger logger) {
        super(logger);
    }

    private Set<SocketChannelContext> hasConnectedMap = Collections.newSetFromMap(new WeakHashMap<>());

    public void handleConnect(SocketChannelContext context) throws IOException {
        assert hasConnectedMap.contains(context) == false : "handleConnect should only be called is a channel is not yet connected";
        super.handleConnect(context);
        if (context.isConnectComplete()) {
            hasConnectedMap.add(context);
        }
    }

    private Set<SocketChannelContext> hasConnectExceptionMap = Collections.newSetFromMap(new WeakHashMap<>());

    public void connectException(SocketChannelContext context, Exception e) {
        assert hasConnectExceptionMap.contains(context) == false : "connectException should only called at maximum once per channel";
        hasConnectExceptionMap.add(context);
        super.connectException(context, e);
    }
}


text:
Concepts

		This framework provides a standardized way to implement and publish dashboards to the Pentaho BI Platform.&nbsp
		The main goal of this framework is to give the user an  easy and friendly way to build dashboards..

How can this be achieved?

No need to create additional JSP pages to deliver new dashboards.

The user has no need to make jsp pages or even have the knowledge to deal with that kind of technology.

Easy to design

It's all plain html, css and javascript

No need to create pentaho Action Sequences.

On most cases, the components are configured using a friendly syntax.

The dashboard objects can be easy reused.

The behaviors of dashboard objects (components) are related to their parameters values, and so
			the user may use the same object on an different dashboard, modifying only the values
			of one or two parameters.

Auto refresh and interaction between dashboard objects.

The user doesn't need to concern about interaction between components. The only thing
			the user must specify is what variable is bound to the object.

The ability to auto generate a navigation bar that picks up new dashboards.

A new dashboard was added? No need do modify the menu, the navigation bar will
			deal and present the new one.

New form objects, timeplot charts, tooltips, openstreet maps integration, etc, that makes the dashboard richer.

What is need to get all this new stuff to work? Just add the desired component.

Build your one dashboard component library.

When a particular component with a specific behavior is being used in all your projects,

			just add it to your javascript library for later use.

Beyond this, the are other technical advantages that this framework brings to pentaho dashboard:

Enforces security via Pentaho's security model.

Separation of the html design and component definition.

Portlet integration.


text:
struct CImageBMPHeader;

class CImageBMP : public CImageFmt {
 public:
  static CImageBMP *getInstance() {
    static CImageBMP *instance;

    if (! instance)
      instance = new CImageBMP;

    return instance;
  }

  bool read(CFile *file, CImagePtr &image);

  bool readHeader(CFile *file, CImagePtr &image);

  bool write(CFile *file, CImagePtr image);

 private:
  CImageBMP() :
   CImageFmt(CFILE_TYPE_IMAGE_BMP) {
  }

 ~CImageBMP() { }

  CImageBMP(const CImageBMP &bmp);

  CImageBMP &operator=(const CImageBMP &bmp);

 private:
  bool readHeader(CFile *file, CImageBMPHeader *header);

  void readColors(CFile *file, CImageBMPHeader *header, CRGBA **colors);

  bool readData(CFile *file, CImagePtr &image, CImageBMPHeader *header, uint **data);

  void readCmp0Data8(CFile *file, int width, int height, uint **data, int *num_data);
  void readCmp1Data8(CFile *file, int width, int height, uint **data, int *num_data);

  void readInteger(uchar *, int *);
  void readShort(uchar *, int *);

  void writeInteger(CFile *file, int data);
  void writeShort(CFile *file, int data);
  void writeByte(CFile *file, int data);
};

#endif


text:
shared_examples_for 'access granted' do
  it 'should allow read' do
    ability.should be_able_to(:read, resource, token) if token
    ability.should be_able_to(:read, resource) unless token
  end

  it 'should allow create' do
    ability.should be_able_to(:create, resource, token) if token
    ability.should be_able_to(:create, resource) unless token
  end

  it 'should allow update' do
    ability.should be_able_to(:update, resource, token) if token
    ability.should be_able_to(:update, resource) unless token
  end
end

shared_examples_for 'access denied' do
  it 'should not allow read' do
    ability.should_not be_able_to(:read, resource)
  end

  it 'should not allow create' do
    ability.should_not be_able_to(:create, resource)
  end

  it 'should not allow update' do
    ability.should_not be_able_to(:update, resource)
  end
end

shared_examples_for 'index allowed' do
  it 'should allow index' do
    ability.should be_able_to(:index, resource)
  end
end

shared_examples_for 'no index allowed' do
  it 'should not allow index' do
    ability.should_not be_able_to(:index, resource)
  end
end

shared_examples_for 'create only' do
  it 'should allow create' do
    ability.should be_able_to(:create, resource)
  end

  it 'should not allow read' do
    ability.should_not be_able_to(:read, resource)
  end

  it 'should not allow update' do
    ability.should_not be_able_to(:update, resource)
  end

  it 'should not allow index' do
    ability.should_not be_able_to(:index, resource)
  end
end

shared_examples_for 'read only' do
  it 'should not allow create' do
    ability.should_not be_able_to(:create, resource)
  end

  it 'should not allow update' do
    ability.should_not be_able_to(:update, resource)
  end

  it 'should allow index' do
    ability.should be_able_to(:index, resource)
  end
end


text:
// Copyright 2018, 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.

using System.Collections.Generic;
using Xunit;

namespace Google.Cloud.Firestore.Tests
{
    internal static class ComparisonTester
    {
        internal static void AssertComparison<T>(T smaller, T larger, IComparer<T> comparer = null)
        {
            comparer = comparer ?? Comparer<T>.Default;
            Assert.True(comparer.Compare(smaller, larger) < 0,
                $"Compare({smaller}, {larger}) should be < 0");
            Assert.True(comparer.Compare(larger, smaller) > 0,
                $"Compare({larger}, {smaller}) should be > 0.");
            Assert.Equal(0, comparer.Compare(smaller, smaller));
            Assert.Equal(0, comparer.Compare(larger, larger));
        }
    }
}


text:
import datetime
import os
import psycopg2
import sys

con = None
f = None

try:
    ################   CHANGE THESE PARAMETERS ONLY   ################
    con = con = psycopg2.connect(database='switch', host='localhost', port='5432', user='deepakc_super', password='myPassword')
    completeFilePath = "/Volumes/Data/DB_Code/study_dates/study_dates.txt"

    ################   CHANGE THESE PARAMETERS ONLY   ################

    cur = con.cursor()

    cur.execute("""DROP TABLE IF EXISTS study_date""")

    # note: study_date is an integer identifying a particular date in the study; 'date' is a date value corresponding to a specific historical date
    # also note: in this case, 'date' is meant to refer to a date in the local timezone
    query = """CREATE TABLE "study_date"(period smallint, study_date int, month_of_year smallint, date date, hours_in_sample smallint)"""
    cur.execute(query)

    # note: eventually the date sampling logic should be moved into this script (possibly using some minimal parameters set externally by the user)
    # but for now we import a pre-written list of date samples
    f = open(completeFilePath, 'r')
    query = """COPY "study_date"(period,study_date,month_of_year,date,hours_in_sample) FROM '%s' WITH DELIMITER AS ',' NULL '' """ %completeFilePath
    cur.copy_expert(query, f)
    if f:
        f.close()

    # in future, this should include a sequence number that increments for all the different sample dates that occur in the same month and same period.
    # for now we just use 1
    query = """UPDATE "study_date" SET study_date = (period * 100 + month_of_year) * 100 + 1 """
    cur.execute(query)
    con.commit()

except psycopg2.DatabaseError, e:
    if con:
        con.rollback()
    print 'Error %s' % e
    sys.exit(1)

except IOError, e:
    if con:
        con.rollback()
    print 'Error %s' % e
    sys.exit(1)

finally:
    if con:
        con.close()


text:
package yuown.spring.derby.security;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import yuown.spring.derby.model.UserModel;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class YuownTokenHandler {

	private static final String ALGORITHM = "AES";

	private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

	private Key secretKey;

	public YuownTokenHandler(byte[] secret) {
		secretKey = new SecretKeySpec(secret, ALGORITHM);
	}

	public String createTokenForUser(UserModel user) {
		String encryptedToken = null;
		try {
			byte[] userBytes = toJSON(user);
			byte[] hash = doCrypto(Cipher.ENCRYPT_MODE, userBytes);
			encryptedToken = new String(toBase64(hash));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return encryptedToken;
	}

	public UserModel parseUserFromToken(String token) {
		try {
			byte[] input = fromBase64(token);
			byte[] jsonBytes = doCrypto(Cipher.DECRYPT_MODE, input);
			final UserModel user = fromJSON(jsonBytes);
			if (new Date().getTime() < user.getExpires()) {
				return user;
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	private byte[] doCrypto(int mode, byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		Cipher cipher = Cipher.getInstance(TRANSFORMATION);
		cipher.init(mode, secretKey);
		return cipher.doFinal(input);
	}

	private UserModel fromJSON(final byte[] userBytes) {
		try {
			return new ObjectMapper().readValue(new ByteArrayInputStream(userBytes), UserModel.class);
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

	private byte[] toJSON(UserModel user) {
		try {
			return new ObjectMapper().writeValueAsBytes(user);
		} catch (JsonProcessingException e) {
			throw new IllegalStateException(e);
		}
	}

	private byte[] fromBase64(String content) {
		return DatatypeConverter.parseBase64Binary(content);
	}

	private String toBase64(byte[] content) {
		return DatatypeConverter.printBase64Binary(content);
	}
}


text:
<?php

class Migration_add_page_menu_order extends Migration {

	public function up() {
		$table = Base::table('pages');

		if( ! $this->has_table_column($table, 'menu_order')) {
			$sql = 'ALTER TABLE `' . $table . '` ADD `menu_order` int(4) NOT NULL';
			DB::ask($sql);
		}
	}

	public function down() {}

}


text:
/**
 *
 */
var httpUtil = require('http_util'),
    log = require('log'),
    util = require('util');
module.exports = {
    testGetHeader: function(test){
      var headers = {
          "content-type" : "text/html",
          "Check-Something": "test"
      }
      test.assertEquals(httpUtil.getHeader(headers, "Content-Type"),"text/html");
      test.assertEquals(httpUtil.getHeader(headers, "content-type"),"text/html");
      test.assertEquals(httpUtil.getHeader(headers, "check-something"),"test");
      test.assertEquals(httpUtil.getHeader(headers, "none",undefined));
      test.done();
    },
    testParseUrlEncoded: function(test){
      var data = "asdf=wer&sdfd=wer&wer=vsed";
      test.assertEquals(httpUtil.parseUrlEncoded(data),{"asdf":"wer","sdfd":"wer","wer":"vsed"});
      test.done();
    },
    testParseUrl: function(test){
      var urls =
        [
         "http://localhost:8080/path1?query=something&other=check#hash1/hash2?other=test",
         "localhost:8080/path1?query=something&other=check#hash1/hash2?other=test",
         "http://localhost/path1?query=something&other=check#hash1/hash2?other=test",
         "/path1?query=something&other=check#hash1/hash2?other=test",
         "localhost/path1/path2",
        ]
      var uris =
        [
          {"protocol":"http","host":"localhost:8080","hostname":"localhost","port":"8080","path":"/path1","query":"query=something&other=check","params":{"query":"something","other":"check"},"hash":"hash1/hash2?other=test"},
          {"host":"localhost:8080","hostname":"localhost","port":"8080","path":"/path1","query":"query=something&other=check","params":{"query":"something","other":"check"},"hash":"hash1/hash2?other=test"},
          {"protocol":"http","host":"localhost","hostname":"localhost","port":"","path":"/path1","query":"query=something&other=check","params":{"query":"something","other":"check"},"hash":"hash1/hash2?other=test"},
          {"path":"/path1","query":"query=something&other=check","params":{"query":"something","other":"check"},"hash":"hash1/hash2?other=test"},
          {"host":"localhost","hostname":"localhost","port":"","path":"/path1/path2"}
        ]
      var sequence = util.sequence(urls.length);
      test.assertEvery(sequence, function(i){
        return util.deepEqual(httpUtil.parseUrl(urls[i]), uris[i]);
      })
      test.done();
    }
}


text:
docker push mkodockx/docker-clamav:alpine-idb-amd64-v2021-05-25

docker push mkodockx/docker-clamav:alpine-idb-amd64


text:
  <wicket:panel>

      [ATTIRIBUTE]

    <wicket:fragment wicket:id="doubleValue">

        [ATTIRIBUTE]

        [ATTIRIBUTE]

    </wicket:fragment>
  </wicket:panel>


text:
import os
import shutil
import tempfile

import pytest

from halt import insert
from halt import load_column
from halt import load_row
from halt import delete
from halt import update
from halt import objectify
from halt import HaltException

from test_util import *

class TestHalt():

    def setup_class(cls):
        cls.tdir = tempfile.mkdtemp()

    def teardown_class(cls):
        shutil.rmtree(cls.tdir)

    def setup_method(self, func):
        '''create fresh database for each test method'''
        db = os.path.join(self.tdir, func.__name__+'.db')
        try:
            os.remove(db)
        except FileNotFoundError:
            pass
        dbcreate(db)
        self.db = db

    def test_insert(self):
        data = {'Name': 'bob', 'Password': 'password'}
        rowid = insert(self.db, 'Test', data, mash=False, commit=True, con=False)
        assert type(rowid) == int
        assert ([('bob', 'password', None)] == get_all_data(self.db))

    def test_insert_only_mash(self):
        data = {'random': 15}
        insert(self.db, 'Test', data, mash=True, commit=True, con=False)
        assert ([(None, None, '{"random": 15}')] == get_all_data(self.db))

    def test_insert_with_mash_and_columns(self):
        data = {'Name': 'bob', 'random': 15}
        insert(self.db, 'Test', data, mash=True, commit=True, con=False)
        assert ([('bob', None, '{"random": 15}')] == get_all_data(self.db))

    def test_load_column(self):
        data = {'Name': 'bob', 'Password': 'pass', 'random': 15}
        insert(self.db, 'Test', data, mash=True)
        assert 'bob' == load_column(self.db, 'Test', ('Name',))[0][0]
        assert ('bob', 'pass') == load_column(self.db,
                                             'Test', ('Name', 'Password'))[0]

    def test_load_row(self):
        data = {'Name': 'bob', 'Password': 'pass', 'random': 15}
        insert(self.db, 'Test', data, mash=True)
        assert [('bob', 'pass', {'random':15})] == load_row(self.db, 'Test', headers=False)
        should = [{'MashConfig': {'random': 15}, 'Password': 'pass', 'Name': 'bob'}]
        assert should == load_row(self.db, 'Test')

    def test_delete(self):
        data = {'Name': 'bob', 'Password': 'pass', 'random': 15}
        insert(self.db, 'Test', data, mash=True)
        delete(self.db, 'Test', "where Name == 'bob'")
        assert not get_all_data(self.db)

    def test_update_columns(self):
        data = {'Name': 'bob', 'Password': 'pass', 'random': 15}
        insert(self.db, 'Test', data, mash=True)

        new_data = {'Name': 'tom', 'random2': 15}
        update(self.db, 'Test', new_data, mash=False, cond="where Name == 'bob'")
        assert [('tom', 'pass', '{"random": 15}')] == get_all_data(self.db)

    @pytest.mark.here
    def test_update_only_mash(self):
        # First test when NOTHING in the MashConfig column
        data = {'Name': 'bob', 'Password': 'pass'}
        insert(self.db, 'Test', data, mash=False)

        new_data = {'r': 1, 'r2': 2}
        update(self.db, 'Test', new_data, mash=True, cond="where Name == 'bob'")
        results = get_all_data(self.db)
        assert results[0][:2] == ('bob', 'pass')
        dict_cmp({"r": 1, "r2": 2}, objectify(results[0][2]))

        # Now test with something existing in the mashconfig column
        new_data = {'r': 10, 'r3': 30}
        update(self.db, 'Test', new_data, mash=True, cond="where Name == 'bob'")
        results = get_all_data(self.db)
        assert results[0][:2] == ('bob', 'pass')
        dict_cmp({"r": 10, "r2": 2, "r3": 30}, objectify(results[0][2]))

    @pytest.mark.here
    def test_update_with_mash_and_columns(self):
        # First test when NOTHING in the MashConfig column
        data = {'Name': 'bob', 'Password': 'pass'}
        insert(self.db, 'Test', data, mash=False)

        new_data = {'Name': 'tom', 'r': 1, 'r2': 2}
        update(self.db, 'Test', new_data, mash=True, cond="where Name == 'bob'")
        results = get_all_data(self.db)
        assert results[0][:2] == ('tom', 'pass')
        dict_cmp({"r": 1, "r2": 2}, objectify(results[0][2]))

        # Now test with something existing in the mashconfig column
        new_data = {'Name': 'peter', 'r': 10, 'r3': 30}
        update(self.db, 'Test', new_data, mash=True, cond="where Name == 'tom'")
        results = get_all_data(self.db)
        assert results[0][:2] == ('peter', 'pass')
        dict_cmp({"r": 10, "r2": 2, "r3": 30}, objectify(results[0][2]))


text:
class RepliesController < ApplicationController
  before_action :set_reply, only: [:show, :edit, :update, :destroy]

  # GET /replies
  # GET /replies.json
  def index
    @replies = Reply.all
  end

  # GET /replies/1
  # GET /replies/1.json
  def show
  end

  # GET /replies/new
  def new
    @reply = Reply.new
  end

  # GET /replies/1/edit
  def edit
  end

  # POST /replies
  # POST /replies.json
  def create
    @reply = Reply.new(reply_params)

    respond_to do |format|
      if @reply.save
        format.html { redirect_to @reply, notice: 'Reply was successfully created.' }
        format.json { render :show, status: :created, location: @reply }
      else
        format.html { render :new }
        format.json { render json: @reply.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /replies/1
  # PATCH/PUT /replies/1.json
  def update
    respond_to do |format|
      if @reply.update(reply_params)
        format.html { redirect_to @reply, notice: 'Reply was successfully updated.' }
        format.json { render :show, status: :ok, location: @reply }
      else
        format.html { render :edit }
        format.json { render json: @reply.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /replies/1
  # DELETE /replies/1.json
  def destroy
    @reply.destroy
    respond_to do |format|
      format.html { redirect_to replies_url, notice: 'Reply was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_reply
      @reply = Reply.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def reply_params
      params.require(:reply).permit(:comment, :post_id, :user_id)
    end
end


text:
/**
 * App controller
 */
app.controllers.controller('AppController', function ($scope, $ionicSideMenuDelegate) {
    $scope.toggleLeft = function () {
        $ionicSideMenuDelegate.toggleLeft()
    }

    $scope.showSettings = function () {
        $ionicSideMenuDelegate.toggleRight()
    }
})


text:
set -xe

varnishd -a :80 -f /etc/varnish/default.vcl -s malloc,256m
varnishlog


text:
int main(int argc, char * argv[])
{
	// =====================================================================
	// Initialization & Command Line Read-In
	// =====================================================================

	int version = 13;
	double start, stop;

	// Process CLI Fields
	Input input = read_CLI( argc, argv );

	// Set number of OpenMP Threads
	omp_set_num_threads(input.nthreads);

	// =====================================================================
	// Print-out of Input Summary
	// =====================================================================
	logo(version);
	center_print("INPUT SUMMARY", 79);
	border_print();
	print_input_summary(input);

	// =====================================================================
	// Intialize Simulation Data Structures
	// =====================================================================
	border_print();
	center_print("INITIALIZATION", 79);
	border_print();

	start = get_time();

	SimulationData SD = initialize_simulation( input );

	stop = get_time();

	printf("Initialization Complete. (%.2lf seconds)\n", stop-start);

	// =====================================================================
	// Cross Section (XS) Parallel Lookup Simulation Begins
	// =====================================================================
	border_print();
	center_print("SIMULATION", 79);
	border_print();

	unsigned long vhash = 0;

	// Run Simulation
	start = get_time();

	// Run simulation
	if( input.simulation_method == EVENT_BASED )
	{
		if( input.kernel_id == 0 )
			run_event_based_simulation(input, SD, &vhash );
		else if( input.kernel_id == 1 )
			run_event_based_simulation_optimization_1(input, SD, &vhash );
		else
		{
			printf("Error: No kernel ID %d found!\n", input.kernel_id);
			exit(1);
		}
	}
	else if( input.simulation_method == HISTORY_BASED )
		run_history_based_simulation(input, SD, &vhash );

	stop = get_time();

	// Final hash step
	vhash = vhash % 999983;

	printf("Simulation Complete.\n");

	// =====================================================================
	// Print / Save Results and Exit
	// =====================================================================
	border_print();
	center_print("RESULTS", 79);
	border_print();

	int is_invalid = validate_and_print_results(input, stop-start, vhash);

	border_print();

	return is_invalid;
}


text:
require 'spec_helper'

describe Job::Tagging do
  include Support::ActiveRecord

  let(:rules) do
    YAML.load <<-yml
    - tag: rake_not_bundled
      pattern: rake is not part of the bundle
      message: Your Gemfile is missing Rake.
    - tag: database_missing
      pattern: database "[^"]*" does not exist
      message: Your test database is missing
    - tag: log_limit_exceeded
      message: Your test suite has output more than 4194304 Bytes
      pattern: The log length has exceeded the limit
    yml
  end

  let(:log) do
    <<-log
      in `block in replace_gem': rake is not part of the bundle. Add it to Gemfile. (Gem::LoadError)
      PGError: FATAL:  database "data_migrations_test" does not exist
    log
  end

  let(:job) { Factory(:test) }

  before :each do
    Job::Tagging.stubs(:rules).returns(rules)
  end

  describe :add_tags do
    it 'tags the job according to the rules' do
      job.append_log!(log)
      job.reload.add_tags
      job.tags.should == 'rake_not_bundled,database_missing'
    end
  end
end