text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2016 LinkedIn Corp.

  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy of
  the License at

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

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

<!-- General configurations -->
<configuration>
  <property>
    <name>autotuning.enabled</name>
    <value>true</value>
    <description>Auto Tuning is enabled or not</description>
  </property>
  <property>
    <name>autotuning.default.allowed_max_resource_usage_percent</name>
    <value>150</value>
    <description>Default value for allowed max resource usage percent</description>
  </property>
  <property>
    <name>autotuning.default.allowed_max_execution_time_percent</name>
    <value>150</value>
    <description>Default value for allowed max execution time percent</description>
  </property>
  <property>
    <name>autotuning.daemon.wait.interval.ms</name>
    <value>600</value>
    <description>Auto tuning daemon wait interval</description>
  </property>
  <property>
    <name>baseline.execution.count</name>
    <value>30</value>
    <description>Baseline to be done on recent number of execution</description>
  </property>
  <property>
    <name>fitness.compute.wait_interval.ms</name>
    <value>0</value>
    <description>Wait time after the job is completed till fitness is computer</description>
  </property>
  <property>
    <name>dr.elephant.api.url</name>
    <value>http://ltx1-holdemdre01.grid.linkedin.com:8080</value>
    <description>API URL for Dr Elephant</description>
  </property>
  <!--The below property is optional-->
  <!--<property>-->
  <!--<name>python.path</name>-->
  <!--<value>/path/to/python/binary</value>-->
  <!--<description>Root directory for python</description>-->
  <!--</property>-->
</configuration>


text:
#import "AAPLLocalListCoordinator.h"
#import "AAPLListUtilities.h"
#import "AAPLAppConfiguration.h"

@interface AAPLLocalListCoordinator ()

@property (nonatomic, strong) NSPredicate *predicate;

@end

@implementation AAPLLocalListCoordinator
@synthesize delegate = _delegate;

#pragma mark - Initializers

- (instancetype)initWithPredicate:(NSPredicate *)predicate {
    self = [super init];

    if (self) {
        _predicate = predicate;
    }

    return self;
}

- (instancetype)initWithPathExtension:(NSString *)pathExtension {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(pathExtension = %@)", pathExtension];

    self = [self initWithPredicate:predicate];

    if (self) {
        // No need for additional initialization.
    }

    return self;
}

- (instancetype)initWithLastPathComponent:(NSString *)lastPathComponent {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(lastPathComponent = %@)", lastPathComponent];

    self = [self initWithPredicate:predicate];

    if (self) {
        // No need for additional initialization.
    }

    return self;
}

#pragma mark - AAPLListCoordinator

- (void)startQuery {
    dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);

    dispatch_async(defaultQueue, ^{
        NSFileManager *fileManager = [NSFileManager defaultManager];

        // Fetch the list documents from container documents directory.
        NSArray *localDocumentURLs = [fileManager contentsOfDirectoryAtURL:[AAPLListUtilities localDocumentsDirectory] includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsPackageDescendants error:nil];

        NSArray *localListURLs = [localDocumentURLs filteredArrayUsingPredicate:self.predicate];

        if (localListURLs.count > 0) {
            [self.delegate listCoordinatorDidUpdateContentsWithInsertedURLs:localListURLs removedURLs:@[] updatedURLs:@[]];
        }
    });
}

- (void)stopQuery {
    // Nothing to do here since the documents are local and everything gets funnelled this class
    // if the storage is local.
}

- (void)removeListAtURL:(NSURL *)URL {
    [AAPLListUtilities removeListAtURL:URL withCompletionHandler:^(NSError *error) {
        if (error) {
            [self.delegate listCoordinatorDidFailRemovingListAtURL:URL withError:error];
        }
        else {
            [self.delegate listCoordinatorDidUpdateContentsWithInsertedURLs:@[] removedURLs:@[URL] updatedURLs:@[]];
        }
    }];
}

- (void)createURLForList:(AAPLList *)list withName:(NSString *)name {
    NSURL *documentURL = [self documentURLForName:name];

    [AAPLListUtilities createList:list atURL:documentURL withCompletionHandler:^(NSError *error) {
        if (error) {
            [self.delegate listCoordinatorDidFailCreatingListAtURL:documentURL withError:error];
        }
        else {
            [self.delegate listCoordinatorDidUpdateContentsWithInsertedURLs:@[documentURL] removedURLs:@[] updatedURLs:@[]];
        }
    }];
}

- (BOOL)canCreateListWithName:(NSString *)name {
    if (name.length <= 0) {
        return NO;
    }

    NSURL *documentURL = [self documentURLForName:name];

    return ![[NSFileManager defaultManager] fileExistsAtPath:documentURL.path];
}

#pragma mark - Convenience

- (NSURL *)documentURLForName:(NSString *)name {
    NSURL *documentURLWithoutExtension = [[AAPLListUtilities localDocumentsDirectory] URLByAppendingPathComponent:name];

    return [documentURLWithoutExtension URLByAppendingPathExtension:AAPLAppConfigurationListerFileExtension];
}

@end

redpajama_set_name: RedPajamaGithub


text:
GFXGeneralFence::~GFXGeneralFence()
{
   // Release the ref pointers
   mRenderTarget = NULL;
   mRTTexHandle = NULL;

   // Unregister texture callback
   GFXTextureManager::removeEventDelegate( this, &GFXGeneralFence::_onTextureEvent );
}

//------------------------------------------------------------------------------

void GFXGeneralFence::_init()
{
   // Register texture callback to re-create resources
   if ( !mInitialized )
      GFXTextureManager::addEventDelegate( this, &GFXGeneralFence::_onTextureEvent );

   // Set this to true for error checking
   mInitialized = true;

   // Allocate resources
   mInitialized &= mRTTexHandle.set( 2, 2, GFXFormatR8G8B8X8, &GFXRenderTargetProfile, avar("%s() - mInitialized (line %d)", __FUNCTION__, __LINE__) );
   mRenderTarget = GFX->allocRenderToTextureTarget();
   mInitialized &= ( mRenderTarget != NULL );

   GFXStateBlockDesc d;
   mRenderSB = GFX->createStateBlock(d);
}

//------------------------------------------------------------------------------

void GFXGeneralFence::issue()
{
   PROFILE_SCOPE(GFXGeneralFence_Issue);

   // Resource creation will be done on first call to issue()
   if( !mInitialized )
      _init();

   // If we can't init, return.
   if(!mInitialized)
      return;

   AssertFatal( mInitialized, "Error occured during GFXGeneralFence::_init, sorry I can't be more specific, break and debug." );

   RectI viewport = GFX->getViewport();

   GFX->pushActiveRenderTarget();
   mRenderTarget->attachTexture( GFXTextureTarget::Color0, mRTTexHandle );
   GFX->setActiveRenderTarget( mRenderTarget );

   // Set-up states
   GFX->setStateBlock(mRenderSB);
   GFX->pushWorldMatrix();
   GFX->setWorldMatrix( MatrixF::Identity );

   // CodeReview: We can re-do this with a static vertex buffer at some point. [5/9/2007 Pat]
   PrimBuild::begin( GFXTriangleList, 3 );
      PrimBuild::vertex2f( 0.f, 0.f );
      PrimBuild::vertex2f( 0.f, 1.f );
      PrimBuild::vertex2f( 1.f, 0.f );
   PrimBuild::end();

   GFX->popWorldMatrix();
   GFX->popActiveRenderTarget();

   GFX->setViewport(viewport);
}

//------------------------------------------------------------------------------

void GFXGeneralFence::block()
{
   PROFILE_SCOPE(GFXGeneralFence_block);
   if( !mInitialized )
      return;

   // We have to deal with the case where the lock fails (usually due to
   // a device reset).
   if(mRTTexHandle.lock())
      mRTTexHandle.unlock();
}

void GFXGeneralFence::_onTextureEvent( GFXTexCallbackCode code )
{
   switch( code )
   {
   case GFXZombify:
      mRTTexHandle = NULL;
      break;

   case GFXResurrect:
      mRTTexHandle.set( 2, 2, GFXFormatR8G8B8X8, &GFXRenderTargetProfile, avar("%s() - GFXGeneralFence->mRTTexHandle (line %d)", __FUNCTION__, __LINE__) );
      break;
   }
}

void GFXGeneralFence::zombify()
{
   mRTTexHandle = NULL;
}

void GFXGeneralFence::resurrect()
{
   mRTTexHandle.set( 2, 2, GFXFormatR8G8B8X8, &GFXRenderTargetProfile, avar("%s() - mRTTexHandle (line %d)", __FUNCTION__, __LINE__) );
}

const String GFXGeneralFence::describeSelf() const
{
   // We've got nothing
   return String();
}


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Management and Approval Regulations for Hong Kong and Macao Residents with Overseas Chinese I.D.</英文法規名稱>
<中文法規名稱>取得華僑身分香港澳門居民聘僱及管理辦法</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=N0090008</法規網址>
<最新英文異動日期>20150921</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件 />
<沿革內容><![CDATA[1.Developed pursuant to the official act of (86) Tai-Lao-Zhi-Wai-Tze No. 0901368 of Council of Labor Affairs, Executive Yuan, dated June 28, 1997 and announced 14 articles
2.Amended and promulgated the contents of 8th, 10th, 12th and 14th Articles by the order of Council of Labor Affairs, Executive Yuan (90) Tai-Lao-Zhi-Wai-Tze No. 0225163 on November 28, 2001
3.Amended and promulgated the contents of 5th, 7th to 10th Articles and deleted the 12th Article by the order of Council of Labor Affairs, Executive Yuan (93) Tai-Lao-Zhi-Wai-Tze No. 0930207938 on December 22, 2004
4.Amended and promulgated the contents of 8th Article by the order of Council of Labor Affairs, Executive Yuan (98) Tai-Lao-Zhi-Wai-Tze No. 0980506912 on April 29, 2009
5.Amended on September 21, 2015]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[The present Regulations are stipulated based on the second paragraph of Article 13 of Regulations Governing the Relations with Hong Kong and Macao (the Regulations).]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The present Regulations are applied to residents of Hong Kong and Macau, who have obtained the status of overseas Chinese prior to the end of British or Portuguese rule, as the case may be, and those of their spouses and children who meet the requirements for obtaining Republic of China nationality.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[The authority of this implementation rule is Ministry of Labour.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[For employment of workers mentioned in Article 2, the employer should apply for permit from the Competent Authority.
People mentioned in Article 2, who are allowed to reside in Taiwan, can apply for permit on their own initiatives without their employers' initiation.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[When an employer employs workers mentioned in Article 2 to work in Taiwan, the employer doesn't have to abide the first paragraph of Article 46, Article 47, Article 52, Article 53, Article 56 and the first paragraph of Article 74 of Employment Service Act, the employer is also exempt from paying Employment Security Fees as required by Article 55.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[When an employer employs the workers mentioned in Article 2, their maximum of working period is three years; If the employer need to continue the employment after due period, the employer must apply for extension of working periods, and each extension should be only one year.
For the workers mentioned in second paragraph of Article 4 are permitted to work, their valid working period should be the same as their residence period; when their residence periods are due and have to work longer, they should apply for permission from the Competent Authority based on second paragraph of Article 7 when their residence periods are allowed and extended.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 7</條號>
    <條文內容><![CDATA[The employer should prepare the following documents to apply for employment permit from the Competent Authority:
1. Application form(s).
2. Photocopy of the national identity card of the Applicant Employer or the person in charge of the Applicant Company, the certificates of the company registration, business registration, factory registration, and that of the license for specially permitted businesses. But those are exempted if so provided for in other laws or regulations.
3. The health certificate for the employee issued in recent 3 months by the hospitals in Taiwan, Hong Kong Region or Makau Region which are authorised and appointed by Central Health and Welfare's Authority
4. Overseas compatriot identity certificates of the employed people and other documents which prove their spouses and children meet the requirements for obtaining Republic of China nationality.
5. Contract of labor or employment.
6. Original of the receipt for examination fee.
7. Other documents as may be required by the Competent Authorities.
People mentioned in second paragraph of Article 4 should prepare the photocopy of their residence certificates and the documents mentioned in preceding subparagraph 1, subparagraph 4, subparagraph 6 and subparagraph 7 to apply for permit from the Competent Authorities.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 8</條號>
    <條文內容><![CDATA[The Health Checkup mentioned in the Regulations should include the following:
1. Chest X-ray for tuberculosis.
2. Syphilis test.
3. Stool examination in concentration method for parasites (including Entameba Histolytica).
4. Regular physical checkup (including mental status checkup).
5. Examination for Hanses's Disease.
According to the Article 2 regulating the personnel's working status and the epidemic situation in Hong Kong Region and Macau Region, the Central Health and Welfare's Authority shall issue a declaration to add, delete or alter the above-mentioned health examination subjects.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 9</條號>
    <條文內容><![CDATA[Should any of the following events occur when applying for permit based on the regulation in Article 4 and Article 7, the Competent Authorities should not allow the application:
1. The documents submitted contain false or incomplete information.
2. Other unqualified application entries and are still not corrected after notification for correction.
3. People who fail the health checkup test. However, people have positive results in Hepatitis B Surface Antigen Test are not bound by this.
4. Serious violators of the present Regulations or other applicable regulations.
If the incomplete or unclear submission mentioned in the preceding subparagraph 1 can be corrected, the Competent Authorities should inform the applicants to make correction within the limitation period.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 10</條號>
    <條文內容><![CDATA[If the employer need to continue the employment, within 60-day period prior to the expiration of employment permit, the employer should prepare the following documents for filing the application for employment permit extension from the Competent Authorities:
1. Application form for employment permit extension
2. The original employment permit issued by the Competent Authorities
3. The health checkup certificate of the employed person within the latest three months
4. Contract of labor or employment.
5. Original of the receipt for examination fee.
6. Other documents as may be required by the Competent Authorities.
If all the entries in preceding paragraph are met, the Competent Authorities should issue the permit of working extension.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 11</條號>
    <條文內容><![CDATA[If the people mentioned in Article 2 have to transfer to a new employer or be employed by more than two employers within the duration of employment permits, the new employer(s) should apply for permit; In case of transfer to a new employer, the new employer should submit upon such application the relevant document(s) certifying the termination of the previous employment.
When the workers mentioned in second paragraph of Article 4 have to transfer to a new employer or be employed by more than two employers, they are not restricted by the preceding paragraph.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 12</條號>
    <條文內容><![CDATA[(Deleted)]]></條文內容>
  </條文>
  <條文>
    <條號>Article 13</條號>
    <條文內容><![CDATA[The form and format of the present Regulations should be stipulated by the Competent Authorities with another order.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 14</條號>
    <條文內容><![CDATA[The present Regulations shall enter into force as of the date of promulgation. When the proviso in Article 62 happens, the Regulation shall enter into force partially or wholly as of the date of promulgation.
The Amendment to the Regulations shall enter into force upon its date of promulgation.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
using Microsoft.SharePoint;

namespace GSoft.Dynamite.Examples.Branding
{
    /// <summary>
    /// Web-level Branding event receiver that changes the site's master page
    /// </summary>
    public class WebEventReceiver : SPWebEventReceiver
    {
        /// <summary>
        /// Fires when a new web is created and changes the site's main and custom master page
        /// </summary>
        /// <param name="properties">The context</param>
        public override void WebProvisioned(SPWebEventProperties properties)
        {
            SPWeb site = properties.Web;
            SPWeb rootSite = site.Site.RootWeb;
            site.MasterUrl = rootSite.MasterUrl;
            site.CustomMasterUrl = rootSite.CustomMasterUrl;
            site.Update();
        }
    }
}


text: google-site-verification: google7a3a134684db3f75.html


text:
title: Why are my requests not being traced?
weight: 30
---

Since Istio 1.0.3, the sampling rate for tracing has been reduced to 1% in the `default`
[configuration profile](/docs/setup/additional-setup/config-profiles/).
This means that only 1 out of 100 trace instances captured by Istio will be reported to the tracing backend.
The sampling rate in the `demo` profile is still set to 100%. See
[this section](/docs/tasks/observability/distributed-tracing/mesh-and-proxy-config/#customizing-trace-sampling)
for more information on how to set the sampling rate.

If you still do not see any trace data, please confirm that your ports conform to the Istio [port naming conventions](/about/faq/#naming-port-convention) and that the appropriate container port is exposed (via pod spec, for example) to enable
traffic capture by the sidecar proxy (Envoy).

If you only see trace data associated with the egress proxy, but not the ingress proxy, it may still be related to the Istio [port naming conventions](/about/faq/#naming-port-convention). Starting with [Istio 1.3](/news/releases/1.3.x/announcing-1.3/#intelligent-protocol-detection-experimental) the protocol for **outbound** traffic is automatically detected.


text:
local common = require('test_scripts/API/Restructuring_OnResetTimeout/common_OnResetTimeout')

--[[ Local Functions ]]
local function Alert(isSendingNotificationForUI, isSendingNotificationForTTS)
  local requestParams = {
    alertText1 = "alertText1",
    progressIndicator = true,
    duration = 3000,
    softButtons = {
      {
        softButtonID = 1,
        text = "Button",
        type = "TEXT",
        isHighlighted = false,
        systemAction = "DEFAULT_ACTION"
      }
    },
    ttsChunks = {
      { type = "TEXT",
        text = "pathToFile"
      }
    }
  }

  local cid = common.getMobileSession():SendRPC("Alert", requestParams)
  local requestTime = timestamp()

  common.getHMIConnection():ExpectRequest( "UI.Alert")
  :Do(function(_, data)
      if isSendingNotificationForUI == true then
        common.onResetTimeoutNotification(data.id, data.method, common.defaultTimeout + 5000)
      end
      local function sendresponse()
        common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
      end
      RUN_AFTER(sendresponse, common.defaultTimeout + 8000)
    end)

  common.getHMIConnection():ExpectRequest("TTS.Speak", {
      ttsChunks = requestParams.ttsChunks,
      speakType = "ALERT",
      appID = common.getHMIAppId()
    })
  :Do(function(_, data)
      if isSendingNotificationForTTS == true then
        common.onResetTimeoutNotification(data.id, data.method, common.defaultTimeout + 5000)
      end
      local function SpeakResponse()
        common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", { })
        common.getHMIConnection():SendNotification("TTS.Stopped")
      end
      RUN_AFTER(SpeakResponse, common.defaultTimeout + 7000)
    end)

  common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
  :Timeout(common.defaultTimeout + 9000)
  :ValidIf(function()
      if isSendingNotificationForTTS == true or isSendingNotificationForUI == true then
        return common.responseTimeCalculationFromMobReq(common.defaultTimeout + 8000, nil, requestTime)
      end
      return true
    end)
end

--[[ Scenario ]]
common.Title("Preconditions")
common.Step("Clean environment", common.preconditions)
common.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
common.Step("App registration", common.registerAppWOPTU)
common.Step("App activation", common.activateApp)

common.Title("Test")
common.Step("Send Alert with ttsChunks and softButton", Alert)
common.Step("Send Alert with softButton, ttsChunks and onResetTimeout notification for UI.Alert",
  Alert, { true, false })
common.Step("Send Alert with softButton, ttsChunks and onResetTimeout notification for TTS.Speak",
  Alert, { false, true })
common.Step("Send Alert with softButton, ttsChunks and onResetTimeout notification for TTS.Speak and UI.Alert" ,
  Alert, { true, true })

common.Title("Postconditions")
common.Step("Stop SDL", common.postconditions)


text:
#include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h"

#include "tensorflow_lite_support/cc/port/status_macros.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/vision/proto/bounding_box_proto_inc.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_utils.h"
#include "tensorflow_lite_support/cc/task/vision/utils/image_tensor_specs.h"

namespace tflite {
namespace task {
namespace processor {

namespace {
// Number of bytes required for 8-bit per pixel RGB color space.
static constexpr int kRgbPixelBytes = 3;

using ::tflite::task::vision::BoundingBox;
using ::tflite::task::vision::FrameBuffer;
}  // namespace

/* static */
tflite::support::StatusOr<std::unique_ptr<ImagePreprocessor>>
ImagePreprocessor::Create(
    core::TfLiteEngine* engine,
    const std::initializer_list<int> input_indices,
    const vision::FrameBufferUtils::ProcessEngine& process_engine) {
  ASSIGN_OR_RETURN(auto processor,
                   Processor::Create<ImagePreprocessor>(
                       /* num_expected_tensors = */ 1, engine, input_indices,
                       /* requires_metadata = */ false));

  RETURN_IF_ERROR(processor->Init(process_engine));
  return processor;
}

// Returns false if image preprocessing could be skipped, true otherwise.
bool ImagePreprocessor::IsImagePreprocessingNeeded(
    const FrameBuffer& frame_buffer,
    const BoundingBox& roi) {
  // Is crop required?
  if (roi.origin_x() != 0 || roi.origin_y() != 0 ||
      roi.width() != frame_buffer.dimension().width ||
      roi.height() != frame_buffer.dimension().height) {
    return true;
  }

  // Are image transformations required?
  if (frame_buffer.orientation() != FrameBuffer::Orientation::kTopLeft ||
      frame_buffer.format() != FrameBuffer::Format::kRGB ||
      frame_buffer.dimension().width != input_specs_.image_width ||
      frame_buffer.dimension().height != input_specs_.image_height) {
    return true;
  }

  return false;
}

absl::Status ImagePreprocessor::Init(
    const vision::FrameBufferUtils::ProcessEngine& process_engine) {
  frame_buffer_utils_ = vision::FrameBufferUtils::Create(process_engine);

  ASSIGN_OR_RETURN(input_specs_, vision::BuildInputImageTensorSpecs(
                                     *engine_->interpreter(),
                                     *engine_->metadata_extractor()));

  if (input_specs_.color_space != tflite::ColorSpaceType_RGB) {
    return tflite::support::CreateStatusWithPayload(
        absl::StatusCode::kUnimplemented,
        "ImagePreprocessor only supports RGB color space for now.");
  }

  // Determine if the input shape is resizable.
  const TfLiteIntArray* dims_signature = GetTensor()->dims_signature;

  // Some fixed-shape models do not have dims_signature.
  if (dims_signature != nullptr && dims_signature->size > 2) {
    // Only the HxW dimensions support mutability.
    is_height_mutable_ = dims_signature->data[1] == -1;
    is_width_mutable_ = dims_signature->data[2] == -1;
  }
  return absl::OkStatus();
}

absl::Status ImagePreprocessor::Preprocess(const FrameBuffer& frame_buffer) {
  BoundingBox roi;
  roi.set_width(frame_buffer.dimension().width);
  roi.set_height(frame_buffer.dimension().height);
  return Preprocess(frame_buffer, roi);
}

absl::Status ImagePreprocessor::Preprocess(const FrameBuffer& frame_buffer,
                                           const BoundingBox& roi) {
  // Input data to be normalized (if needed) and used for inference. In most
  // cases, this is the result of image preprocessing. In case no image
  // preprocessing is needed (see below), this points to the input frame
  // buffer raw data.
  const uint8* input_data;
  size_t input_data_byte_size;

  // Optional buffers in case image preprocessing is needed.
  std::unique_ptr<FrameBuffer> preprocessed_frame_buffer;
  std::vector<uint8> preprocessed_data;

  if (IsImagePreprocessingNeeded(frame_buffer, roi)) {
    // Preprocess input image to fit model requirements.
    // For now RGB is the only color space supported, which is ensured by
    // `InitInternal`.
    input_specs_.image_width =
        is_width_mutable_ ? roi.width() : input_specs_.image_width;
    input_specs_.image_height =
        is_height_mutable_ ? roi.height() : input_specs_.image_height;

    FrameBuffer::Dimension to_buffer_dimension = {input_specs_.image_width,
                                                  input_specs_.image_height};
    input_data_byte_size =
        GetBufferByteSize(to_buffer_dimension, FrameBuffer::Format::kRGB);
    preprocessed_data.resize(input_data_byte_size / sizeof(uint8), 0);
    input_data = preprocessed_data.data();

    FrameBuffer::Plane preprocessed_plane = {
        /*buffer=*/preprocessed_data.data(),
        /*stride=*/{input_specs_.image_width * kRgbPixelBytes, kRgbPixelBytes}};
    preprocessed_frame_buffer = FrameBuffer::Create(
        {preprocessed_plane}, to_buffer_dimension, FrameBuffer::Format::kRGB,
        FrameBuffer::Orientation::kTopLeft);

    RETURN_IF_ERROR(frame_buffer_utils_->Preprocess(
        frame_buffer, roi, preprocessed_frame_buffer.get()));
  } else {
    // Input frame buffer already targets model requirements: skip image
    // preprocessing. For RGB, the data is always stored in a single plane.
    input_data = frame_buffer.plane(0).buffer;
    input_data_byte_size = frame_buffer.plane(0).stride.row_stride_bytes *
                           frame_buffer.dimension().height;
  }

  // If dynamic, it will re-dim the entire graph as per the input.
  if (is_height_mutable_ || is_width_mutable_) {
    engine_->interpreter()->ResizeInputTensorStrict(
        0, {GetTensor()->dims->data[0], input_specs_.image_height,
            input_specs_.image_width, GetTensor()->dims->data[3]});

    engine_->interpreter()->AllocateTensors();
  }
  // Then normalize pixel data (if needed) and populate the input tensor.
  switch (input_specs_.tensor_type) {
    case kTfLiteUInt8:
      if (GetTensor()->bytes != input_data_byte_size) {
        return tflite::support::CreateStatusWithPayload(
            absl::StatusCode::kInternal,
            "Size mismatch or unsupported padding bytes between pixel data "
            "and input tensor.");
      }
      // No normalization required: directly populate data.
      RETURN_IF_ERROR(tflite::task::core::PopulateTensor(
          input_data, input_data_byte_size / sizeof(uint8), GetTensor()));
      break;
    case kTfLiteFloat32: {
      if (GetTensor()->bytes / sizeof(float) !=
          input_data_byte_size / sizeof(uint8)) {
        return tflite::support::CreateStatusWithPayload(
            absl::StatusCode::kInternal,
            "Size mismatch or unsupported padding bytes between pixel data "
            "and input tensor.");
      }
      // Normalize and populate.
      ASSIGN_OR_RETURN(
          float* normalized_input_data,
          tflite::task::core::AssertAndReturnTypedTensor<float>(GetTensor()));
      const tflite::task::vision::NormalizationOptions& normalization_options =
          input_specs_.normalization_options.value();
      for (int i = 0; i < normalization_options.num_values; i++) {
        if (std::abs(normalization_options.std_values[i]) <
            std::numeric_limits<float>::epsilon()) {
          return tflite::support::CreateStatusWithPayload(
              absl::StatusCode::kInternal,
              "NormalizationOptions.std_values can't be 0. Please check if the "
              "tensor metadata has been populated correctly.");
        }
      }
      if (normalization_options.num_values == 1) {
        float mean_value = normalization_options.mean_values[0];
        float inv_std_value = (1.0f / normalization_options.std_values[0]);
        for (size_t i = 0; i < input_data_byte_size / sizeof(uint8);
             i++, input_data++, normalized_input_data++) {
          *normalized_input_data =
              inv_std_value * (static_cast<float>(*input_data) - mean_value);
        }
      } else {
        std::array<float, 3> inv_std_values = {
            1.0f / normalization_options.std_values[0],
            1.0f / normalization_options.std_values[1],
            1.0f / normalization_options.std_values[2]};
        for (size_t i = 0; i < input_data_byte_size / sizeof(uint8);
             i++, input_data++, normalized_input_data++) {
          *normalized_input_data = inv_std_values[i % 3] *
                                   (static_cast<float>(*input_data) -
                                    normalization_options.mean_values[i % 3]);
        }
      }
      break;
    }
    case kTfLiteInt8:
      return tflite::support::CreateStatusWithPayload(
          absl::StatusCode::kUnimplemented,
          "kTfLiteInt8 input type is not implemented yet.");
    default:
      return tflite::support::CreateStatusWithPayload(
          absl::StatusCode::kInternal, "Unexpected input tensor type.");
  }

  return absl::OkStatus();
}

}  // namespace processor
}  // namespace task
}  // namespace tflite


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace GcmSender.Utils
{
    public class Command : ICommand
    {
        private readonly Action _Action;

        public Command(Action action ) {
            _Action = action;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            _Action();
        }
    }
}


text:
RSpec.describe DialogTab do
  let(:dialog_tab) { FactoryBot.build(:dialog_tab, :label => 'tab') }
  context "#validate_children" do
    it "fails without box" do
      expect { dialog_tab.save! }
        .to raise_error(ActiveRecord::RecordInvalid, /tab must have at least one Box/)
    end

    it "validates with box" do
      dialog_tab.dialog_groups << FactoryBot.create(:dialog_group, :label => 'box')
      expect_any_instance_of(DialogGroup).to receive(:valid?)
      expect(dialog_tab.errors.full_messages).to be_empty
      dialog_tab.validate_children
    end
  end

  context "#dialog_fields" do
    # other tests are in dialog_spec.rb
    it "returns [] even when no dialog_groups" do
      expect(dialog_tab.dialog_fields).to be_empty
    end

    it "returns [] when empty dialog_group " do
      dialog_tab.dialog_groups << FactoryBot.build(:dialog_group)
      expect(dialog_tab.dialog_fields).to be_empty
    end
  end

  describe '#update_dialog_groups' do
    let(:dialog_fields) { FactoryBot.create_list(:dialog_field, 2) }
    let(:dialog_groups) { FactoryBot.create_list(:dialog_group, 2) }
    let(:dialog_tab) { FactoryBot.create(:dialog_tab, :dialog_groups => dialog_groups) }

    before do
      dialog_groups.each_with_index { |group, index| group.dialog_fields << dialog_fields[index] }
    end

    context 'a collection of dialog groups containing two objects with ids and one without an id' do
      let(:updated_groups) do
        [
          { 'id'            => dialog_groups.first.id,
            'label'         => 'updated_label',
            'dialog_fields' => [{ 'id' => dialog_fields.first.id}]
          },
          { 'id'            => dialog_groups.last.id,
            'label'         => 'updated_label',
            'dialog_fields' => [{'id' => dialog_fields.last.id}]
          },
          {
            'label'         => 'a new label',
            'dialog_fields' => [{'name' => 'field name', 'label' => 'field label'}]
          }
        ]
      end

      it 'updates the dialog groups with an id' do
        dialog_tab.update_dialog_groups(updated_groups)

        dialog_tab.reload
        expect(dialog_tab.dialog_groups.collect(&:label))
          .to match_array(['updated_label', 'updated_label', 'a new label'])
      end

      it 'creates a new dialog group from the dialog group without an id' do
        expect do
          dialog_tab.update_dialog_groups(updated_groups)
        end.to change(dialog_tab.reload.dialog_groups, :count).by(1)
      end
    end

    context 'with a dialog group removed from the dialog groups' do
      let(:updated_groups) do
        [
          { 'id' => dialog_groups.first.id, 'dialog_fields' => []}
        ]
      end

      it 'deletes the removed dialog group' do
        expect do
          dialog_tab.update_dialog_groups(updated_groups)
        end.to change(dialog_tab.reload.dialog_groups, :count).by(-1)
      end
    end
  end
end


text:
describe("jasmine-pass", function () {
	it("should define pass", function () {
		expect(pass).toEqual(jasmine.any(Function));
	});

	it("should pass", function () {
		pass();
	});
});


text:
"""
    CacheManager provides encapsulation to the caching mechanism used in GGRC
    for resource collection.

"""
from cache import all_cache_entries, all_mapping_entries

class CacheManager:
  """Cache manager provides encapsulation to caching mechanism such as
  Memcache.

  Attributes:
    cache: Ordered dictionary of all cache objects derived from base class
           (Cache)
    supported_classes: Model plural table name for a supported resource type
    supported_mappings: Mapping entry tuples for a supported resource type
    factory: Factory class to create cache object
    new, dirty, deleted: temporary dictionaries used in session event listeners
                         before and after flush
    marked_for_<op>: dictionaries used in session event listeners after flush,
                     before and after commit

  Returns:
    None
  """
  factory = None

  def __init__(self):
    pass

  def initialize(self, cache):
    """Initialize Cache Manager, configure cache mechanism."""
    self.supported_classes = {}
    for cache_entry in all_cache_entries():
      self.supported_classes[cache_entry.class_name] = cache_entry.model_plural

    self.supported_mappings = {}
    for mapping_entry in all_mapping_entries():
      self.supported_mappings.setdefault(mapping_entry.class_name, [])
      self.supported_mappings[mapping_entry.class_name].append(mapping_entry)

    self.cache_object = cache

    self.new = {}
    self.dirty = {}
    self.deleted = {}
    self.marked_for_add = {}
    self.marked_for_update = {}
    self.marked_for_delete = []

  def get_collection(self, category, resource, filter):
    """Get collection from cache.

    Args:
      category: collection or stub
      resource: regulation, controls, etc.
      filter: dictionary containing ids and optional attrs

    Returns:
      JSON string representation
    """
    if not self.is_caching_supported(category, resource, filter,
                                     'get_collection'):
      return None
    ret = self.cache_object.get(category, resource, filter)
    return ret

  def add_collection(self, category, resource, data, expiration_time=0):
    """Add collection in cache.

    Args:
      category: collection or stub
      resource: regulation, controls, etc.
      data: dictionary containing ids and attrs to update
    Returns:
     DTO formatted string, e.g. JSON string representation
    """

    if not self.is_caching_supported(category, resource, data,
                                     'add_collection'):
      return None
    ret = self.cache_object.add(category, resource, data, expiration_time)
    return ret

  def update_collection(self, category, resource, data, expiration_time=0):
    """Update collection in cache.

    Args:
      category: collection or stub
      resource: regulation, controls, etc.
      data: dictionary containing ids and attrs to update
    Returns:
     JSON string representation
    """
    if not self.is_caching_supported(category, resource, data,
                                     'update_collection'):
      return None
    ret = self.cache_object.update(category, resource, data, expiration_time)
    return ret

  def delete_collection(self, category, resource, data, lockadd_seconds=0):
    """Delete collection from cache.

    Args:
      category: collection or stub
      resource: regulation, controls, etc.
      data: dictionary containing ids of the resource to delete
    Returns:
      JSON string representation
    """
    if not self.is_caching_supported(category, resource, data,
                                     'delete_collection'):
      return None

    ret = self.cache_object.remove(category, resource, data, lockadd_seconds)
    return ret

  def is_caching_supported(self, category, resource, data=None,
                           operation=None):
    """Check if caching is supported.

    Args:
      category: collection or stub
      resource: regulation, controls, etc.
      data: additional data such as context information, Default is None
      operation: operation performed such as get, update, delete or add

    Returns:
      True if caching is supported for the category and resource.
      False otherwise
    """
    # TODO(dan): Leverage policy manager to apply configured policies
    #
    if self.cache_object.is_caching_supported(category, resource):
      return True
    else:
      return False

  def bulk_get(self, data):
    """Perform Bulk Get operations in cache for specified data.

    Args:
      data: keys for bulk get
    Returns:
     Result of cache get_multi
    """
    return self.cache_object.get_multi(data)

  def bulk_add(self, data, expiration_time=0):
    """Perform Bulk Add operations in cache for specified data.

    Args:
      data: keys for bulk add
    Returns:
     Result of cache add_multi
    """
    return self.cache_object.add_multi(data, expiration_time)

  def bulk_update(self, data, expiration_time=0):
    """Perform Bulk update operations in cache for specified data.

    Does a bulk get on all the items in data and then performs bulk update only
    for items present in cache.

    Args:
      data: keys for bulk update
    Returns:
     Result of cache update_multi
    """
    get_result = self.cache_object.get_multi(data.keys())
    for data_key, data_value in data.items():
      for update_key, update_value in data_value.items():
        if data_key in get_result:
          get_result[data_key][update_key] = update_value
    return self.cache_object.update_multi(get_result, expiration_time)

  def bulk_delete(self, data, lockadd_seconds):
    """Perform Bulk Delete operations in cache for specified data.

    Args:
      data: keys for bulk delete
    Returns:
     Result of cache remove_multi
    """
    return self.cache_object.remove_multi(data, lockadd_seconds)

  def clean(self):
    """Cleanup cache manager resources."""
    self.cache_object.clean()
    return True

  def clear_cache(self):
    """Clear temporary dictionaries used for cache operations."""
    self.new = {}
    self.dirty = {}
    self.deleted = {}
    self.marked_for_add = {}
    self.marked_for_update = {}
    self.marked_for_delete = []


text:
var dao = require('./genericdao').newDao('user');

dao.getDoc().index('email', { unique: true });

dao.findByEmail = function (email, next) {
	var doc = dao.getDoc();
	doc.findOne({email: email}, next);
};

var superValidate = dao.validate;
dao.validate = function(document,isInsert){
	if( !document.name || document.name == '' ){
		return 'missing_user_name';
	}
	if( !document.email || document.email == '' ){
		return 'missing_user_email';
	}
	else{
		// TOOD: validate email
	}
	if( !document.password || document.password == '' ){
		return 'missing_user_password';
	}
	else{
		// TODO: validate password
	}
	if( !document.timeZone || document.timeZone == '' ){
		return 'missing_user_timezone';
	}
	else{
		// TODO: validate timeZone
	}

	var validAttributes = ['name', 'email', 'password', 'timeZone', 'active', 'token', '_id'];

	for(attribute in document){
		var valid = false;
		for( i in validAttributes ){
			var validAttrib = validAttributes[i];
			if( validAttrib == attribute ){
				valid = true;
				break;
			}
		}
		if( !valid ){
			return "invalid_user_" + attribute;
		}
	}
	return superValidate(document, isInsert);
};

module.exports = dao;


text:
package bookshop2.shipper.incoming.shipBooks;

import static javax.ejb.ConcurrencyManagementType.BEAN;
import static javax.ejb.TransactionAttributeType.REQUIRED;
import static javax.ejb.TransactionManagementType.CONTAINER;

import javax.annotation.Resource;
import javax.ejb.AccessTimeout;
import javax.ejb.Asynchronous;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.Local;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionManagement;
import javax.inject.Inject;
import javax.interceptor.Interceptors;
import javax.transaction.TransactionSynchronizationRegistry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aries.common.AbstractMessage;
import org.aries.process.TimeoutHandler;
import org.aries.runtime.RequestContext;
import org.aries.tx.service.AbstractServiceHandler;
import org.aries.tx.service.ServiceHandlerInterceptor;
import org.aries.util.ExceptionUtil;

import bookshop2.ShipmentRequestMessage;
import bookshop2.shipper.ShipperContext;
import bookshop2.shipper.ShipperProcess;

@Stateful
@Local(ShipBooksHandler.class)
@ConcurrencyManagement(BEAN)
@TransactionManagement(CONTAINER)
@Interceptors(ServiceHandlerInterceptor.class)
public class ShipBooksHandlerImpl extends AbstractServiceHandler implements ShipBooksHandler {

	private static final Log log = LogFactory.getLog(ShipBooksHandlerImpl.class);

	@Inject
	private RequestContext requestContext;

	@Inject
	private ShipperProcess shipperProcess;

	@Resource
	private TransactionSynchronizationRegistry transactionSynchronizationRegistry;

	public String getName() {
		return "ShipBooks";
	}

	public String getDomain() {
		return "bookshop2.shipper";
	}

	public boolean prepare(String transactionId) {
		return true;
	}

	public void commit(String transactionId) {
		//nothing for now
	}

	public void rollback(String transactionId) {
		//nothing for now
	}

	protected ShipperContext getContext(AbstractMessage message) {
		return getContext(getCorrelationId(message));
	}

	protected ShipperContext getContext(String correlationId) {
		requestContext.setCorrelationId(correlationId);
		return ShipperContext.getInstance(correlationId);
	}

	@Override
	@Asynchronous
	@AccessTimeout(value = 60000)
	@TransactionAttribute(REQUIRED)
	public void shipBooks(ShipmentRequestMessage shipmentRequestMessage) {
		String correlationId = getCorrelationId(shipmentRequestMessage);
		log.info("#### [shipper]: ShipBooks request received: "+correlationId);
		TimeoutHandler timeoutHandler = null;

		try {
			ShipperContext shipperContext = getContext(correlationId);
			shipperContext.validate(shipmentRequestMessage);
			shipperContext.fire_ShipBooks_request_received();

			if (shipperContext.isGlobalTransactionActive())
				enrollTransaction("bookReservation", shipperContext);

			switch (getAction(shipmentRequestMessage)) {
			case CANCEL:
				shipperProcess.handle_ShipBooks_request_cancel(shipmentRequestMessage);
				break;
			case UNDO:
				shipperProcess.handle_ShipBooks_request_undo(shipmentRequestMessage);
				break;
			default:
				timeoutHandler = startTimeoutHandler(createTimeoutHandler(correlationId));
				shipperProcess.handle_ShipBooks_request(shipmentRequestMessage);
				timeoutHandler.reset();
				break;
			}

		} catch (Throwable e) {
			log.error("Error", e);
			if (timeoutHandler != null)
				timeoutHandler.reset();
			e = ExceptionUtil.getRootCause(e);
			transactionSynchronizationRegistry.setRollbackOnly();
			shipperProcess.handle_ShipBooks_request_exception(correlationId, e);

		} finally {
			timeout = DEFAULT_TIMEOUT;
		}
	}

	protected Runnable createTimeoutHandler(final String correlationId) {
		return new Runnable() {
			public void run() {
				String reason = "ShipBooks timed-out";
				shipperProcess.handle_ShipBooks_request_timeout(correlationId, reason);
		}
		};
	}

}


text:
/* vim:set ts=2 sw=2 sts=2 et: */
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

const TEST_URI = 'data:text/html;charset=utf-8,
test repeated' +
                 ' css warnings

hi
';

function onContentLoaded()
{
  browser.removeEventListener("load", onContentLoaded, true);

  let HUD = HUDService.getHudByWindow(content);
  let jsterm = HUD.jsterm;
  let outputNode = HUD.outputNode;

  let cssWarning = "Unknown property '-moz-opacity'.  Declaration dropped.";

  waitForSuccess({
    name: "2 repeated CSS warnings",
    validatorFn: function()
    {
      return outputNode.textContent.indexOf(cssWarning) > -1;
    },
    successFn: function()
    {
      let msg = "The unknown CSS property warning is displayed only once";
      let node = outputNode.firstChild;

      is(node.childNodes[2].textContent, cssWarning, "correct node");
      is(node.childNodes[3].firstChild.getAttribute("value"), 2, msg);

      testConsoleLogRepeats();
    },
    failureFn: finishTest,
  });
}

function testConsoleLogRepeats()
{
  let HUD = HUDService.getHudByWindow(content);
  let jsterm = HUD.jsterm;
  let outputNode = HUD.outputNode;

  jsterm.clearOutput();

  jsterm.setInputValue("for (let i = 0; i < 10; ++i) console.log('this is a line of reasonably long text that I will use to verify that the repeated text node is of an appropriate size.');");
  jsterm.execute();

  waitForSuccess({
    name: "10 repeated console.log messages",
    validatorFn: function()
    {
      let node = outputNode.querySelector(".webconsole-msg-console");
      return node && node.childNodes[3].firstChild.getAttribute("value") == 10;
    },
    successFn: finishTest,
    failureFn: finishTest,
  });
}

/**
 * Unit test for bug 611795:
 * Repeated CSS messages get collapsed into one.
 */
function test()
{
  addTab(TEST_URI);
  browser.addEventListener("load", function onLoad() {
    browser.removeEventListener("load", onLoad, true);
    openConsole(null, function(aHud) {
      // Clear cached messages that are shown once the Web Console opens.
      aHud.jsterm.clearOutput(true);
      browser.addEventListener("load", onContentLoaded, true);
      content.location.reload();
    });
  }, true);
}


text:
from decimal import Decimal
from typing import Any, Coroutine, Dict, Generator, List, Tuple, Union

from .account import Account
from .asset import Asset
from .base_transaction_envelope import BaseTransactionEnvelope
from .call_builder.base import (
    BaseAccountsCallBuilder,
    BaseAssetsCallBuilder,
    BaseClaimableBalancesCallBuilder,
    BaseDataCallBuilder,
    BaseEffectsCallBuilder,
    BaseFeeStatsCallBuilder,
    BaseLedgersCallBuilder,
    BaseLiquidityPoolsBuilder,
    BaseOffersCallBuilder,
    BaseOperationsCallBuilder,
    BaseOrderbookCallBuilder,
    BasePaymentsCallBuilder,
    BaseRootCallBuilder,
    BaseStrictReceivePathsCallBuilder,
    BaseStrictSendPathsCallBuilder,
    BaseTradeAggregationsCallBuilder,
    BaseTradesCallBuilder,
    BaseTransactionsCallBuilder,
)
from .fee_bump_transaction import FeeBumpTransaction
from .fee_bump_transaction_envelope import FeeBumpTransactionEnvelope
from .helpers import parse_transaction_envelope_from_xdr
from .keypair import Keypair
from .muxed_account import MuxedAccount
from .operation import (
    AccountMerge,
    PathPaymentStrictReceive,
    PathPaymentStrictSend,
    Payment,
)
from .sep.exceptions import AccountRequiresMemoError
from .transaction import Transaction
from .transaction_envelope import TransactionEnvelope
from .type_checked import type_checked

__all__ = ["BaseServer"]

@type_checked
class BaseServer:
    def submit_transaction(
        self,
        transaction_envelope: Union[
            TransactionEnvelope, FeeBumpTransactionEnvelope, str
        ],
        skip_memo_required_check: bool = False,
    ) -> Union[Dict[str, Any], Coroutine[Any, Any, Dict[str, Any]]]:
        """Submits a transaction to the network.

        :param transaction_envelope: :class:`stellar_sdk.transaction_envelope.TransactionEnvelope` object
            or base64 encoded xdr
        :param skip_memo_required_check: Allow skipping memo
        :return: the response from horizon
        :raises:
            :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
            :exc:`NotFoundError <stellar_sdk.exceptions.NotFoundError>`
            :exc:`BadRequestError <stellar_sdk.exceptions.BadRequestError>`
            :exc:`BadResponseError <stellar_sdk.exceptions.BadResponseError>`
            :exc:`UnknownRequestError <stellar_sdk.exceptions.UnknownRequestError>`
            :exc:`AccountRequiresMemoError <stellar_sdk.sep.exceptions.AccountRequiresMemoError>`
        """
        raise NotImplementedError

    def _get_xdr_and_transaction_from_transaction_envelope(
        self,
        transaction_envelope: Union[
            TransactionEnvelope, FeeBumpTransactionEnvelope, str
        ],
    ) -> Tuple[str, Union[Transaction, FeeBumpTransaction]]:
        if isinstance(transaction_envelope, BaseTransactionEnvelope):
            xdr = transaction_envelope.to_xdr()
            tx = transaction_envelope.transaction
        else:
            xdr = transaction_envelope
            tx = parse_transaction_envelope_from_xdr(
                transaction_envelope, ""
            ).transaction
        return xdr, tx

    def root(self) -> BaseRootCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.RootCallBuilder` object configured
            by a current Horizon server configuration.
        """
        raise NotImplementedError

    def accounts(self) -> BaseAccountsCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.AccountsCallBuilder` object configured
            by a current Horizon server configuration.
        """
        raise NotImplementedError

    def assets(self) -> BaseAssetsCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.AssetsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def claimable_balances(self) -> BaseClaimableBalancesCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.ClaimableBalancesCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def data(self, account_id: str, data_name: str) -> BaseDataCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.DataCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def effects(self) -> BaseEffectsCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.EffectsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def fee_stats(self) -> BaseFeeStatsCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.FeeStatsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def ledgers(self) -> BaseLedgersCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.LedgersCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def liquidity_pools(self) -> BaseLiquidityPoolsBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.LiquidityPoolsBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def offers(self) -> BaseOffersCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.OffersCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def operations(self) -> BaseOperationsCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.OperationsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def orderbook(self, selling: Asset, buying: Asset) -> BaseOrderbookCallBuilder:
        """
        :param selling: Asset being sold
        :param buying: Asset being bought
        :return: New :class:`stellar_sdk.call_builder.OrderbookCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def strict_receive_paths(
        self,
        source: Union[str, List[Asset]],
        destination_asset: Asset,
        destination_amount: Union[str, Decimal],
    ) -> BaseStrictReceivePathsCallBuilder:
        """
        :param source: The sender's account ID or a list of Assets. Any returned path must use a source that the sender can hold.
        :param destination_asset: The destination asset.
        :param destination_amount: The amount, denominated in the destination asset, that any returned path should be able to satisfy.
        :return: New :class:`stellar_sdk.call_builder.StrictReceivePathsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def strict_send_paths(
        self,
        source_asset: Asset,
        source_amount: Union[str, Decimal],
        destination: Union[str, List[Asset]],
    ) -> BaseStrictSendPathsCallBuilder:
        """
        :param source_asset: The asset to be sent.
        :param source_amount: The amount, denominated in the source asset, that any returned path should be able to satisfy.
        :param destination: The destination account or the destination assets.
        :return: New :class:`stellar_sdk.call_builder.StrictReceivePathsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def payments(self) -> BasePaymentsCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.PaymentsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def trade_aggregations(
        self,
        base: Asset,
        counter: Asset,
        resolution: int,
        start_time: int = None,
        end_time: int = None,
        offset: int = None,
    ) -> BaseTradeAggregationsCallBuilder:
        """
        :param base: base asset
        :param counter: counter asset
        :param resolution: segment duration as millis since epoch. *Supported values
            are 1 minute (60000), 5 minutes (300000), 15 minutes (900000),
            1 hour (3600000), 1 day (86400000) and 1 week (604800000).*
        :param start_time: lower time boundary represented as millis since epoch
        :param end_time: upper time boundary represented as millis since epoch
        :param offset: segments can be offset using this parameter.
            Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour.
            Value must be in whole hours, less than the provided resolution, and less than 24 hours.*
        :return: New :class:`stellar_sdk.call_builder.TradeAggregationsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def trades(self) -> BaseTradesCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.TradesCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def transactions(self) -> BaseTransactionsCallBuilder:
        """
        :return: New :class:`stellar_sdk.call_builder.TransactionsCallBuilder` object configured by
            a current Horizon server configuration.
        """
        raise NotImplementedError

    def load_account(
        self, account_id: Union[MuxedAccount, Keypair, str]
    ) -> Union[Account, Coroutine[Any, Any, Account]]:
        """Fetches an account's most current base state (like sequence) in the ledger and then creates
        and returns an :class:`stellar_sdk.account.Account` object.

        If you want to get complete account information, please
        use :func:`stellar_sdk.server.Server.accounts`.

        :param account_id: The account to load.
        :return: an :class:`stellar_sdk.account.Account` object.
        :raises:
            :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
            :exc:`NotFoundError <stellar_sdk.exceptions.NotFoundError>`
            :exc:`BadRequestError <stellar_sdk.exceptions.BadRequestError>`
            :exc:`BadResponseError <stellar_sdk.exceptions.BadResponseError>`
            :exc:`UnknownRequestError <stellar_sdk.exceptions.UnknownRequestError>`
        """
        raise NotImplementedError

    def _check_destination_memo(
        self, account_resp: dict, index: int, destination: str
    ) -> None:
        memo_required_config_key = "config.memo_required"
        memo_required_config_value = "MQ=="
        data = account_resp["data"]
        if data.get(memo_required_config_key) == memo_required_config_value:
            raise AccountRequiresMemoError(
                "Destination account requires a memo in the transaction.",
                destination,
                index,
            )

    def _get_check_memo_required_destinations(
        self, transaction: Transaction
    ) -> Generator[Tuple[int, str], Any, Any]:
        destinations = set()
        for index, operation in enumerate(transaction.operations):
            if isinstance(
                operation,
                (
                    Payment,
                    AccountMerge,
                    PathPaymentStrictSend,
                    PathPaymentStrictReceive,
                ),
            ):
                destination: str = operation.destination.account_id
            else:
                continue
            if destination in destinations:
                continue
            destinations.add(destination)
            yield index, destination

    def fetch_base_fee(self) -> Union[int, Coroutine[Any, Any, int]]:
        """Fetch the base fee. Since this hits the server, if the server call fails,
        you might get an error. You should be prepared to use a default value if that happens.

        :return: the base fee
        :raises:
            :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
            :exc:`NotFoundError <stellar_sdk.exceptions.NotFoundError>`
            :exc:`BadRequestError <stellar_sdk.exceptions.BadRequestError>`
            :exc:`BadResponseError <stellar_sdk.exceptions.BadResponseError>`
            :exc:`UnknownRequestError <stellar_sdk.exceptions.UnknownRequestError>`
        """
        raise NotImplementedError

    def _handle_base_fee(self, latest_ledger: dict) -> int:
        base_fee = 100
        if (
            latest_ledger["_embedded"]
            and latest_ledger["_embedded"]["records"]
            and latest_ledger["_embedded"]["records"][0]
        ):
            base_fee = int(
                latest_ledger["_embedded"]["records"][0]["base_fee_in_stroops"]
            )
        return base_fee

    def close(self) -> Union[None, Coroutine[Any, Any, None]]:
        """Close underlying connector.

        Release all acquired resources.
        """
        raise NotImplementedError

    async def __aenter__(self):
        raise NotImplementedError

    async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
        raise NotImplementedError

    def __enter__(self):
        raise NotImplementedError

    def __exit__(self, exc_type, exc_val, exc_tb):
        raise NotImplementedError


text:
#ifndef _GUAC_TERMINAL_DISPLAY_H
#define _GUAC_TERMINAL_DISPLAY_H

#include "config.h"

#include "guac_surface.h"
#include "types.h"

#include <guacamole/client.h>
#include <guacamole/layer.h>
#include <pango/pangocairo.h>

#include <stdbool.h>

/**
 * The maximum width of any character, in columns.
 */
#define GUAC_TERMINAL_MAX_CHAR_WIDTH 2

/**
 * The available color palette. All integer colors within structures
 * here are indices into this palette.
 */
extern const guac_terminal_color guac_terminal_palette[16];

/**
 * All available terminal operations which affect character cells.
 */
typedef enum guac_terminal_operation_type {

    /**
     * Operation which does nothing.
     */
    GUAC_CHAR_NOP,

    /**
     * Operation which copies a character from a given row/column coordinate.
     */
    GUAC_CHAR_COPY,

    /**
     * Operation which sets the character and attributes.
     */
    GUAC_CHAR_SET

} guac_terminal_operation_type;

/**
 * A pairing of a guac_terminal_operation_type and all parameters required by
 * that operation type.
 */
typedef struct guac_terminal_operation {

    /**
     * The type of operation to perform.
     */
    guac_terminal_operation_type type;

    /**
     * The character (and attributes) to set the current location to. This is
     * only applicable to GUAC_CHAR_SET.
     */
    guac_terminal_char character;

    /**
     * The row to copy a character from. This is only applicable to
     * GUAC_CHAR_COPY.
     */
    int row;

    /**
     * The column to copy a character from. This is only applicable to
     * GUAC_CHAR_COPY.
     */
    int column;

} guac_terminal_operation;

/**
 * Set of all pending operations for the currently-visible screen area.
 */
typedef struct guac_terminal_display {

    /**
     * The Guacamole client this display will use for rendering.
     */
    guac_client* client;

    /**
     * Array of all operations pending for the visible screen area.
     */
    guac_terminal_operation* operations;

    /**
     * The width of the screen, in characters.
     */
    int width;

    /**
     * The height of the screen, in characters.
     */
    int height;

    /**
     * The description of the font to use for rendering.
     */
    PangoFontDescription* font_desc;

    /**
     * The width of each character, in pixels.
     */
    int char_width;

    /**
     * The height of each character, in pixels.
     */
    int char_height;

    /**
     * Color of glyphs in copy buffer
     */
    int glyph_foreground;

    /**
     * Color of glyphs in copy buffer
     */
    int glyph_background;

    /**
     * The surface containing the actual terminal.
     */
    guac_common_surface* display_surface;

    /**
     * Layer which contains the actual terminal.
     */
    guac_layer* display_layer;

    /**
     * Sub-layer of display layer which highlights selected text.
     */
    guac_layer* select_layer;

    /**
     * Whether text is being selected.
     */
    bool text_selected;

    /**
     * Whether the selection is finished, and will no longer be modified. A
     * committed selection remains highlighted for reference, but the
     * highlight will be removed when the display changes.
     */
    bool selection_committed;

    /**
     * The row that the selection starts at.
     */
    int selection_start_row;

    /**
     * The column that the selection starts at.
     */
    int selection_start_column;

    /**
     * The row that the selection ends at.
     */
    int selection_end_row;

    /**
     * The column that the selection ends at.
     */
    int selection_end_column;

} guac_terminal_display;

/**
 * Allocates a new display having the given default foreground and background
 * colors.
 */
guac_terminal_display* guac_terminal_display_alloc(guac_client* client,
        const char* font_name, int font_size, int dpi,
        int foreground, int background);

/**
 * Frees the given display.
 */
void guac_terminal_display_free(guac_terminal_display* display);

/**
 * Copies the given range of columns to a new location, offset from
 * the original by the given number of columns.
 */
void guac_terminal_display_copy_columns(guac_terminal_display* display, int row,
        int start_column, int end_column, int offset);

/**
 * Copies the given range of rows to a new location, offset from the
 * original by the given number of rows.
 */
void guac_terminal_display_copy_rows(guac_terminal_display* display,
        int start_row, int end_row, int offset);

/**
 * Sets the given range of columns within the given row to the given
 * character.
 */
void guac_terminal_display_set_columns(guac_terminal_display* display, int row,
        int start_column, int end_column, guac_terminal_char* character);

/**
 * Resize the terminal to the given dimensions.
 */
void guac_terminal_display_resize(guac_terminal_display* display, int width, int height);

/**
 * Flushes all pending operations within the given guac_terminal_display.
 */
void guac_terminal_display_flush(guac_terminal_display* display);

/**
 * Draws the text selection rectangle from the given coordinates to the given end coordinates.
 */
void guac_terminal_display_select(guac_terminal_display* display,
        int start_row, int start_col, int end_row, int end_col);

/**
 * Commits the select rectangle, allowing the display to clear it when
 * necessary.
 */
void guac_terminal_display_commit_select(guac_terminal_display* display);

#endif


text:
XtraUpload
=======

_XtraUpload_ is a file hosting application written in PHP. It supports a vary large number of features right out of the box.  It can use a number of SQL databases including MySQL, SQLite, MSSQL, etc.

Minimum System Requirements
--------
PHP 5.3.3+

*   MySql > v4.1
*   GD v2
*   FreeType v2
*   FTP

1 Free Sql Database
Lots of file storage space.

More Coming Soon...
--------


text:
{% extends "layout.html" %}

{% block bodyhead %}
{% if login %}

	{% if notification %}

	{% else %}

	{% endif %}

{% endif %}
{% endblock %}

{% block body %}

    <form action="{{ url_for('login') }}" method=post>

            {% for message in get_flashed_messages() %}

{{ message }}

            {% endfor %}
            {% if error %}
Error: {{ error }}{% endif %}

Welcome {{display_name}} !

My Groups

My Grocery Bag

My Recipes

    </form>

{% endblock %}


text:
/**
 * @asset(qx/icon/${qx.icontheme}/22/actions/dialog-apply.png)
 * @asset(qx/icon/${qx.icontheme}/22/actions/dialog-cancel.png)
 */
qx.Class.define("appudo_cli_creator.view.desktop.CommandTreeRemDialog",
{
  extend : qx.ui.window.Window,
  members :
  {
    __controller : null,
    __commandTree : null,

    openAndCenter : function(type, item) {
      var selection = this.__commandTree.getSelection();
      var item;
      var kind;
      if(selection.length) {
        item = selection[0];
      } else {
        return;
      }
      kind = item.getNodeKind();
      var type = kind == 2 || kind == 4 ? 1 : 0;

      this.setCaption(type == 0 ? this.tr('Remove Command') : this.tr('Remove Function'));

      this.removeAll();

      var form = new qx.ui.form.Form();

      var textLabel = new qx.ui.form.TextField();
      textLabel.setValue(item.getLabel());
      textLabel.setReadOnly(true);
      form.add(textLabel, type == 0 ? this.tr("Name") : this.tr("Index"));

      var renderedForm = new qx.ui.form.renderer.Single(form);
      this.add(renderedForm);

      var okButton = new qx.ui.form.Button(this.tr("Remove"), "icon/22/actions/dialog-apply.png");
      okButton.addState("default");
      renderedForm.addButton(okButton);

      var submit = function() {
        if(type == 0) {
          this.__commandTree.remCommand(item);
        } else {
          this.__commandTree.remFunction(item);
        }
        this.close();
      };

      okButton.addListener('execute', submit, this);

      var cancelButton = new qx.ui.form.Button(this.tr("Cancel"), "icon/22/actions/dialog-cancel.png");
      renderedForm.addButton(cancelButton);

      cancelButton.addListener('execute', function() {
          this.close();
      }, this);

      this.center();
      this.open();
    },

    __close : function() {

    }
  },

  construct : function(controller, tree)
  {
    var _this = this;
    this.base(arguments);
    this.__controller = controller;
    this.__commandTree = tree;
    this.setModal(true);
    this.setAllowMinimize(false);
    this.setLayout(new qx.ui.layout.VBox(5));
    this.setMinWidth(300);

    this.addListener('beforeClose', this.__close, this);
  }
});


text:
<?php

namespace MikeRoetgers\ArangoPHP\Document\Options;

class RemoveByExampleOptions
{
    public $waitForSync = false;
    public $limit = null;
}


text:
"""
tests_output_folder.

Test formerly known from a unittest residing in test_generate.py named
TestOutputFolder.test_output_folder
"""
import os

import pytest

from cookiecutter import exceptions
from cookiecutter import generate
from cookiecutter import utils

@pytest.fixture(scope='function')
def remove_output_folder(request):
    """Remove the output folder after test."""
    yield
    if os.path.exists('output_folder'):
        utils.rmtree('output_folder')

@pytest.mark.usefixtures('clean_system', 'remove_output_folder')
def test_output_folder():
    """Tests should correctly create content, as output_folder does not yet exist."""
    context = generate.generate_context(
        context_file='tests/test-output-folder/cookiecutter.json'
    )
    generate.generate_files(context=context, repo_dir='tests/test-output-folder')

    something = """Hi!
My name is Audrey Greenfeld.
It is 2014."""
    something2 = open('output_folder/something.txt').read()
    assert something == something2

    in_folder = "The color is green and the letter is D."
    in_folder2 = open('output_folder/folder/in_folder.txt').read()
    assert in_folder == in_folder2

    assert os.path.isdir('output_folder/im_a.dir')
    assert os.path.isfile('output_folder/im_a.dir/im_a.file.py')

@pytest.mark.usefixtures('clean_system', 'remove_output_folder')
def test_exception_when_output_folder_exists():
    """Tests should raise error as output folder created before `generate_files`."""
    context = generate.generate_context(
        context_file='tests/test-output-folder/cookiecutter.json'
    )
    output_folder = context['cookiecutter']['test_name']

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    with pytest.raises(exceptions.OutputDirExistsException):
        generate.generate_files(context=context, repo_dir='tests/test-output-folder')


text:
KISSY.use('node,overlay', function (S, Node, Overlay) {
    var $ = Node.all;
    var overlay = new Overlay({
        content: $('#loading').html(),
        mask: true,
        align: {
            points: ['cc', 'cc']
        }
    });
    var canvas = $('#canvas')[0];
    var upload = $('#upload');
    var filter = $('#filter');
    var download = $('#download');
    var h = $('#h');
    var s = $('#s');
    var l = $('#l');
    var restore = $('#restore');
    var ctx = canvas.getContext('2d');
    var tmpCanvas = document.createElement('canvas');
    var tmpCtx = tmpCanvas.getContext('2d');
    var originalImage;
    var originalImageData;
    var originalWidth;
    var originalHeight;

//        var blob = new Blob(Array.prototype.map.call(
//                document.querySelectorAll(
//                        "script[type=\"text\/js-worker\"]"),
//                function (oScript) {
//                    return oScript.textContent;
//                }), {type: "text/javascript"});
//
//        var worker = new Worker(window.URL.createObjectURL(blob));

    var worker = new Worker('worker.js');

    worker.postMessage({
        host: location.host
    });

    worker.onmessage = function (e) {
        if (e.data.complete) {
            upload[0].disabled = false;
            return;
        }
        if (e.data.log) {
            S.log(e.data.log);
            return;
        }
        if (window[e.data.callback]) {
            window[e.data.callback](e.data.data);
        }
    };

    function createImageData(w, h) {
        return tmpCtx.createImageData(w, h);
    }

    function filterImage(percentage) {
        var pixels = createImageData(originalWidth, originalHeight);
        var callback = 'callback' + S.now();
        window[callback] = function (data) {
            overlay.hide();
            var pixelsData = pixels.data;
            for (var i = 0; i < data.length; i++) {
                pixelsData[i] = data[i];
            }
            ctx.putImageData(pixels, 0, 0);
            download.attr('href', canvas.toDataURL());
            delete window[callback];
        };
        overlay.show();
        worker.postMessage({
            data: originalImageData,
            callback: callback,
            percentage: percentage
        });
    }

    filter.on('click', function () {
        filterImage({
            h: h.val() / 100,
            s: s.val() / 100,
            l: l.val() / 100
        });
    });

    restore.on('click', function () {
        ctx.putImageData(originalImage, 0, 0);
        download.attr('href', canvas.toDataURL());
    });

    upload.on('change', function () {
        var f = this.files[0];
        // Only process image files.
        if (!f.type.match(/image.*/)) {
            return;
        }

        var reader = new FileReader();
        // Closure to capture the file information.
        reader.onload = (function (theFile) {
            return function (e) {
                var img = new Image();
                // tainted canvas
                //img.crossOrigin = "Anonymous";
                img.title = theFile.name;
                img.src = e.target.result;
                download.attr('download', theFile.name);

                //img.src='http://localhost:9999/kissy/src/color/demo/backdrop.png';
                img.onload = function () {
                    restore[0].disabled = filter[0].disabled = h[0].disabled =
                        s[0].disabled = l[0].disabled = false;
                    h[0].value = s[0].value = l[0].value = 100;
                    originalWidth = canvas.width = img.width;
                    originalHeight = canvas.height = img.height;
                    ctx.drawImage(img, 0, 0);
                    originalImage = ctx.getImageData(0, 0, originalWidth, originalHeight);
                    originalImageData = originalImage.data;
                    download.attr('href', canvas.toDataURL());
                };
            };
        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
    });
});


text:
"""
For more information: http://pythonhosted.org//Flask-Bootstrap/index.html
"""

import os
from wsgiref.handlers import CGIHandler
from utils import adjust_sys_path

adjust_sys_path()

from app import create_app
from werkzeug_debugger_appengine import get_debugged_app

def main():
    app = create_app()
    # If we're on the local server, let's enable Flask debugging.
    if 'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Dev'):
        app.debug = False
        app = get_debugged_app(app)
    CGIHandler().run(app)

if __name__ == '__main__':
    main()


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Laravel\Socialite\Contracts\Factory as Socialite;
use Illuminate\Mail\Message;

use App\User;
use App\UserFactory;
use App\Proposition;
use App\PropositionFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class ProfileController extends Controller
{

	public function __construct(Socialite $socialite){
		$this->socialite = $socialite;
		\App::setLocale(Auth::user()->language());
	}

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
    	$user = Auth::user();
    	$propositionFactory = new PropositionFactory();
    	$propositionsCount = $propositionFactory->getPropositionsCountByUser($user->userId());

    	$viewUser = [
    			'fullName' => $user->firstName() . " " . $user->lastName(),
    			'firstName' => $user->firstName(),
    			'lastName' => $user->lastName(),
    			'contactEmail' => $user->contactEmail(),
    			'email' => $user->email(),
    			'avatar' => $user->avatar(),
    			'belongsToSchool' => $user->belongsToSchool(),
    			'schoolEmail' => $user->googleEmail(),
    			'role' => $user->role(),
    			'lang' => $user->language(),
    			'propositionsCount' => $propositionsCount,
    	];

		$highlight = array();
		$highlight[session('highlight')] = true;

    	return view('account_new.profile', ['fullName' => $user->firstName() . " " . $user->lastName(), 'user' => $viewUser, 'highlight' => $highlight]);
    }

    public function language()
    {
    	return redirect()->route('profile.main')->with('highlight', 'lang');
    }

    public function setLanguage($code)
    {
    	$user = Auth::user();
    	$user->setLanguage($code);
    	$user->save();

    	return redirect()->back();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
    	$validator = Validator::make($request->all(), [
    			'first' => 'required',
    			'last' => 'required',
    			'contact' => 'email',
    			'lang' => 'required',
    	]);

    	if ($validator->fails()) {

    		return redirect()->back()->withInput($request->all())->withErrors($validator->errors());

    	} else {

    		$firstName = $request->input('first');
    		$lastName = $request->input('last');
    		$contactemail = $request->input('contact');
    		$lang = $request->input('lang');

    		$user = Auth::user();

    		$user->setFirstName($firstName);
    		$user->setLastName($lastName);
    		$user->setContactEmail($contactemail);
    		$user->setLanguage($lang);

    		$user->save();

    		return redirect()->back();

    	}
    }

    public function propositions() {
    	$user = Auth::user();
    	$propositionFactory = new PropositionFactory();
    	$propositionsCount = $propositionFactory->getPropositionsCountByUser($user->userId());
    	$viewUser = [
    			'fullName' => $user->firstName() . " " . $user->lastName(),
    			'firstName' => $user->firstName(),
    			'lastName' => $user->lastName(),
    			'contactEmail' => $user->contactEmail(),
    			'email' => $user->email(),
    			'avatar' => $user->avatar(),
    			'belongsToSchool' => $user->belongsToSchool(),
    			'schoolEmail' => $user->googleEmail(),
    			'role' => $user->role(),
    			'propositionsCount' => $propositionsCount,
    	];

    	$propositionFactory = new PropositionFactory();
    	$userPropositions = $propositionFactory->getPropositionsByUser($user->userId());

    	$viewPropositions = array();

    	foreach ($userPropositions as $proposition) {

    		$viewPropositions[$proposition->propositionId()] = [
    				'id' => $proposition->propositionId(),
    				'propositionSort' => $proposition->propositionSort(),
    				'propositionLong' => $proposition->propositionLong(),
    				'propositionCreationDate' => Carbon::createFromTimestamp(strtotime($proposition->date_created()))->diffForHumans(),
    				'userHasVoted' => $propositionFactory->getUserVoteStatus($proposition->propositionId(), $user->userId()),
    				'upvotes' => $propositionFactory->getUpvotes($proposition->propositionId()),
    				'downvotes' => $propositionFactory->getDownvotes($proposition->propositionId()),
    				'commentsCount' => $propositionFactory->getCommentsCount($proposition->propositionId()),
    				'deadline' => $proposition->deadline(),
    				'statusId' => $proposition->status(),
    				'blockReason' => $proposition->blockReason(),
    				'ending_in' => Carbon::now()->diffInDays(Carbon::createFromTimestamp(strtotime($proposition->deadline())), false),
    				'marker' => $propositionFactory->getMarker($proposition->propositionId()),
    		];
    	}

    	return view('account_new.propositions', ['fullName' => $user->firstName() . " " . $user->lastName(), 'user' => $viewUser, 'propositions' => $viewPropositions]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function getLinkAuth()
    {
    	return $this->socialite->with('google')->redirect();
    }

    public function getLinkAuthCallback()
    {
    	if($socialUser = $this->socialite->with('google')->user()){

    		if (isset($socialUser->user['domain'])) {

    			$domain = $socialUser->user['domain'];

    			if ($domain === "eursc-mamer.lu") {

    				$id = $socialUser->id;
    				$email = $socialUser->email;

    				$userFactory = new UserFactory();

    				if ($userFactory->schoolEmailIsTaken($email) == true) {
    					return redirect()->route('profile.main')->withErrors(['linkState' => trans('messages.profile.account.school_link_messages.already_linked')]);
    				} else {
    					$user = Auth::user();

    					$user->setGoogleId($id);
    					$user->setGoogleEmail($email);

    					$user->setBelongsToSchool(true);

    					$user->save();

    					return redirect()->route('profile.main');
    				}

    			} else {
    				return redirect()->route('profile.main')->withErrors(['linkState' => trans('messages.profile.account.school_link_messages.not_valid_email')]);
    			}

    		} else {
    			return redirect()->route('profile.main')->withErrors(['linkState' => trans('messages.profile.account.school_link_messages.not_valid_email')]);
    		}
    	} else {
    		return redirect()->route('profile.main')->withErrors(['linkState' => trans('messages.profile.account.school_link_messages.error')]);
    	}
    }

    public function unlinkGoogle()
    {
    	$user = Auth::user();
    	$userFactory = new UserFactory();

    	$userFactory->unlinkGoogleAccount($user->userId());

    	return redirect()->route('profile.main')->withErrors(['linkState' => trans('messages.profile.account.school_link_messages.unlinked')]);
    }

    public function password()
    {
    	$user = Auth::user();
    	$propositionFactory = new PropositionFactory();
    	$propositionsCount = $propositionFactory->getPropositionsCountByUser($user->userId());

    	$viewUser = [
    			'fullName' => $user->firstName() . " " . $user->lastName(),
    			'firstName' => $user->firstName(),
    			'lastName' => $user->lastName(),
    			'contactEmail' => $user->contactEmail(),
    			'email' => $user->email(),
    			'avatar' => $user->avatar(),
    			'belongsToSchool' => $user->belongsToSchool(),
    			'schoolEmail' => $user->googleEmail(),
    			'role' => $user->role(),
    			'propositionsCount' => $propositionsCount,
    	];

    	return view('account_new.password', ['fullName' => $user->firstName() . " " . $user->lastName(), 'user' => $viewUser]);
    }

    public function password_update(Request $request)
    {
    	$user = Auth::user();
    	$propositionFactory = new PropositionFactory();

    	$validator = Validator::make($request->all(), [
    			'old_password' => 'required',
    			'new_password' => 'required|confirmed|min:5',
    	]);

    	if ($validator->fails()) {

    		return redirect()->back()->withErrors($validator->errors());

    	} else {

    		$user = Auth::user();

    		$old_password = $request->input('old_password');
    		$new_password = $request->input('new_password');
    		if (Auth::attempt(['email' => $user->email(), 'password' => $old_password])) {

    			$user->setPassword(\Hash::make($new_password));
    			$user->save();

    		} else {
    			return redirect()->back()->withErrors([
    					'old_password' => trans('messages.profile.password.wrong'),
    			]);
    		}

    		return redirect()->back()->with('status', trans('messages.profile.password.updated'));

    	}

    }

}