text:
import scala.util.{Try,Success,Failure}
import scala.concurrent.{Future,Promise,blocking}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

object ManyFutures extends App {

  println("Started running")

  def manyFutures: List[Future[String]] = {
    List(Future("back"), Future("to"), Future("the"), Future("future"))
  }

  Future.sequence(manyFutures) onComplete {
    case Success(listOfStrings) => listOfStrings.map(println)
    case Failure(t) => println(t.getMessage)
  }
  println("Done!")

  delay(Duration(1000,"millis")) onComplete {
    case _ => println("hello")
  }

  def delay(t: Duration): Future[Unit] = {
      val p = Promise[Unit]()
      p.success(blocking {
        Thread.sleep(t.toMillis)
        })
      p.future
    }
}

redpajama_set_name: RedPajamaGithub


text:
package de.nb.federkiel.logic;

/**
 * Signals, that a term cannot be fulfilled. Used, when the System tries to
 * build bounds for terms.
 *
 * @author nbudzyn 2010
 */
public class CannotFulfillTermException extends Exception {
	private static final long serialVersionUID = 1L;

	public CannotFulfillTermException() {
		super();
	}
}


text:
<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>Make Glyph Texture Atlas</title>
<link type="text/css" href="resources/webgl-tutorials.css" rel="stylesheet" />
<style>
* {
  box-sizing: border-box;
}
#ui {
    width: 200px;
}
</style>
<script src="resources/webgl-utils.js"></script>
</head>
<body>
</body>
<script>
"use strict";

function saveProperties(obj) {
  var props = {};
  Object.keys(obj).forEach(function(key) {
    var desc = Object.getOwnPropertyDescriptor(obj, key);
    // only save writable properties
    if (desc.writable) {
      props[key] = obj[key];
    }
  });
  return props;
}

function restoreProperties(props, obj) {
  Object.keys(props).forEach(function(key) {
    obj[key] = props[key];
  });
}

function makeGlyphCanvas(ctx, maxWidthOfTexture, heightOfLetters, baseLine, padding, letters) {
  var rows = 1;      // number of rows of glyphs
  var x = 0;         // x position in texture to draw next glyph
  var y = 0;         // y position in texture to draw next glyph
  var glyphInfos = { // info for each glyph
  };

  // Go through each letter, measure it, remember its width and position
  for (var ii = 0; ii < letters.length; ++ii) {
    var letter = letters[ii];
    var t = ctx.measureText(letter);
    // Will this letter fit on this row?
    if (x + t.width + padding > maxWidthOfTexture) {
       // so move to the start of the next row
       x = 0;
       y += heightOfLetters;
       ++rows;
    }
    // Remember the data for this letter
    glyphInfos[letter] = {
      x: x,
      y: y,
      width: t.width,
    };
    // advance to space for next letter.
    x += t.width + padding;
  }

  // Now that we know the size we need set the size of the canvas
  // We have to save the canvas settings because changing the size
  // of a canvas resets all the settings
  var settings = saveProperties(ctx);
  ctx.canvas.width = (rows == 1) ? x : maxWidthOfTexture;
  ctx.canvas.height = rows * heightOfLetters;
  restoreProperties(settings, ctx);

  // Draw the letters into the canvas
  for (var ii = 0; ii < letters.length; ++ii) {
    var letter = letters[ii];
    var glyphInfo = glyphInfos[letter];
    var t = ctx.fillText(letter, glyphInfo.x, glyphInfo.y + baseLine);
  }

  return glyphInfos;
}

function main() {
  updateCSSIfInIFrame();
  var ctx = document.createElement("canvas").getContext("2d");
  document.body.insertBefore(ctx.canvas, document.body.firstChild);
  ctx.font = "20px sans-serif";
  ctx.fillStyle = "white";
  var maxTextureWidth = 256;
  var letterHeight = 22;
  var baseline = 16;
  var padding = 1;
  var letters = "0123456789.,abcdefghijklmnopqrstuvwxyz";
  var glyphInfos = makeGlyphCanvas(
      ctx,
      maxTextureWidth,
      letterHeight,
      baseline,
      padding,
      letters);

  // To make it clear lets draw a rect for each glyph
  ctx.globalCompositeOperation = "destination-over";
  Object.keys(glyphInfos).forEach(function(letter, ndx) {
    var glyphInfo = glyphInfos[letter];
    ctx.fillStyle = ndx % 2 ? "red" : "green";
    ctx.fillRect(glyphInfo.x, glyphInfo.y, glyphInfo.width, letterHeight);
  });
}

main();
</script>
</html>


text:
package org.springframework.social.discord.connect;

import org.springframework.social.discord.api.Discord;
import org.springframework.social.discord.api.impl.DiscordTemplate;
import org.springframework.social.oauth2.AbstractOAuth2ServiceProvider;
import org.springframework.social.oauth2.OAuth2Template;

public class DiscordServiceProvider extends AbstractOAuth2ServiceProvider<Discord> {

    public DiscordServiceProvider(String clientId, String clientSecret) {
        super(createOAuth2Template(clientId, clientSecret));
    }

    private static OAuth2Template createOAuth2Template(String clientId, String clientSecret) {
        OAuth2Template oAuth2Template = new OAuth2Template(clientId, clientSecret, "https://discordapp.com/api/oauth2/authorize", "https://discordapp.com/api/oauth2/token");
        oAuth2Template.setUseParametersForClientAuthentication(true);
        return oAuth2Template;
    }

    @Override
    public Discord getApi(String accessToken) {
        return new DiscordTemplate(accessToken);
    }
}


text:
cd ..
. ./setEnv.sh

RUN_CMD="$JAVA_HOME/bin/java $MEM_ARGS -cp $CLASSPATH twitter4j.examples.media.TwippleImageUpload"
echo $RUN_CMD ${1+"$@"}
exec $RUN_CMD ${1+"$@"}


text:
USAGE="etl/setup_database_for_etl.sh --project <PROJECT> --account <ACCOUNT> --src-folder <FOLDER> "
while true; do
  case "$1" in
    --account) ACCOUNT=$2; shift 2;;
    --project) PROJECT=$2; shift 2;;
    --src-folder) SRCFOLDER=$2; shift 2;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

if [ -z "${ACCOUNT}" ] || [ -z "${PROJECT}" ] || [ -z "${SRCFOLDER}" ]; then
  echo "Usage: $USAGE"
  exit 1
fi

CREDS_ACCOUNT=${ACCOUNT}

SRCBUCKET="all-of-us-rdr-vocabulary"

echo ""
echo "  source folder:  ${SRCBUCKET}/${SRCFOLDER}"

echo
while true; do
    read -p "Is this source correct? (y/n) " yn
    case $yn in
        [Yy]* ) break;;
        [Nn]* ) exit;;
        * ) echo "Please answer y or n.";;
    esac
done
echo "running..."

source tools/auth_setup.sh
get_db_password "${ROOT_DB_USER}"

run_cloud_sql_proxy

echo "Creating voc and cdm databases..."
mysql --verbose -h 127.0.0.1 -u "${ROOT_DB_USER}" -p${PASSWORD} --port ${PORT} < etl/create_dbs.sql

SQL_SERVICE_ACCOUNT=`gcloud sql instances describe --project ${PROJECT} --account ${ACCOUNT} \
rdrmaindb | grep serviceAccountEmailAddress | cut -d: -f2`

echo "Granting GCS access to ${SQL_SERVICE_ACCOUNT}..."
gsutil acl ch -u ${SQL_SERVICE_ACCOUNT}:W gs://${SRCBUCKET}
gsutil acl ch -u ${SQL_SERVICE_ACCOUNT}:R gs://${SRCBUCKET}/${SRCFOLDER}/*.sql

echo "Importing CDM database..."
# WARNING: This command is deprecated and will be removed in version 205.0.0. Use `gcloud sql import sql` instead.
gcloud sql instances import --quiet --project ${PROJECT} --account ${ACCOUNT} rdrmaindb gs://${SRCBUCKET}/${SRCFOLDER}/cdm.sql

echo "Importing VOC database..."
gcloud sql instances import --quiet --project ${PROJECT} --account ${ACCOUNT} rdrmaindb gs://${SRCBUCKET}/${SRCFOLDER}/voc.sql

echo "Done."


text:
"""WiZ integration models."""
from dataclasses import dataclass

from pywizlight import wizlight

from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

@dataclass
class WizData:
    """Data for the wiz integration."""

    coordinator: DataUpdateCoordinator
    bulb: wizlight
    scenes: list


text:
#!/usr/bin/env node

const figures = require('figures');
const chalk = require('chalk');
const StackUtils = require('stack-utils');
const loadEnv = require('./lib/load-env');
const cli = require('./cli');
const runDev = require('./run-dev');
const runBuild = require('./run-build');
const runLint = require('./run-lint');

loadEnv(process.env.NODE_ENV);

const catchErrors = fn => (...args) => fn(...args).catch(error => {
	const stackUtils = new StackUtils({
		cwd: process.cwd(),
		internals: StackUtils.nodeInternals()
	})
	const stack = stackUtils.clean(error.stack)

	// Log task specific errors. These are task specific errors like invald params passed or invalid data sent.
	// or log generic errors tiggered by 3rd party non task specific code.
	if (error.isAppError && error.errorType === 'task') {
		console.error(`\n${chalk.red(figures.cross)} ${chalk.bgRedBright(`There was a task error`)}`);
		console.error(error);
		console.error(`\n${chalk.red(stack)}`);
	} else {
		console.error(`\n${chalk.red(figures.cross)} ${chalk.bgRedBright(`There was an error`)}`);
		console.error(error);
		console.error(`\n${chalk.red(stack)}`);
	}

	// Exit process if we are in `release` mode so that the build pipelie fails hard with a proper exit code.
	if (cli.flags.release) {
		process.exitCode = 1;
	}
});

/**
 * CLI commands switchboard
 */
switch (cli.input[0]) {
	case 'dev':
		catchErrors(runDev)({
			isDebug: !cli.flags.release,
			nodeInspect: cli.flags.inspect,
			logLevel: cli.flags.verbose ? 3 : 8
		});
		break;
	case 'build':
		catchErrors(runBuild)({
			isDebug: !cli.flags.release,
			logLevel: cli.flags.verbose ? 3 : 8
		});
		break;
	case 'lint':
		catchErrors(runLint)();
		break;
	case 'version':
		console.log('{version.number}');
		break;
	default:
		catchErrors(runBuild)({
			isDebug: !cli.flags.release,
			logLevel: cli.flags.verbose ? 3 : 8
		});
		break;
}


text:
namespace DynamicMVC.UI.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ishotorder : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.Orders", "IsHotOrder", c => c.Boolean(nullable: false));
        }

        public override void Down()
        {
            DropColumn("dbo.Orders", "IsHotOrder");
        }
    }
}


text:
package com.intellij.execution.testframework;

import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.testframework.ui.BaseTestProxyNodeDescriptor;
import com.intellij.ide.OccurenceNavigator;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.NlsActions;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.List;

public class FailedTestsNavigator implements OccurenceNavigator {
  private TestFrameworkRunningModel myModel;

  @Override
  public boolean hasNextOccurence() {
    return myModel != null && getNextOccurenceInfo().hasNextOccurence();
  }

  @Override
  public boolean hasPreviousOccurence() {
    return myModel != null && getPreviousOccurenceInfo().hasNextOccurence();
  }

  @Override
  public OccurenceNavigator.OccurenceInfo goNextOccurence() {
    final FailedTestInfo result = getNextOccurenceInfo();
    myModel.selectAndNotify(result.getDefect());
    return new OccurenceInfo(TestsUIUtil.getOpenFileDescriptor(result.myDefect, myModel), result.getDefectNumber(),
                             result.getDefectsCount());
  }

  public void setModel(final TestFrameworkRunningModel model) {
    myModel = model;
    Disposer.register(myModel, new Disposable() {
      @Override
      public void dispose() {
        myModel = null;
      }
    });
  }

  @Override
  public OccurenceNavigator.OccurenceInfo goPreviousOccurence() {
    final FailedTestInfo result = getPreviousOccurenceInfo();
    myModel.selectAndNotify(result.getDefect());
    return new OccurenceInfo(TestsUIUtil.getOpenFileDescriptor(result.myDefect, myModel), result.getDefectNumber(),
                             result.getDefectsCount());
  }

  @NotNull
  @Override
  public String getNextOccurenceActionName() {
    return getNextName();
  }

  @NotNull
  @Override
  public String getPreviousOccurenceActionName() {
    return getPreviousName();
  }

  private FailedTestInfo getNextOccurenceInfo() {
    return new NextFailedTestInfo().execute();
  }

  private FailedTestInfo getPreviousOccurenceInfo() {
    return new PreviousFailedTestInfo().execute();
  }

  protected abstract class FailedTestInfo {
    private AbstractTestProxy myDefect = null;
    private List<AbstractTestProxy> myAllTests;
    private List<AbstractTestProxy> myDefects;

    public AbstractTestProxy getDefect() {
      return myDefect;
    }

    private int getDefectNumber() {
      return myDefect == null ? getDefectsCount() : myDefects.indexOf(myDefect) + 1;
    }

    public FailedTestInfo execute() {
      myAllTests = new ArrayList<>();
      collectTests(myAllTests, (TreeNode)myModel.getTreeView().getModel().getRoot());
      myDefects = Filter.DEFECTIVE_LEAF.select(myAllTests);
      if (myDefects.isEmpty()) {
        return this;
      }
      final AbstractTestProxy selectedTest = myModel.getTreeView().getSelectedTest();
      final int selectionIndex = myAllTests.indexOf(selectedTest);
      if (selectionIndex == -1)
        return this;
      final AbstractTestProxy defect = findNextDefect(selectionIndex);
      if (defect == null)
        return this;
      if (defect != selectedTest) {
        myDefect = defect;
        return this;
      }
      final int defectIndex = myDefects.indexOf(defect);
      if (defectIndex == -1 || defectIndex == getBoundIndex())
        return this;
      myDefect = myDefects.get(nextIndex(defectIndex));
      return this;
    }

    private void collectTests(List<? super AbstractTestProxy> tests, TreeNode node) {
      if (node == null) return;
      Object elementFor = TreeUtil.getUserObject(node);
      if (elementFor instanceof BaseTestProxyNodeDescriptor) {
        elementFor = ((BaseTestProxyNodeDescriptor<?>)elementFor).getElement();
      }
      if (elementFor instanceof AbstractTestProxy) tests.add((AbstractTestProxy)elementFor);
      for(int i = 0; i < node.getChildCount(); i++) {
        collectTests(tests, node.getChildAt(i));
      }
    }

    private AbstractTestProxy findNextDefect(final int startIndex) {
      for (int i = nextIndex(startIndex); 0 <= i && i < myAllTests.size(); i = nextIndex(i)) {
        final AbstractTestProxy nextDefect = myAllTests.get(i);
        if (Filter.DEFECTIVE_LEAF.shouldAccept(nextDefect))
          return nextDefect;
      }
      return null;
    }

    protected abstract int nextIndex(int defectIndex);

    protected abstract int getBoundIndex();

    protected int getDefectsCount() {
      return myDefects.size();
    }

    private boolean hasNextOccurence() {
      return myDefect != null;
    }
  }

  private class NextFailedTestInfo extends FailedTestInfo {
    @Override
    protected int nextIndex(final int defectIndex) {
      return defectIndex + 1;
    }

    @Override
    protected int getBoundIndex() {
      return getDefectsCount() - 1;
    }
  }

  private class PreviousFailedTestInfo extends FailedTestInfo {
    @Override
    protected int nextIndex(final int defectIndex) {
      return defectIndex - 1;
    }

    @Override
    protected int getBoundIndex() {
      return 0;
    }
  }

  static @NlsActions.ActionText String getNextName() {
    return ExecutionBundle.message("next.faled.test.action.name");
  }

  static @NlsActions.ActionText String getPreviousName() {
    return ExecutionBundle.message("prev.faled.test.action.name");
  }
}


text:
use nbndata
go

select
	ln.item_name,
	min(l.spatial_ref) GridRef
from
	location_name ln
inner join
	location l on
	ln.location_key = l.location_key
group by
	item_name
order by
	item_name


text:
package cache

type Closer interface {
	//关闭缓存引擎
	Close() error
}

type Storer interface {
	//保存到缓存
	Put(key string, value interface{}) error

	//删除缓存
	Del(key string) error

	//获取缓存
	Get(key string) (interface{}, error)
}


text:
package org.keycloak.authentication.authenticators.resetcred;

import org.keycloak.Config;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.Authenticator;
import org.keycloak.authentication.AuthenticatorFactory;
import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
import org.keycloak.email.EmailException;
import org.keycloak.email.EmailProvider;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.login.LoginFormsProvider;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.ClientSessionModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.services.Urls;
import org.keycloak.services.messages.Messages;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class ResetCredentialChooseUser implements Authenticator, AuthenticatorFactory {

    public static final String PROVIDER_ID = "reset-credentials-choose-user";

    @Override
    public void authenticate(AuthenticationFlowContext context) {
        Response challenge = context.form().createPasswordReset();
        context.challenge(challenge);
    }

    @Override
    public void action(AuthenticationFlowContext context) {
        EventBuilder event = context.getEvent();
        MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
        String username = formData.getFirst("username");
        if (username == null || username.isEmpty()) {
            event.error(Errors.USERNAME_MISSING);
            Response challenge = context.form()
                    .setError(Messages.MISSING_USERNAME)
                    .createPasswordReset();
            context.failureChallenge(AuthenticationFlowError.INVALID_USER, challenge);
            return;
        }

        UserModel user = context.getSession().users().getUserByUsername(username, context.getRealm());
        if (user == null && username.contains("@")) {
            user =  context.getSession().users().getUserByEmail(username, context.getRealm());
        }

        context.getClientSession().setNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

        // we don't want people guessing usernames, so if there is a problem, just continue, but don't set the user
        // a null user will notify further executions, that this was a failure.
        if (user == null) {
            event.clone()
                    .detail(Details.USERNAME, username)
                    .error(Errors.USER_NOT_FOUND);
        } else if (!user.isEnabled()) {
            event.clone()
                    .detail(Details.USERNAME, username)
                    .user(user).error(Errors.USER_DISABLED);
        } else {
            context.setUser(user);
        }

        context.success();
    }

    @Override
    public boolean requiresUser() {
        return false;
    }

    @Override
    public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
        return true;
    }

    @Override
    public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {

    }

    @Override
    public String getDisplayType() {
        return "Choose User";
    }

    @Override
    public String getReferenceCategory() {
        return null;
    }

    @Override
    public boolean isConfigurable() {
        return false;
    }

    public static final AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = {
            AuthenticationExecutionModel.Requirement.REQUIRED
    };

    @Override
    public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
        return REQUIREMENT_CHOICES;
    }

    @Override
    public boolean isUserSetupAllowed() {
        return false;
    }

    @Override
    public String getHelpText() {
        return "Choose a user to reset credentials for";
    }

    @Override
    public List<ProviderConfigProperty> getConfigProperties() {
        return null;
    }

    @Override
    public void close() {

    }

    @Override
    public Authenticator create(KeycloakSession session) {
        return this;
    }

    @Override
    public void init(Config.Scope config) {

    }

    @Override
    public void postInit(KeycloakSessionFactory factory) {

    }

    @Override
    public String getId() {
        return PROVIDER_ID;
    }
}


text:
/**
 * Created by GregRos on 28/05/2016.
 */
"use strict";
var Num = (function () {
    function Num() {
    }
    Num.sigFigs = function (n, sig) {
        var mult = Math.pow(10, sig - Math.floor(Math.log(n) / Math.LN10) - 1);
        return Math.round(n * mult) / mult;
    };
    return Num;
}());
exports.Num = Num;
function clone(o) {
    return JSON.parse(JSON.stringify(o));
}
exports.clone = clone;
//# sourceMappingURL=helpers.js.map


text:
<title>PHP - Mysql </title>
 Edição de registo
Escolha um registo pelo nome para Alterar ou seleccione o e-mail para enviar

<?php
$ligação= mysql_connect("localhost","root","");
if (!$ligação) {
      print ("problemas na ligação ao servidor Mysql");
}
$sql="select * from teste";
$resultado = mysql_db_query ("testeDB", $sql);
if ($resultado) {
print ("
");
print ("
NOME	TELEFONE		 dar click para enviar e-mail
");
while ($registo=mysql_fetch_array($resultado)) {
$id=$registo["id"];
$nome=$registo["nome"];
$telf=$registo["telefone"];
$imagem=$registo["img_nome"];
$email=$registo ["email"];
if ($email) {
$gif="_email.gif" ;
} else {
$gif="_email1.gif" ;
}
print ("
 $nome	 $telf	 	 $email
");
}
echo ("
");
}else{
print ("não há registos");
}
mysql_free_result ($resultado);
mysql_close();
include ('menu1.inc');
//include ('menu1A.inc');
?>


text:
<!---
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->

# org.apache.cordova.globalization

Questo plugin ottiene informazioni ed esegue operazioni specifiche impostazioni locali dell'utente, lingua e fuso orario. Si noti la differenza tra lingua e impostazioni internazionali: controlli delle impostazioni internazionali, numeri, date e tempi di visualizzazione per una regione, mentre la lingua determina quale testo di lingua appare come, indipendentemente dalle impostazioni locali. Spesso gli sviluppatori utilizzano impostazioni locali per impostare entrambe le impostazioni, ma non non c'è alcun motivo per che un utente non poteva impostare la lingua "Inglese" ma locale alla "Francese", così che il testo viene visualizzato in inglese ma le date, tempi, ecc., vengono visualizzati come sono in Francia. Purtroppo, piattaforme mobili più attualmente non fanno una distinzione tra queste impostazioni.

## Installazione

    cordova plugin add org.apache.cordova.globalization

## Oggetti

*   GlobalizationError

## Metodi

*   navigator.globalization.getPreferredLanguage
*   navigator.globalization.getLocaleName
*   navigator.globalization.dateToString
*   navigator.globalization.stringToDate
*   navigator.globalization.getDatePattern
*   navigator.globalization.getDateNames
*   navigator.globalization.isDayLightSavingsTime
*   navigator.globalization.getFirstDayOfWeek
*   navigator.globalization.numberToString
*   navigator.globalization.stringToNumber
*   navigator.globalization.getNumberPattern
*   navigator.globalization.getCurrencyPattern

## navigator.globalization.getPreferredLanguage

Ottenere il tag di lingua BCP 47 per la lingua corrente del client.

    navigator.globalization.getPreferredLanguage(successCallback, errorCallback);

### Descrizione

Restituisce l'etichetta di identificatore di linguaggio compatibile con BCP-47 per il `successCallback` con un `properties` oggetto come parametro. Tale oggetto dovrebbe avere una `value` proprietà con un `String` valore.

Se c'è un errore nell'acquisizione della lingua, poi la `errorCallback` viene eseguita con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.UNKNOWN_ERROR`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   Firefox OS
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en-US` lingua, questo dovrebbe visualizzare una finestra di dialogo pop-up con il testo `language: en-US` :

    navigator.globalization.getPreferredLanguage(
        function (language) {alert('language: ' + language.value + '\n');},
        function () {alert('Error getting language\n');}
    );

### Stranezze Android

*   Restituisce il codice di due lettere della lingua 639-1 ISO, maiuscolo ISO 3166-1 prefisso e variante separati da trattini. Esempi: "en", "en-US", "US"

### Windows Phone 8 stranezze

*   Codice restituisce l'ISO 639-1 due lettere della lingua e il codice ISO 3166-1 paese della variante regionale corrispondente alla "Lingua" impostazione, separati da un trattino.
*   Si noti che la variante regionale è una proprietà di impostazione "Language" e non determinato dall'impostazione del "Paese" indipendente su Windows Phone.

## navigator.globalization.getLocaleName

Restituisce il tag compatibile con BCP 47 per impostazione locale corrente del client.

    navigator.globalization.getLocaleName(successCallback, errorCallback);

### Descrizione

Restituisce la stringa dell'identificatore locale conforme BCP 47 per il `successCallback` con un `properties` oggetto come parametro. Tale oggetto dovrebbe avere una `value` proprietà con un `String` valore. L'etichetta locale sarà costituito da un codice di due lettere minuscole lingua, codice paese di due lettere maiuscole e codice variante (non specificato), separati da un trattino.

Se c'è un errore di ottenere le impostazioni locali, poi il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.UNKNOWN_ERROR`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   Firefox OS
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en-US` locale, questa viene visualizzata una finestra popup con il testo`locale: en-US`.

    navigator.globalization.getLocaleName(
        function (locale) {alert('locale: ' + locale.value + '\n');},
        function () {alert('Error getting locale\n');}
    );

### Stranezze Android

*   Java non fa distinzione tra un set "lingua" e impostare "impostazioni", quindi questo metodo è essenzialmente lo stesso`navigator.globalizatin.getPreferredLanguage()`.

### Windows Phone 8 stranezze

*   Codice restituisce l'ISO 639-1 due lettere della lingua e il codice ISO 3166-1 paese della variante regionale corrispondente all'impostazione "Formato regionale", separato da un trattino.

## navigator.globalization.dateToString

Restituisce una data formattata come stringa secondo le impostazioni locali del client e fuso orario.

    navigator.globalization.dateToString(date, successCallback, errorCallback, options);

### Descrizione

Restituisce la data formattata `String` tramite un `value` proprietà accessibile dall'oggetto passato come parametro per la`successCallback`.

L'ingresso `date` parametro dovrebbe essere di tipo`Date`.

Se c'è un errore di formattazione della data, allora il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.FORMATTING_ERROR`.

Il `options` parametro è facoltativo e valori predefiniti sono:

    {formatLength: 'breve', selettore: 'data e ora'}

Il `options.formatLength` può essere `short` , `medium` , `long` , o`full`.

Il `options.selector` può essere `date` , `time` o`date and time`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   Firefox OS
*   iOS
*   Windows Phone 8

### Esempio

Se il browser è impostato per la `en_US` locale, questa viene visualizzata una finestra di popup con testo simile a `date: 9/25/2012 4:21PM` utilizzando le opzioni di default:

    navigator.globalization.dateToString(
        new Date(),
        function (date) { alert('date: ' + date.value + '\n'); },
        function () { alert('Error getting dateString\n'); },
        { formatLength: 'short', selector: 'date and time' }
    );

### Windows Phone 8 stranezze

*   Il `formatLength` opzione supporta solo `short` e `full` i valori.

### Firefox OS stranezze

*   `formatLength`non è distinguere `long` e`full`
*   solo un metodo di visualizzazione data (non `long` o `full` versione)

## navigator.globalization.getCurrencyPattern

Restituisce una stringa per formattare e analizzare i valori di valuta secondo le preferenze dell'utente e il codice ISO 4217 del client.

     navigator.globalization.getCurrencyPattern(currencyCode, successCallback, errorCallback);

### Descrizione

Restituisce il modello per la `successCallback` con un `properties` oggetto come parametro. Tale oggetto deve contenere le seguenti proprietà:

*   **modello**: il modello valuta per formattare e analizzare i valori di valuta. I modelli seguono [Unicode Technical Standard #35][1]. *(String)*

*   **codice**: codice per il modello The ISO 4217. *(String)*

*   **frazione**: il numero di cifre da utilizzare durante l'analisi e la formattazione valuta. *(Numero)*

*   **arrotondamento**: l'arrotondamento incrementare per utilizzare quando l'analisi e la formattazione. *(Numero)*

*   **decimale**: il simbolo decimale da utilizzare per l'analisi e la formattazione. *(String)*

*   **raggruppamenti**: il raggruppamento simbolo da utilizzare per l'analisi e la formattazione. *(String)*

 [1]: http://unicode.org/reports/tr35/tr35-4.html

L'ingresso `currencyCode` parametro dovrebbe essere un `String` di uno dei codici valuta ISO 4217, ad esempio 'USD'.

Se c'è un errore, ottenendo il pattern, allora il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.FORMATTING_ERROR`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   iOS

### Esempio

Quando il browser è impostato per la `en_US` locale e la valuta selezionata è dollari degli Stati Uniti, in questo esempio viene visualizzata una finestra di popup con testo simile ai risultati che seguono:

    navigator.globalization.getCurrencyPattern(
        'USD',
        function (pattern) {
            alert('pattern: '  + pattern.pattern  + '\n' +
                  'code: '     + pattern.code     + '\n' +
                  'fraction: ' + pattern.fraction + '\n' +
                  'rounding: ' + pattern.rounding + '\n' +
                  'decimal: '  + pattern.decimal  + '\n' +
                  'grouping: ' + pattern.grouping);
        },
        function () { alert('Error getting pattern\n'); }
    );

Risultato atteso:

    pattern: $#,##0.##;($#,##0.##)
    code: USD
    fraction: 2
    rounding: 0
    decimal: .
    grouping: ,

## navigator.globalization.getDateNames

Restituisce una matrice di nomi di mesi o giorni della settimana, a seconda delle preferenze dell'utente del client e calendario.

    navigator.globalization.getDateNames(successCallback, errorCallback, options);

### Descrizione

Restituisce la matrice di nomi per la `successCallback` con un `properties` oggetto come parametro. Tale oggetto contiene un `value` proprietà con un `Array` di `String` i valori. I nomi di funzioni matrice a partire da entrambi il primo mese dell'anno o il primo giorno della settimana, a seconda dell'opzione selezionata.

Se c'è un errore ottenendo i nomi, poi il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.UNKNOWN_ERROR`.

Il `options` parametro è facoltativo e valori predefiniti sono:

    {type:'wide', item:'months'}

Il valore di `options.type` può essere `narrow` o`wide`.

Il valore di `options.item` può essere `months` o`days`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   Firefox OS
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en_US` locale, in questo esempio viene visualizzata una serie di dodici finestre pop-up, uno al mese, con un testo simile a `month: January` :

    navigator.globalization.getDateNames(
        function (names) {
            for (var i = 0; i < names.value.length; i++) {
                alert('month: ' + names.value[i] + '\n');
            }
        },
        function () { alert('Error getting names\n'); },
        { type: 'wide', item: 'months' }
    );

### Firefox OS stranezze

*   `options.type`supporta un `genitive` valore, importante per alcune lingue

## navigator.globalization.getDatePattern

Restituisce una stringa per formattare e analizzare i dati secondo le preferenze dell'utente del client.

    navigator.globalization.getDatePattern(successCallback, errorCallback, options);

### Descrizione

Restituisce il modello per la `successCallback` . L'oggetto passato come parametro contiene le seguenti proprietà:

*   **modello**: il modello di data e ora per formattare e analizzare i dati. I modelli seguono [Unicode Technical Standard #35][1]. *(String)*

*   **fuso orario**: il nome abbreviato del fuso orario sul client. *(String)*

*   **utc_offset**: l'attuale differenza in secondi tra del client fuso orario e tempo universale coordinato. *(Numero)*

*   **DST_OFFSET**: l'offset corrente ora legale in secondi tra non-legale del client di fuso orario e ora legale del cliente risparmio di fuso orario. *(Numero)*

Se c'è un errore per ottenere il modello, il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.PATTERN_ERROR`.

Il `options` parametro è facoltativo e verrà impostato i seguenti valori:

    {formatLength: 'breve', selettore: 'data e ora'}

Il `options.formatLength` può essere `short` , `medium` , `long` , o `full` . Il `options.selector` può essere `date` , `time` o`date and
time`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en_US` locale, in questo esempio viene visualizzata una finestra di popup con il testo come `pattern: M/d/yyyy h:mm a` :

    function checkDatePattern() {
        navigator.globalization.getDatePattern(
            function (date) { alert('pattern: ' + date.pattern + '\n'); },
            function () { alert('Error getting pattern\n'); },
            { formatLength: 'short', selector: 'date and time' }
        );
    }

### Windows Phone 8 stranezze

*   Il `formatLength` supporta solo `short` e `full` i valori.

*   La `pattern` per `date and time` modello restituisce solo il formato datetime completo.

*   Il `timezone` restituisce il nome della zona a tempo pieno.

*   La `dst_offset` proprietà non è supportata, e sempre restituisce zero.

## navigator.globalization.getFirstDayOfWeek

Restituisce il primo giorno della settimana secondo le preferenze dell'utente del client e calendario.

    navigator.globalization.getFirstDayOfWeek(successCallback, errorCallback);

### Descrizione

I giorni della settimana sono numerati a partire da 1, dove 1 è presupposto per essere domenica. Restituisce il giorno per la `successCallback` con un `properties` oggetto come parametro. Tale oggetto dovrebbe avere una `value` proprietà con un `Number` valore.

Se c'è un errore, ottenendo il pattern, allora il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.UNKNOWN_ERROR`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   Firefox OS
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en_US` locale, questa viene visualizzata una finestra di popup con testo simile a`day: 1`.

    navigator.globalization.getFirstDayOfWeek(
        function (day) {alert('day: ' + day.value + '\n');},
        function () {alert('Error getting day\n');}
    );

## navigator.globalization.getNumberPattern

Restituisce una stringa per formattare e analizzare i numeri secondo le preferenze dell'utente del client.

    navigator.globalization.getNumberPattern(successCallback, errorCallback, options);

### Descrizione

Restituisce il modello per la `successCallback` con un `properties` oggetto come parametro. Tale oggetto contiene le seguenti proprietà:

*   **modello**: il modello del numero per formattare e analizzare i numeri. I modelli seguono [Unicode Technical Standard #35][1]. *(String)*

*   **simbolo**: il simbolo da utilizzare durante la formattazione e l'analisi, come un simbolo di percentuale o valuta. *(String)*

*   **frazione**: il numero di cifre da utilizzare durante l'analisi e la formattazione dei numeri. *(Numero)*

*   **arrotondamento**: l'arrotondamento incrementare per utilizzare quando l'analisi e la formattazione. *(Numero)*

*   **positivo**: il simbolo da utilizzare per i numeri positivi quando l'analisi e la formattazione. *(String)*

*   **negativo**: il simbolo da utilizzare per i numeri negativi quando l'analisi e la formattazione. *(String)*

*   **decimale**: il simbolo decimale da utilizzare per l'analisi e la formattazione. *(String)*

*   **raggruppamenti**: il raggruppamento simbolo da utilizzare per l'analisi e la formattazione. *(String)*

Se c'è un errore, ottenendo il pattern, allora il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.PATTERN_ERROR`.

Il `options` parametro è facoltativo e i valori predefiniti sono:

    {tipo: 'decimale'}

Il `options.type` può essere `decimal` , `percent` , o`currency`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en_US` locale, questo dovrebbe visualizzare una finestra di popup con testo simile ai risultati che seguono:

    navigator.globalization.getNumberPattern(
        function (pattern) {alert('pattern: '  + pattern.pattern  + '\n' +
                                  'symbol: '   + pattern.symbol   + '\n' +
                                  'fraction: ' + pattern.fraction + '\n' +
                                  'rounding: ' + pattern.rounding + '\n' +
                                  'positive: ' + pattern.positive + '\n' +
                                  'negative: ' + pattern.negative + '\n' +
                                  'decimal: '  + pattern.decimal  + '\n' +
                                  'grouping: ' + pattern.grouping);},
        function () {alert('Error getting pattern\n');},
        {type:'decimal'}
    );

Risultati:

    pattern: #,##0.###
    symbol: .
    fraction: 0
    rounding: 0
    positive:
    negative: -
    decimal: .
    grouping: ,

### Windows Phone 8 stranezze

*   La `pattern` proprietà non è supportata e retuens una stringa vuota.

*   La `fraction` proprietà non è supportata e restituisce zero.

## navigator.globalization.isDayLightSavingsTime

Indica se l'ora legale è in vigore per una data specifica utilizzando del client fuso orario e calendario.

    navigator.globalization.isDayLightSavingsTime(date, successCallback, errorCallback);

### Descrizione

Indica se è o meno dell'ora legale in vigore alla `successCallback` con un `properties` oggetto come parametro. Tale oggetto dovrebbe avere una `dst` proprietà con un `Boolean` valore. A `true` il valore indica che l'ora legale è in vigore per la data specificata, e `false` indica che non è.

Il parametro in ingresso `date` dovrebbe essere di tipo`Date`.

Se c'è un errore di lettura della data, allora il `errorCallback` esegue. Previsto codice dell'errore è`GlobalizationError.UNKNOWN_ERROR`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   Firefox OS
*   iOS
*   Windows Phone 8

### Esempio

Durante l'estate, e se il browser è impostato su un fuso orario abilitato DST, questo dovrebbe visualizzare una finestra di popup con testo simile a `dst: true` :

    navigator.globalization.isDayLightSavingsTime(
        new Date(),
        function (date) {alert('dst: ' + date.dst + '\n');},
        function () {alert('Error getting names\n');}
    );

## navigator.globalization.numberToString

Restituisce un numero formattato come una stringa secondo le preferenze dell'utente del client.

    navigator.globalization.numberToString(number, successCallback, errorCallback, options);

### Descrizione

Restituisce la stringa formattata numero per la `successCallback` con un `properties` oggetto come parametro. Tale oggetto dovrebbe avere una `value` proprietà con un `String` valore.

Se c'è un errore di formattazione del numero, poi il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.FORMATTING_ERROR`.

Il `options` parametro è facoltativo e valori predefiniti sono:

    {tipo: 'decimale'}

Il `options.type` può essere 'decimale', '%' o 'valuta'.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en_US` locale, questa viene visualizzata una finestra di popup con testo simile a `number: 3.142` :

    navigator.globalization.numberToString(
        3.1415926,
        function (number) {alert('number: ' + number.value + '\n');},
        function () {alert('Error getting number\n');},
        {type:'decimal'}
    );

## navigator.globalization.stringToDate

Analizza una data formattata come stringa, secondo le preferenze dell'utente e calendario utilizzando il fuso orario del cliente, il cliente e restituisce l'oggetto data corrispondente.

    navigator.globalization.stringToDate(dateString, successCallback, errorCallback, options);

### Descrizione

Restituisce la data al metodo di callback con successo un `properties` oggetto come parametro. Tale oggetto dovrebbe avere le seguenti proprietà:

*   **anno**: l'anno a quattro cifre. *(Numero)*

*   **mese**: mese da (0-11). *(Numero)*

*   **giorno**: il giorno da (1-31). *(Numero)*

*   **ora**: l'ora (0-23). *(Numero)*

*   **minuti**: il minuto da (0-59). *(Numero)*

*   **secondo**: il secondo da (0-59). *(Numero)*

*   **millisecondo**: I millisecondi (da 0-999), non disponibili su tutte le piattaforme. *(Numero)*

L'ingresso `dateString` parametro dovrebbe essere di tipo`String`.

Il `options` parametro è facoltativo e verrà impostato i seguenti valori:

    {formatLength: 'breve', selettore: 'data e ora'}

Il `options.formatLength` può essere `short` , `medium` , `long` , o `full` . Il `options.selector` può essere `date` , `time` o`date and
time`.

Se c'è un errore di parsing della stringa data, allora il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.PARSING_ERROR`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   Firefox OS
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en_US` locale, questa viene visualizzata una finestra di popup con testo simile a `month:8 day:25 year:2012` . Si noti che il mese intero è uno minore di stringa, come l'intero mese rappresenta un indice di matrice.

    navigator.globalization.stringToDate(
        '9/25/2012',
        function (date) {alert('month:' + date.month +
                               ' day:'  + date.day   +
                               ' year:' + date.year  + '\n');},
        function () {alert('Error getting date\n');},
        {selector: 'date'}
    );

### Windows Phone 8 stranezze

*   Il `formatLength` opzione supporta solo `short` e `full` i valori.

## navigator.globalization.stringToNumber

Analizza un numero formattato come una stringa secondo le preferenze dell'utente del client e restituisce il numero corrispondente.

    navigator.globalization.stringToNumber(string, successCallback, errorCallback, options);

### Descrizione

Restituisce il numero per il `successCallback` con un `properties` oggetto come parametro. Tale oggetto dovrebbe avere una `value` proprietà con un `Number` valore.

Se c'è un errore di parsing della stringa di numeri, poi il `errorCallback` viene eseguito con un `GlobalizationError` oggetto come parametro. Previsto codice dell'errore è`GlobalizationError.PARSING_ERROR`.

Il `options` parametro è facoltativo e verrà impostato i seguenti valori:

    {tipo: 'decimale'}

Il `options.type` può essere `decimal` , `percent` , o`currency`.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   iOS
*   Windows Phone 8

### Esempio

Quando il browser è impostato per la `en_US` locale, questo dovrebbe visualizzare una finestra di popup con testo simile a `number: 1234.56` :

    navigator.globalization.stringToNumber(
        '1234.56',
        function (number) {alert('number: ' + number.value + '\n');},
        function () {alert('Error getting number\n');},
        {type:'decimal'}
    );

## GlobalizationError

Un oggetto che rappresenta un errore dall'API di globalizzazione.

### Proprietà

*   **codice**: Uno dei seguenti codici che rappresenta il tipo di errore *(Numero)*
    *   GlobalizationError.UNKNOWN_ERROR: 0
    *   GlobalizationError.FORMATTING_ERROR: 1
    *   GlobalizationError.PARSING_ERROR: 2
    *   GlobalizationError.PATTERN_ERROR: 3
*   **messaggio**: un messaggio di testo che include la spiegazione dell'errore e/o dettagli *(String)*

### Descrizione

Questo oggetto è creato e popolato da Cordova e restituito una richiamata in caso di errore.

### Piattaforme supportate

*   Amazon fuoco OS
*   Android
*   BlackBerry 10
*   Firefox OS
*   iOS

### Esempio

Quando si esegue il callback di errore seguenti, esso viene visualizzata una finestra popup con il testo simile a `code: 3` e`message:`

    function errorCallback(error) {
        alert('code: ' + error.code + '\n' +
              'message: ' + error.message + '\n');
    };


text:
"""Module for communication tools."""
# flake8: noqa
from .group_communication import (
    group_value_read,
    group_value_response,
    group_value_write,
    read_group_value,
)

__all__ = [
    "group_value_read",
    "group_value_response",
    "group_value_write",
    "read_group_value",
]


text:
Sonia Sen
---------

![](photos/sonia-sen.png)

* [LinkedIn](https://www.linkedin.com/in/soniasen)
* [Github](https://github.com/szsen)
* [Twitter](https://twitter.com/thesoniasen)


text:
const query = require('../../utilities/query')

const StudentColumns = [
  'sid',
  'student_id',
  'curriculum_id',
  'member_id',
  'title',
  'firstname',
  'lastname',
  'email',
  'nationality',
  'birthdate',
  'gender',
  'citizen_id',
  'religion',
  'mobile',
  'img',
  'addr',
  'zipcode',
  'country',
  'emer_name',
  'emer_mobile',
  'emer_addr',
  'emer_zipcode',
  'emer_country',
  'highschool_name',
  'highschool_grade',
  'gpax',
  'semester_count',
  'summer_count',
  'status',
  'behavioral_score'
]
const TABLE_NAME = 'students'
const getAllStudentSQL = () => `SELECT * FROM ${TABLE_NAME}`

const getOneStudentSQL = (studentID) => {
  return `SELECT * FROM ${TABLE_NAME} WHERE student_id = "${studentID}"`
}

const deleteStudentSQL = (where) => {
  return query.transformToSQL.delete(TABLE_NAME, where)
}

const updateStudentSQL = (studentID, dataSet) => {
  return query.transformToSQL.update(TABLE_NAME, dataSet,
    `student_id = "${studentID}"`)
}

const insertStudentSQL = (dataSet) => {
  return query.transformToSQL.insert(TABLE_NAME, dataSet)
}

const filterStudentSQL = (filterList) => {
  return query.transformToSQL.filter(TABLE_NAME, filterList)
}

const getEnrollsCourseSQL = (id) => {
  return `SELECT students.student_id, enrollment_records.grade, courses.* FROM courses
  INNER JOIN sections ON courses.course_id = sections.course_id
  INNER JOIN enrollment_records ON enrollment_records.course_id = sections.course_id
  INNER JOIN students ON students.sid = enrollment_records.sid
  WHERE student_id = "${id}"
  GROUP BY students.sid, courses.course_id;`
}

const getGpaAndGpax = (id) => {
  return `select g.gpa, g.gpax, g.year, g.semester from grades as g
          inner join students as s
          on s.sid = g.sid
          where s.student_id = "${id}"
          order by g.year, g.semester;`
}

module.exports = {
  StudentColumns,
  getAllStudentSQL,
  getOneStudentSQL,
  deleteStudentSQL,
  updateStudentSQL,
  insertStudentSQL,
  filterStudentSQL,
  getEnrollsCourseSQL,
  getGpaAndGpax
}


text:
@interface DMKeychain : NSObject

+ (void)setAccessIdentifier:(nonnull NSString*)identifier;
+ (nonnull instancetype)shared;

- (void)setObject:(nonnull id)ob forKey:(nonnull NSString*)key;
- (nullable id)objectForKey:(nonnull NSString*)key;

@end


text:
package com.lefu.remote.netty.client;

import java.net.SocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;

import com.lefu.remote.netty.NettyConfigure;

/**
 * 客户端行为定义
 * @author jiang.li
 *
 */
public interface NettyClient extends NettyConfigure {
	/**
	 * 建立新的连接
	 * @param host
	 * @param port
	 * @return
	 * @throws Exception
	 */
	public Channel connect(String host, int port) throws Exception;
	/**
	 *
	 * @param socketAddress
	 * @return
	 * @throws Exception
	 */
	public Channel connect(SocketAddress socketAddress) throws Exception;

	/**
	 * 获取Netty {@link Bootstrap}
	 * @return
	 */
	public Bootstrap getBootstrap();
}


text:
perms :: Int -> Int -> Int

perms rank length | length < 0 = 0
				  | rank < 0 = 0
                  | rank > length = 0
				  | rank == length = 1
                  | otherwise = (perms (rank + 1) (length - 1)) + (perms (rank - 1) (length - 1))

-- calc rank of a sequence
rank :: [Char] -> Int
rank [] = 0
rank ['('] = 1
rank [')'] = -1
rank x :: xs = rank [x] + rank xs

solution :: Int -> Int -> [Char] -> Int
solution n m xs =
	let r = rank xs
		len = length xs

	-- for all possible lengths of prefix
	-- for all possible ranks of prefix
	-- calculate the number of permutations of prefix
	-- calculate number of permutations of suffix
	-- accumulate

	-- take mod 10 ^ 9 + 7


text:
<?php
require_once(__DIR__."/../src/02-DBMockStorage.php");
require_once(__DIR__."/../src/02-FileStorage.php");
require_once(__DIR__."/../src/02-MemStorage.php");
class StorageTest extends \PHPUnit\Framework\TestCase {
  public function testDBMockStorage00() {
    // arrange
    $harness = new DBMockStorage("MySQL", "item0");
    // act
    $actual = $harness->databaseType();
    // assert
    $this->assertEquals("MySQL", $actual);
    $this->assertEquals(1, $harness->Count());
  }
  public function testDBMockStorage01() {
    // arrange
    $harness = new DBMockStorage("MySQL", "item0");
    $harness->Put("item1");
    // act
    $actual = $harness->Count();
    // assert
    $this->assertEquals(2, $harness->Count());
  }
 public function testFileStorage00() {
    // arrange
    $harness = new FileStorage();
    $harness->Put("item0");
    // act
    $actual = $harness->Count();
    // assert
    $this->assertEquals(5, $actual);
  }
 public function testFileStorage01() {
    // arrange
    $harness = new FileStorage();
    $harness->Put("item0");
    $harness->Put("item1");
    // act
    $actual = $harness->Count();
    // assert
    $this->assertEquals(10, $actual);
  }
  public function testFileStorage02()
  {
      // arrange
      $writer = new FileStorage();
      $writer->Put("item0");
      $writer->Put("item1");
      $reader = new FileStorage(); // Don't use an instance counter.
      // act
      $actual = $reader->Count();
      // assert
      $this->assertEquals(10, $actual);
  }
  public function testFileStorage03()
  {
      // arrange
      $harness = new FileStorage();
      $harness->Put("one");
      $harness->Put("four");
      // act
      $actual = $harness->Count();
      // assert
      $this->assertEquals(7, $actual);
  }
  public function testMemStorage00() {
    // arrange
    $harness = new MemStorage("item0");
    // act
    $actual = $harness->Count();
    // assert
    $this->assertEquals(1, $actual);
  }
  public function testMemStorage01() {
    // arrange
    $harness = new MemStorage("item0");
    $harness->Put("item1");
    // act
    $actual = $harness->Count();
    // assert
    $this->assertEquals(2, $actual);
  }
  protected function tearDown() {
    system("rm -f data.txt");
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IntelliTect.Coalesce.DataAnnotations
{
    /// <summary>
    /// Controls attributes of the API controller action generated for the target method.
    /// </summary>
    [System.AttributeUsage(System.AttributeTargets.Method)]
    public class ControllerActionAttribute : System.Attribute
    {
        public ControllerActionAttribute() { }

        public ControllerActionAttribute(HttpMethod method)
        {
            Method = method;
        }

        public HttpMethod Method { get; set; }

        /// <summary>
        /// <para>
        /// For HTTP GET model instance methods, specifies the name of a property on the model
        /// that will be used for ETag values and for querystring-based cache variation.
        /// </para>
        /// <para>
        /// The ViewModels on the client will automatically include the property's value
        /// in the querystring of URLs for the method, and the generated controller will
        /// set a long term Cache-Control value on the response if the client-provided value matches the true value.
        /// </para>
        /// </summary>
        public string? VaryByProperty { get; set; }
    }

    public enum HttpMethod
    {
        Post = 0,
        Get = 1,
        Put = 2,
        Delete = 3,
        Patch = 4
    }
}


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="API documentation for the Rust `list` mod in crate `proxer`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, list">

    <title>proxer::list - Rust</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">

proxer

        <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>

Module proxer::<wbr>list

                       [−]

               [src]

Structs

                           EntryList

Diese Funktion liefert eine Liste aller Entrys einer Kategorie mit bestimmten Einschränkungsmöglichkeiten.

                           EntrySearch

Diese Funktion erfüllt die Aufgabe der erweiterten Suche

                           Industry

Diese Funktion liefert eine Liste aller Firmen, anhand bestimmter Kriterien.

                           IndustrysProject

Diese Funktion liefert eine Liste aller Projekte (=Entrys) einer Firma anhand ihrer ID.

                           List

Diese Klasse dient als Hauptmethode um die Daten von Entrys zu erhalten,
insbesondere der ID (die für jede spezielle Entry Schnittstelle nötig ist).
Sie enthält zwei Arten von Schnittstellen: Eine "Search" Schnittstelle,
die wie die Erweiterte Suche auf Proxer funktioniert, sowie Auflistungs-Schnittstellen,
die Animelisten nach bestimmten Schemata erstellen.

                           Tag

Diese Funktion liefert eine Liste aller Tags, anhand bestimmter Kriterien.

                           TagIDs

Diese Funktion zieht aus einem String die IDs aller darin vorkommenden Tags und gibt sie zurück.

                           TranslatorGroup

Diese Funktion liefert eine Liste aller Sub/Scanlation Gruppen, anhand bestimmter Kriterien.

                           TranslatorGroupProject

Diese Funktion liefert eine Liste aller Projekte (=Entrys) einer Gruppe anhand ihrer ID.

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:
@echo off

REM     Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.

REM     Licensed under the Amazon Software License (the "License").
REM     You may not use this file except in compliance with the License.
REM     A copy of the License is located at

REM     http://aws.amazon.com/asl/

REM     or in the "license" file accompanying this file. This file is distributed
REM     on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
REM     express or implied. See the License for the specific language governing
REM     permissions and limitations under the License.

node %~dp0\kcl-bootstrap %*


text:
package org.ovirt.engine.extension.aaa.jdbc.binding.cli.parser;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class StringValueConverter {

    private static final Map<Class<?>, Class<?>> typeBox = new HashMap<>();
    static {
        typeBox.put(boolean.class, Boolean.class);
        typeBox.put(byte.class, Byte.class);
        typeBox.put(char.class, Character.class);
        typeBox.put(double.class, Double.class);
        typeBox.put(float.class, Float.class);
        typeBox.put(int.class, Integer.class);
        typeBox.put(long.class, Long.class);
        typeBox.put(short.class, Short.class);
        typeBox.put(void.class, Void.class);
    }

    public static Object getObjectValueByString(Class<?> clazz, String value) {
        Object v = null;

        if (clazz.isPrimitive()) {
            clazz = typeBox.get(clazz);
        }

        if (clazz.equals(Collection.class)) {
            List<Object> r = new ArrayList<>();
            for (String c : value.trim().split(" *, *")) {
                if (!c.isEmpty()) {
                    r.add(getObjectValueByString(String.class, c));
                }
            }
            v = r;
        }

        if (v == null) {
            if (clazz.isArray() && Object.class.isAssignableFrom(clazz.getComponentType())) {
                List<Object> r = new ArrayList<>();
                for (String c : value.trim().split(" *, *")) {
                    if (!c.isEmpty()) {
                        r.add(getObjectValueByString(clazz.getComponentType(), c));
                    }
                }
                v = (Object)r.toArray((Object[]) Array.newInstance(clazz.getComponentType(), 0));
            }
        }

        if (v == null) {
            try {
                Field f = clazz.getField(value);
                if (Modifier.isStatic(f.getModifiers())) {
                    v = f.get(null);
                }
            } catch(ReflectiveOperationException e) {}
        }

        if (v == null) {
            try {
                Method convert = clazz.getMethod("valueOf", String.class);
                if (Modifier.isStatic(convert.getModifiers())) {
                    v = convert.invoke(null, value);
                }
            } catch(ReflectiveOperationException e) {}
        }

        if (v == null) {
            try {
                Method convert = clazz.getMethod("valueOf", Object.class);
                if (Modifier.isStatic(convert.getModifiers())) {
                    v = convert.invoke(null, value);
                }
            } catch(ReflectiveOperationException e) {}
        }

        if (v == null) {
            try {
                Constructor<?> constructor = clazz.getDeclaredConstructor(String.class);
                v = constructor.newInstance(value);
            } catch(ReflectiveOperationException e) {}
        }

        return v;
    }

}


text:
<?php

namespace Google\Service\Contentwarehouse;

class KnowledgeAnswersIntentQueryGroundingSignals extends \Google\Model
{
  /**
   * @var bool
   */
  public $addedByGrounding;
  public $groundabilityScore;
  public $numConstraints;
  public $numConstraintsSatisfied;
  public $numGroundableArgs;
  public $numGroundedArgs;
  public $numVariables;
  public $numVariablesGrounded;
  /**
   * @var string
   */
  public $pgrpOutputFormat;
  /**
   * @var bool
   */
  public $usesGroundingBox;

  /**
   * @param bool
   */
  public function setAddedByGrounding($addedByGrounding)
  {
    $this->addedByGrounding = $addedByGrounding;
  }
  /**
   * @return bool
   */
  public function getAddedByGrounding()
  {
    return $this->addedByGrounding;
  }
  public function setGroundabilityScore($groundabilityScore)
  {
    $this->groundabilityScore = $groundabilityScore;
  }
  public function getGroundabilityScore()
  {
    return $this->groundabilityScore;
  }
  public function setNumConstraints($numConstraints)
  {
    $this->numConstraints = $numConstraints;
  }
  public function getNumConstraints()
  {
    return $this->numConstraints;
  }
  public function setNumConstraintsSatisfied($numConstraintsSatisfied)
  {
    $this->numConstraintsSatisfied = $numConstraintsSatisfied;
  }
  public function getNumConstraintsSatisfied()
  {
    return $this->numConstraintsSatisfied;
  }
  public function setNumGroundableArgs($numGroundableArgs)
  {
    $this->numGroundableArgs = $numGroundableArgs;
  }
  public function getNumGroundableArgs()
  {
    return $this->numGroundableArgs;
  }
  public function setNumGroundedArgs($numGroundedArgs)
  {
    $this->numGroundedArgs = $numGroundedArgs;
  }
  public function getNumGroundedArgs()
  {
    return $this->numGroundedArgs;
  }
  public function setNumVariables($numVariables)
  {
    $this->numVariables = $numVariables;
  }
  public function getNumVariables()
  {
    return $this->numVariables;
  }
  public function setNumVariablesGrounded($numVariablesGrounded)
  {
    $this->numVariablesGrounded = $numVariablesGrounded;
  }
  public function getNumVariablesGrounded()
  {
    return $this->numVariablesGrounded;
  }
  /**
   * @param string
   */
  public function setPgrpOutputFormat($pgrpOutputFormat)
  {
    $this->pgrpOutputFormat = $pgrpOutputFormat;
  }
  /**
   * @return string
   */
  public function getPgrpOutputFormat()
  {
    return $this->pgrpOutputFormat;
  }
  /**
   * @param bool
   */
  public function setUsesGroundingBox($usesGroundingBox)
  {
    $this->usesGroundingBox = $usesGroundingBox;
  }
  /**
   * @return bool
   */
  public function getUsesGroundingBox()
  {
    return $this->usesGroundingBox;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(KnowledgeAnswersIntentQueryGroundingSignals::class, 'Google_Service_Contentwarehouse_KnowledgeAnswersIntentQueryGroundingSignals');


text:
title: "Page One adult storytime: Robinson Crusoe by Daniel Defoe"
location-display-name: "BLOC: Building Libraries on Creativity"
format: recording
link: A4sPl6A7yXw
category: interview
service: youtube
---

'Page One' is storytime for grown-ups. Suffolk Libraries will be reading tasters of the adventures, tall tales and stories available through our 44 libraries across Suffolk and available on our eLibrary services.

This week we bring you [Robinson Crusoe](https://suffolklibraries.overdrive.com/media/344615) by Daniel Defoe, read by Andrew Wisher.

For free access to thousands of the latest eBooks, eAudio titles, magazines, newspapers, films, courses and streaming, have a look at our [eLibrary](/elibrary)


text:
namespace peloton {
namespace logging {

void WriteBehindBackendLogger::Log(LogRecord *record) {
  // if we are committing, sync all data before taking the lock
  if (record->GetType() == LOGRECORD_TYPE_TRANSACTION_COMMIT) {
    auto &log_manager = LogManager::GetInstance();
    auto no_write = log_manager.GetNoWrite();

    if(no_write == false) {
      SyncDataForCommit();
    }
  }
  log_buffer_lock.Lock();
  switch (record->GetType()) {
    case LOGRECORD_TYPE_TRANSACTION_COMMIT:
      highest_logged_commit_message = record->GetTransactionId();
      // fallthrough
    case LOGRECORD_TYPE_TRANSACTION_ABORT:
    case LOGRECORD_TYPE_TRANSACTION_BEGIN:
    case LOGRECORD_TYPE_TRANSACTION_DONE:
    case LOGRECORD_TYPE_TRANSACTION_END: {
      if (logging_cid_lower_bound < record->GetTransactionId() - 1) {
        logging_cid_lower_bound = record->GetTransactionId() - 1;
      }
      break;
    }
    case LOGRECORD_TYPE_WBL_TUPLE_DELETE:
    case LOGRECORD_TYPE_WAL_TUPLE_DELETE: {
      tile_groups_to_sync_.insert(
          ((TupleRecord *)record)->GetDeleteLocation().block);
      break;
    }
    case LOGRECORD_TYPE_WBL_TUPLE_INSERT:
    case LOGRECORD_TYPE_WAL_TUPLE_INSERT: {
      tile_groups_to_sync_.insert(
          ((TupleRecord *)record)->GetInsertLocation().block);
      break;
    }
    case LOGRECORD_TYPE_WBL_TUPLE_UPDATE:
    case LOGRECORD_TYPE_WAL_TUPLE_UPDATE: {
      tile_groups_to_sync_.insert(
          ((TupleRecord *)record)->GetDeleteLocation().block);
      tile_groups_to_sync_.insert(
          ((TupleRecord *)record)->GetInsertLocation().block);
      break;
    }
    default:
      LOG_INFO("Invalid log record type");
      break;
  }

  log_buffer_lock.Unlock();
}

void WriteBehindBackendLogger::SyncDataForCommit() {
  auto &manager = catalog::Manager::GetInstance();

  // Sync the tiles in the modified tile groups and their headers
  for (oid_t tile_group_id : tile_groups_to_sync_) {
    auto tile_group = manager.GetTileGroup(tile_group_id);
    tile_group->Sync();
    tile_group->GetHeader()->Sync();
  }

  // Clear the list of tile groups
  tile_groups_to_sync_.clear();
}

LogRecord *WriteBehindBackendLogger::GetTupleRecord(
    LogRecordType log_record_type, txn_id_t txn_id, oid_t table_oid,
    oid_t db_oid, ItemPointer insert_location, ItemPointer delete_location,
    UNUSED_ATTRIBUTE const void *data) {
  // Figure the log record type
  LogRecord *tuple_record;

  switch (log_record_type) {
    case LOGRECORD_TYPE_TUPLE_INSERT: {
      log_record_type = LOGRECORD_TYPE_WBL_TUPLE_INSERT;
      break;
    }

    case LOGRECORD_TYPE_TUPLE_DELETE: {
      log_record_type = LOGRECORD_TYPE_WBL_TUPLE_DELETE;
      break;
    }

    case LOGRECORD_TYPE_TUPLE_UPDATE: {
      log_record_type = LOGRECORD_TYPE_WBL_TUPLE_UPDATE;
      break;
    }

    default: {
      PL_ASSERT(false);
      break;
    }
  }
  // Don't make use of "data" in case of peloton log records
  // Build the tuple log record
  tuple_record =
      new TupleRecord(log_record_type, txn_id, table_oid, insert_location,
                      delete_location, nullptr, db_oid);

  return tuple_record;
}

}  // namespace logging
}  // namespace peloton


text:
package com.billybyte.spanjava;

import java.util.Map;

import com.billybyte.commonstaticmethods.Utils;
import com.billybyte.spanjava.resources.SpanUtils;

import junit.framework.TestCase;

public class TestResourcesInPackages extends TestCase{
	@SuppressWarnings("unchecked")
	public void test1(){
		Map<String,String> bestOptSymbolMap = Utils.getXmlData(Map.class, SpanUtils.class, "bestOptSymbolMap.xml");
		assertTrue(bestOptSymbolMap!=null && bestOptSymbolMap.size()>0);
		Map<String,String> iceCmeAssocMap = Utils.getXmlData(Map.class, SpanUtils.class, "iceToCmeProdConvMap.xml");
		assertTrue(iceCmeAssocMap!=null && iceCmeAssocMap.size()>0);

	}
}


text:
package template

import (
	"strconv"
	"strings"

	"github.com/golang/glog"
	"github.com/imdario/mergo"

	"github.com/fatih/structs"
	"github.com/mitchellh/mapstructure"
	go_camelcase "github.com/segmentio/go-camelcase"

	"github.com/aledbf/ingress-controller/backends/nginx/pkg/config"
	"github.com/aledbf/ingress-controller/pkg/ingress/defaults"

	"k8s.io/kubernetes/pkg/api"
)

const (
	customHTTPErrors     = "custom-http-errors"
	skipAccessLogUrls    = "skip-access-log-urls"
	whitelistSourceRange = "whitelist-source-range"
)

// StandarizeKeyNames ...
func StandarizeKeyNames(data interface{}) map[string]interface{} {
	return fixKeyNames(structs.Map(data))
}

// ReadConfig obtains the configuration defined by the user merged with the defaults.
func ReadConfig(conf *api.ConfigMap) config.Configuration {
	if len(conf.Data) == 0 {
		return config.NewDefault()
	}

	var errors []int
	var skipUrls []string
	var whitelist []string

	if val, ok := conf.Data[customHTTPErrors]; ok {
		delete(conf.Data, customHTTPErrors)
		for _, i := range strings.Split(val, ",") {
			j, err := strconv.Atoi(i)
			if err != nil {
				glog.Warningf("%v is not a valid http code: %v", i, err)
			} else {
				errors = append(errors, j)
			}
		}
	}
	if val, ok := conf.Data[skipAccessLogUrls]; ok {
		delete(conf.Data, skipAccessLogUrls)
		skipUrls = strings.Split(val, ",")
	}
	if val, ok := conf.Data[whitelistSourceRange]; ok {
		delete(conf.Data, whitelistSourceRange)
		whitelist = append(whitelist, strings.Split(val, ",")...)
	}

	to := config.Configuration{}
	to.Backend = defaults.Backend{
		CustomHTTPErrors:     filterErrors(errors),
		SkipAccessLogURLs:    skipUrls,
		WhitelistSourceRange: whitelist,
	}
	def := config.NewDefault()
	if err := mergo.Merge(&to, def); err != nil {
		glog.Warningf("unexpected error merging defaults: %v", err)
	}

	metadata := &mapstructure.Metadata{}
	decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
		TagName:          "structs",
		Result:           &to,
		WeaklyTypedInput: true,
		Metadata:         metadata,
	})

	err = decoder.Decode(conf.Data)
	if err != nil {
		glog.Infof("%v", err)
	}
	return to
}

func filterErrors(codes []int) []int {
	var fa []int
	for _, code := range codes {
		if code > 299 && code < 600 {
			fa = append(fa, code)
		} else {
			glog.Warningf("error code %v is not valid for custom error pages", code)
		}
	}

	return fa
}

func fixKeyNames(data map[string]interface{}) map[string]interface{} {
	fixed := make(map[string]interface{})
	for k, v := range data {
		fixed[go_camelcase.Camelcase(k)] = v
	}
	return fixed
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;

namespace IFramework.Log4Net
{
    internal static class ArrayHelper
    {
        internal static T[] Empty<T>()
        {
            return EmptyArray<T>.Instance;
        }

        private static class EmptyArray<T>
        {
            internal static readonly T[] Instance = new T[0];
        }
    }

    internal static class FormatHelper
    {
        /// Convert object to string
        /// <param name="o">value</param>
        /// <param name="formatProvider">format for conversion.</param>
        /// <returns></returns>
        /// <remarks>
        ///     If <paramref name="formatProvider" /> is <c>null</c> and <paramref name="o" /> isn't a
        ///     <see cref="T:System.String" /> already, then the <see cref="T:NLog.LogFactory" /> will get a locked by
        ///     <see cref="P:NLog.LogManager.Configuration" />
        /// </remarks>
        internal static object Convert(object o, IFormatProvider formatProvider)
        {
            if (formatProvider == null && !(o is string))
            {
                if (o is IEnumerable<KeyValuePair<string, object>> keyValuePairs)
                {
                    return o is Dictionary<string, object> ? o : keyValuePairs.ToDictionary(kv => kv.Key, kv => kv.Value);
                }
                formatProvider = CultureInfo.DefaultThreadCurrentCulture;
            }
            return System.Convert.ToString(o, formatProvider);
        }
    }

    ///
    ///     Async version of <see cref="T:NLog.NestedDiagnosticsContext" /> - a logical context structure that keeps a stack
    ///     Allows for maintaining scope across asynchronous tasks and call contexts.
    ///
    public static class NestedDiagnosticsLogicalContext
    {
        private static readonly AsyncLocal<INestedContext> AsyncNestedDiagnosticsContext = new AsyncLocal<INestedContext>();

        /// Pushes the specified value on current stack
        /// <param name="value">The value to be pushed.</param>
        /// <returns>
        ///     An instance of the object that implements IDisposable that returns the stack to the previous level when
        ///     IDisposable.Dispose() is called. To be used with C# using() statement.
        /// </returns>
        public static IDisposable Push<T>(T value)
        {
            var nestedContext = new NestedContext<T>(GetThreadLocal(), value);
            SetThreadLocal(nestedContext);
            return nestedContext;
        }

        /// Pops the top message off the NDLC stack.
        /// <returns>The top message which is no longer on the stack.</returns>
        /// <remarks>this methods returns a object instead of string, this because of backwardscompatibility</remarks>
        public static object Pop()
        {
            return PopObject();
        }

        /// Pops the top message from the NDLC stack.
        /// <param name="formatProvider">The <see cref="T:System.IFormatProvider" /> to use when converting the value to a string.</param>
        /// <returns>The top message, which is removed from the stack, as a string value.</returns>
        public static object Pop(IFormatProvider formatProvider)
        {
            return FormatHelper.Convert(PopObject() ?? string.Empty, formatProvider);
        }

        /// Pops the top message off the current NDLC stack
        /// <returns>The object from the top of the NDLC stack, if defined; otherwise <c>null</c>.</returns>
        public static object PopObject()
        {
            var threadLocal = GetThreadLocal();
            if (threadLocal != null)
            {
                SetThreadLocal(threadLocal.Parent);
            }
            return threadLocal?.Value;
        }

        /// Peeks the top object on the current NDLC stack
        /// <returns>The object from the top of the NDLC stack, if defined; otherwise <c>null</c>.</returns>
        public static object PeekObject()
        {
            var nestedContext = PeekContext(false);
            return nestedContext?.Value;
        }

        /// Peeks the current scope, and returns its start time
        /// <returns>Scope Creation Time</returns>
        internal static DateTime PeekTopScopeBeginTime()
        {
            var nestedContext = PeekContext(false);
            return new DateTime(nestedContext?.CreatedTimeUtcTicks ?? DateTime.MinValue.Ticks, DateTimeKind.Utc);
        }

        /// Peeks the first scope, and returns its start time
        /// <returns>Scope Creation Time</returns>
        internal static DateTime PeekBottomScopeBeginTime()
        {
            var nestedContext = PeekContext(true);
            return new DateTime(nestedContext?.CreatedTimeUtcTicks ?? DateTime.MinValue.Ticks, DateTimeKind.Utc);
        }

        private static INestedContext PeekContext(bool bottomScope)
        {
            var nestedContext = GetThreadLocal();
            if (nestedContext == null)
            {
                return null;
            }
            if (bottomScope)
            {
                while (nestedContext.Parent != null)
                {
                    nestedContext = nestedContext.Parent;
                }
            }
            return nestedContext;
        }

        /// Clears current stack.
        public static void Clear()
        {
            SetThreadLocal(null);
        }

        /// Gets all messages on the stack.
        /// <returns>Array of strings on the stack.</returns>
        public static object[] GetAllMessages()
        {
            return GetAllMessages(null);
        }

        ///
        ///     Gets all messages from the stack, without removing them.
        ///
        /// <param name="formatProvider">The <see cref="T:System.IFormatProvider" /> to use when converting a value to a string.</param>
        /// <returns>Array of strings.</returns>
        public static object[] GetAllMessages(IFormatProvider formatProvider)
        {
            return GetAllObjects().Select(o => FormatHelper.Convert(o, formatProvider)).Reverse().ToArray();
        }

        ///
        ///     Gets all objects on the stack. The objects are not removed from the stack.
        ///
        /// <returns>Array of objects on the stack.</returns>
        public static object[] GetAllObjects()
        {
            var nestedContext = GetThreadLocal();
            if (nestedContext == null)
            {
                return ArrayHelper.Empty<object>();
            }
            var num = 0;
            var objArray = new object[nestedContext.FrameLevel];
            for (; nestedContext != null; nestedContext = nestedContext.Parent)
            {
                objArray[num++] = nestedContext.Value;
            }
            return objArray;
        }

        private static void SetThreadLocal(INestedContext newValue)
        {
            AsyncNestedDiagnosticsContext.Value = newValue;
        }

        private static INestedContext GetThreadLocal()
        {
            return AsyncNestedDiagnosticsContext.Value;
        }

        private interface INestedContext : IDisposable
        {
            INestedContext Parent { get; }

            int FrameLevel { get; }

            object Value { get; }

            long CreatedTimeUtcTicks { get; }
        }

        private class NestedContext<T> : INestedContext, IDisposable
        {
            private int _disposed;

            public NestedContext(INestedContext parent, T value)
            {
                Parent = parent;
                Value = value;
                CreatedTimeUtcTicks = DateTime.UtcNow.Ticks;
                FrameLevel = parent?.FrameLevel + 1 ?? 1;
            }

            public T Value { get; }

            public INestedContext Parent { get; }

            object INestedContext.Value => Value;

            public long CreatedTimeUtcTicks { get; }

            public int FrameLevel { get; }

            void IDisposable.Dispose()
            {
                if (Interlocked.Exchange(ref _disposed, 1) == 1)
                {
                    return;
                }
                PopObject();
            }

            public override string ToString()
            {
                // ISSUE: variable of a boxed type
                var local = (object) Value;
                return local?.ToString() ?? "null";
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/Fragment_OnDevice_CommonRecycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"/>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/Fragment_OnDevice_Loading"
        android:visibility="gone">
        <com.pnikosis.materialishprogress.ProgressWheel
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_gravity="center"
            app:matProg_barColor="@color/colorPrimary"
            app:matProg_progressIndeterminate="true" />
    </FrameLayout>
</FrameLayout>


text:
package org.ipso.lbc.common.db.dao;

public class MySQLSuperDAOConfigurationBuilder extends ServerBasedDatabaseSuperDAOConfigurationBuilder {
    @Override
    protected String getDefaultPort() {
        return "3306";
    }

    @Override
    protected String getDefaultDatabaseName() {
        return "test";
    }

    @Override
    protected String getDefaultUsername() {
        return "root";
    }

    @Override
    protected String getDefaultDriverClass() {
        return "com.mysql.jdbc.Driver";
    }

    @Override
    protected String getDefaultSqlDialect() {
        return "org.hibernate.dialect.MySQLDialect";
    }

    @Override
    protected String getDefaultJdbcDriverId() {
        return "mysql";
    }
}


text:
namespace DataConnect.Infrastructure.Fit.RawData
{
    internal class SlaveDeviceTarget : BaseRawValue
    {

        public SlaveDeviceTarget(long id) : base(id)
        {
        }
    }
}


text:
package ua.khpi.oop.pavlova07;

import java.util.ArrayList;

import ua.khpi.oop.pavlova03.TextUtil;

/**
 * Class HotelGuest is used for creating domain-objects by the specific
 * variant. In this class information about one guest in a hotel is stored.
 *
 * @param DEFAULT_GUEST_NAME_SURNAME
 *            is a value for name and surname of the guest in a default case.
 * @param DEFAULT_GUEST_BIRTH
 *            is a value for the date of birth of the guest in a default case.
 * @param DEFAULT_GUEST_COUNTRY_CITY
 *            is a value for the counrty and the city where the guestis from in
 *            a default case.
 * @param DEFAULT_GUEST_PASSPORT_NUM
 *            is a value of the guest's passport number in a default case.
 * @param DEFAULT_DATE_OF_ARRIVAL
 *            is a value for the guest's date of arrival in a default case.
 * @param DEFAULT_DATE_OF_EVICTION
 *            is a value for the guest's date of eviction in a default case.
 * @param DEFAULT_ROOM_NUM
 *            is a value for the guest's room number in a default case.
 *
 * @param DEFAULT_ROOM_CLASS
 *            is a type of room
 * @param DEFAULT_ROOM_PLACES_NUM
 *            is a value of places in the specific room
 * @param DEFAULT_REASON_OF_ARRIVAL
 *            is a line where the reason of coming to the hotel is described
 * @param LINES_SEPARATOR
 *            is a separator for getting serialized data in lines
 * @param DATA_SEPARATOR
 *            is a separator for getting exactly useful data from a line (in one
 *            line the description of the data and data itself are written both)
 * @param guestNameSurname
 *            is data about guest's name and surname, that is written in the
 *            object
 * @param guestDateOfBirth
 *            is data about guest's date of birth, that is written in the object
 * @param guestMotherland
 *            is data about country and city where the guest is from, that is
 *            written ia the object
 * @param guestPassport
 *            is data about guest's passport number, that is wrritten in the
 *            object
 * @param dateOfArrival
 *            is data about the date when the guest arrived to the hotel, that
 *            is wriiten in the object
 * @param dateOfEviction
 *            is data about the date when the guest left the hotel, that is
 *            wriiten in the object
 * @param roomNum
 *            is data about the number of a room, where the guest lived, that is
 *            written in the object
 * @param roomClass
 *            is data about the state of the room where the guest lived, that is
 *            written in the object
 * @param roomPlaces
 *            is data about number of places in the room the guest lived, that
 *            is written in the object
 * @param reasonOfArrival
 *            is data with description of the reason of coming to the hotel,
 *            that is written in the object
 * @author pavlova-mv
 *
 */
public class HotelGuest {
	private static final String DEFAULT_GUEST_NAME_SURNAME = "Петренко А.Л.";
	private static final String DEFAULT_GUEST_BIRTH = "01-Сент-1987";
	private static final String DEFAULT_GUEST_COUNTRY_CITY = "Украина, Львов";
	private static final String DEFAULT_GUEST_PASSPORT_NUM = "МТ-589647";

	private static final String DEFAULT_DATE_OF_ARRIVAL = "03-Март-2017";
	private static final String DEFAULT_DATE_OF_EVICTION = "18-Март-2017";

	private static final String DEFAULT_ROOM_NUM = "234";
	private static final String DEFAULT_ROOM_CLASS = "Эконом";
	private static final String DEFAULT_ROOM_PLACES_NUM = "1";

	private static final String DEFAULT_REASON_OF_ARRIVAL = "Турист";

	private static final String LINES_SEPARATOR = "\n";
	private static final String DATA_SEPARATOR = ":";

	private String guestNameSurname;
	private String guestDateOfBirth;
	private String guestMotherland;
	private String guestPassport;
	private String dateOfArrival;
	private String dateOfEviction;
	private String roomNum;
	private String roomClass;
	private String roomPlaces;
	private String reasonOfArrival;

	public HotelGuest() {
		setGuestNameSurname(DEFAULT_GUEST_NAME_SURNAME);
		setGuestDateOfBirth(DEFAULT_GUEST_BIRTH);
		setGuestMotherland(DEFAULT_GUEST_COUNTRY_CITY);
		setGuestPassport(DEFAULT_GUEST_PASSPORT_NUM);
		setDateOfArrival(DEFAULT_DATE_OF_ARRIVAL);
		setDateOfEviction(DEFAULT_DATE_OF_EVICTION);
		setRoomNum(DEFAULT_ROOM_NUM);
		setRoomClass(DEFAULT_ROOM_CLASS);
		setRoomPlaces(DEFAULT_ROOM_PLACES_NUM);
		setReasonOfArrival(DEFAULT_REASON_OF_ARRIVAL);
	}

	public HotelGuest(String guestNameSurname, String guestDateOfBirth, String guestMotherland, String guestPassport,

			String dateOfArrival, String dateOfEviction, String roomNum, String roomClass, String roomPlaces,
			String reasonOfArrival) {
		this.setGuestNameSurname(guestNameSurname);
		this.setGuestDateOfBirth(guestDateOfBirth);
		this.setGuestMotherland(guestMotherland);
		this.setGuestPassport(guestPassport);
		this.setDateOfArrival(dateOfArrival);
		this.setDateOfEviction(dateOfEviction);
		this.setRoomNum(roomNum);
		this.setRoomClass(roomClass);
		this.setRoomPlaces(roomPlaces);
		this.setReasonOfArrival(reasonOfArrival);
	}

	/**
	 * @return the guestNameSurname
	 */
	public String getGuestNameSurname() {
		return guestNameSurname;
	}

	/**
	 * @param guestNameSurname
	 *            the guestNameSurname to set
	 */
	public void setGuestNameSurname(String guestNameSurname) {
		this.guestNameSurname = new String(guestNameSurname);
	}

	/**
	 * @return the guestDateOfBirth
	 */
	public String getGuestDateOfBirth() {
		return guestDateOfBirth;
	}

	/**
	 * @param guestDateOfBirth
	 *            the guestDateOfBirth to set
	 */
	public void setGuestDateOfBirth(String guestDateOfBirth) {
		this.guestDateOfBirth = guestDateOfBirth;
	}

	/**
	 * @return the guestMotherland
	 */
	public String getGuestMotherland() {
		return guestMotherland;
	}

	/**
	 * @param guestMotherland
	 *            the guestMotherland to set
	 */
	public void setGuestMotherland(String guestMotherland) {
		this.guestMotherland = guestMotherland;
	}

	/**
	 * @return the guestPassport
	 */
	public String getGuestPassport() {
		return guestPassport;
	}

	/**
	 * @param guestPassport
	 *            the guestPassport to set
	 */
	public void setGuestPassport(String guestPassport) {
		this.guestPassport = guestPassport;
	}

	/**
	 * @return the dateOfArrival
	 */
	public String getDateOfArrival() {
		return dateOfArrival;
	}

	/**
	 * @param dateOfArrival
	 *            the dateOfArrival to set
	 */
	public void setDateOfArrival(String dateOfArrival) {
		this.dateOfArrival = dateOfArrival;
	}

	/**
	 * @return the dateOfEviction
	 */
	public String getDateOfEviction() {
		return dateOfEviction;
	}

	/**
	 * @param dateOfEviction
	 *            the dateOfEviction to set
	 */
	public void setDateOfEviction(String dateOfEviction) {
		this.dateOfEviction = dateOfEviction;
	}

	/**
	 * @return the roomNum
	 */
	public String getRoomNum() {
		return roomNum;
	}

	/**
	 * @param roomNum
	 *            the roomNum to set
	 */
	public void setRoomNum(String roomNum) {
		this.roomNum = roomNum;
	}

	/**
	 * @return the roomClass
	 */
	public String getRoomClass() {
		return roomClass;
	}

	/**
	 * @param roomClass
	 *            the roomClass to set
	 */
	public void setRoomClass(String roomClass) {
		this.roomClass = roomClass;
	}

	/**
	 * @return the roomPlaces
	 */
	public String getRoomPlaces() {
		return roomPlaces;
	}

	/**
	 * @param roomPlaces
	 *            the roomPlaces to set
	 */
	public void setRoomPlaces(String roomPlaces) {
		this.roomPlaces = roomPlaces;
	}

	/**
	 * @return the reasonOfArrival
	 */
	public String getReasonOfArrival() {
		return reasonOfArrival;
	}

	/**
	 * @param reasonOfArrival
	 *            the reasonOfArrival to set
	 */
	public void setReasonOfArrival(String reasonOfArrival) {
		this.reasonOfArrival = reasonOfArrival;
	}

	/**
	 * Method toString creates a line from an object
	 *
	 * @return string with full data of an object
	 */
	public String toString() {
		StringBuilder temp = new StringBuilder();
		temp.append(this.guestNameSurname + "\n" + this.guestDateOfBirth + "\n" + this.guestMotherland + "\n"
				+ this.guestPassport + "\n\tДата заселения в номер: " + this.dateOfArrival + "\n\tДата выселения: "
				+ this.dateOfEviction + "\n\tНомер: " + this.roomNum + "\n\tКласс: " + this.roomClass
				+ "\n\tКоличество мест: " + this.roomPlaces + "\n\tПричина приезда: " + this.reasonOfArrival
				+ "\n\n\n");
		String info = new String(temp);
		return info;
	}

	/**
	 * Method toObject creates an object from a line
	 *
	 * @param info
	 *            is a line with full information about an object
	 * @return new object
	 *
	 * @see TextUtil
	 */
	public static HotelGuest toObject(String info) {
		ArrayList<String> inLines = (ArrayList<String>) TextUtil.extractElementsFromText(info, LINES_SEPARATOR);
		String[] inArray = new String[10];
		int i;

		for (i = 0; i < 4; i++)
			inArray[i] = inLines.get(i);

		for (i = 4; i < 10; i++) {
			ArrayList<String> twoHalves = (ArrayList<String>) TextUtil.extractElementsFromText(inLines.get(i),
					DATA_SEPARATOR);
			inArray[i] = twoHalves.get(1);
		}
		HotelGuest newObject = new HotelGuest(inArray[0], inArray[1], inArray[2], inArray[3], inArray[4], inArray[5],
				inArray[6], inArray[7], inArray[8], inArray[9]);
		return newObject;
	}
}


text:
package me.zhengjie.domain;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;

/**
 * @author Zheng Jie
 * @date 2018-11-24
 */
@Entity
@Getter
@Setter
@Table(name = "sys_log")
@NoArgsConstructor
public class Log  implements Serializable {

    @Id
    @Column(name = "log_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /** 操作用户 */
    private String username;

    /** 描述 */
    private String description;

    /** 方法名 */
    private String method;

    /** 参数 */
    private String params;

    /** 日志类型 */
    private String logType;

    /** 请求ip */
    private String requestIp;

    /** 地址 */
    private String address;

    /** 浏览器  */
    private String browser;

    /** 请求耗时 */
    private Long time;

    /** 异常详细  */
    private byte[] exceptionDetail;

    /** 创建日期 */
    @CreationTimestamp
    private Timestamp createTime;

    public Log(String logType, Long time) {
        this.logType = logType;
        this.time = time;
    }
}


text:
from flask.ext.sandboy import Sandboy
from flask import current_app, request

from .profile import Profile
from .service import Service
from .notification import Notification
from flask.ext.pushrod import pushrod_view

class APIScaffold(object):
    def init_app(self, app, db, auth):
        """
        request.path:
            - /profile/42 == ['','profile','42']
            - /profile == ['','profile']

        """
        def get_jinja_template():
            parts = request.path.rsplit('/')
            tpl = parts[1] + '.html'

            current_app.logger.debug(
                'pushrod retrieving jinja template=%s for path=%s' %
                (tpl, request.path))
            return tpl

        def get_vcard_template():
            parts = request.path.rsplit('/')
            if len(parts) == 2:
                return NotImplemented

            tpl = parts[1] + '.vcard'

            current_app.logger.debug(
                'pushrod retrieving vcard template=%s for path=%s' %
                (tpl, request.path))
            return tpl

        decorators = [
            auth.login_required,
            pushrod_view(jinja_template=get_jinja_template, vcard_template=get_vcard_template)
        ]

        sandboy = Sandboy(app, db, [Profile, Service, Notification],
                          decorators=decorators,
                          renderer=None)
        return sandboy