text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2022 Google LLC

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.google.cloud.bigtable</groupId>
    <artifactId>bigtable-hbase-mirroring-client-1.x-parent</artifactId>
    <version>0.1.4-SNAPSHOT</version> <!-- {x-version-update:bigtable-hbase-mirroring:current} -->
  </parent>

  <artifactId>bigtable-hbase-mirroring-client-1.x</artifactId>
  <packaging>jar</packaging>
  <version>0.1.4-SNAPSHOT</version> <!-- {x-version-update:bigtable-hbase-mirroring:current} -->

  <name>${project.groupId}:${project.artifactId}</name>
  <description>
    Bigtable/HBase Mirroring Client conforming to HBase API 1.x. Uses hbase-shaded-client and exposes all internal dependencies.
  </description>

  <dependencies>
    <dependency>
      <groupId>com.google.cloud.bigtable</groupId>
      <artifactId>bigtable-hbase-mirroring-client-core</artifactId>
      <version>0.1.4-SNAPSHOT</version> <!-- {x-version-update:bigtable-hbase-mirroring:current} -->
      <scope>compile</scope>
    </dependency>

    <!-- Test deps -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.truth</groupId>
      <artifactId>truth</artifactId>
      <version>1.1.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>${mockito.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.cloud.bigtable</groupId>
      <artifactId>bigtable-hbase-mirroring-client-core</artifactId>
      <version>0.1.4-SNAPSHOT</version> <!-- {x-version-update:bigtable-hbase-mirroring:current} -->
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <executions>
          <execution>
            <id>enforce</id>
            <configuration>
              <rules>
                <requireUpperBoundDeps>
                  <excludes>
                    <!--
                    bigtable-hbase-mirroring-client-core requires 30.1-android (${guava.version})
                    api-common:1.10.4 requires 30.1.1-android
                     -->
                    <exclude>com.google.guava:guava</exclude>
                  </excludes>
                </requireUpperBoundDeps>
              </rules>
            </configuration>
            <goals>
              <goal>enforce</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <!-- skip due to shaded jars added in during package phase (see below) -->
        <artifactId>clirr-maven-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>

      <!-- copy protobuf-java-format-shaded and core into jar -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <shadedArtifactAttached>false</shadedArtifactAttached>
              <createDependencyReducedPom>true</createDependencyReducedPom>
              <artifactSet>
                <includes>
                  <include>com.google.cloud.bigtable:protobuf-java-format-shaded</include>
                  <include>${project.groupId}:bigtable-hbase-mirroring-client-core</include>
                </includes>
              </artifactSet>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
#include "SearchHeadingManager.h"

#include "Requester.h"
#include "DebugClock.h"
#include "ISABThread.h"
#include "ExtServicePacket.h"
#include "Properties.h"
#include "PacketContainer.h"
#include "RequestData.h"

struct SearchHeadingManager::Impl {
   Impl():
      m_headingCRC( 0 ) {
   }

   uint32 getCRC() const {
      ISABSync sync( m_dataLock );
      return m_headingCRC;
   }

   void getHeadings( CompactSearchHitTypeVector& headings,
                     uint32& crc ) const {
      ISABSync sync( m_dataLock );
      headings = m_headings;
      crc = m_headingCRC;
   }

   void setHeadings( CompactSearchHitTypeVector& headings,
                     uint32 crc ) {
      ISABSync sync( m_dataLock );
      m_headings.swap( headings );
      m_headingCRC = crc;
      m_updateClock = DebugClockSeconds();
   }

   /// @return true if update time is reached.
   bool updateTimeReached() const {
      ISABSync sync( m_dataLock );
      return m_updateClock.getTime() >=
         Properties::getUint32Property( "SEARCH_HEADING_TIMEOUT", 180 );
   }
private:
   /// Data lock for setting and getting variables in this class.
   mutable ISABMutex m_dataLock;

   /// Checksum for headings.
   uint32 m_headingCRC;
   /// Headings fetch from module.
   CompactSearchHitTypeVector m_headings;

   /// Count number of seconds since last update
   DebugClockSeconds m_updateClock;
};

SearchHeadingManager::SearchHeadingManager():
   m_impl( new Impl() ) {
}

SearchHeadingManager::~SearchHeadingManager() {
}

bool SearchHeadingManager::
shouldUpdateSearchHeadings( uint32 headingCRC ) const {
   // if crc mismatch or search heading update time is reached.
   return
      m_impl->getCRC() != headingCRC ||
      m_impl->updateTimeReached();
}

void SearchHeadingManager::
getSearchHeadings( Requester& requester,
                   CompactSearchHitTypeVector& headings,
                   uint32& headingCRC ) {

   //
   // If we haven't fetch any headings yet ( crc = 0 ) or
   // if we have a timeout on headings, then fetch new headings from
   // the ExtServiceModule.
   //
   if ( m_impl->getCRC() == 0 ||
        m_impl->updateTimeReached() ) {

      // Fetch the headings so we can setup the search parser handler
      ExtServiceRequestPacket* extServiceListRequest =
         new ExtServiceRequestPacket( 0,
                                      requester.getNextRequestID(),
                                      m_impl->getCRC() );

      auto_ptr< PacketContainer >
         cont( requester.putRequest( extServiceListRequest,
                                     MODULE_TYPE_EXTSERVICE ) );

      if ( cont.get() ) {
         ExtServiceReplyPacket*
            pack = static_cast< ExtServiceReplyPacket* >( cont->getPacket() );

         if ( pack ) {
            CompactSearchHitTypeVector headings;
            pack->getHitTypes( headings );
            m_impl->setHeadings( headings, pack->getCRC() );
         }
      }
   }

   m_impl->getHeadings( headings, headingCRC );
}

redpajama_set_name: RedPajamaGithub


text:
package com.osiris.component.bootstrap.menu;

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

import javax.el.ValueExpression;
import javax.faces.application.ResourceDependencies;
import javax.faces.application.ResourceDependency;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIPanel;

/**
 *
 * Classe que representa um component de menu item.
 *
 * @author Cristian Urbainski<cristianurbainskips@gmail.com>
 * @since 13/07/2013
 * @version 1.0
 *
 */
@ResourceDependencies({
	@ResourceDependency(library = "javax.faces", 	name = "jsf.js"),
	@ResourceDependency(library = "primefaces", 	name = "jquery/jquery.js"),
	@ResourceDependency(library = "primefaces", 	name = "primefaces.js"),
	@ResourceDependency(library = "js", 			name = "bootstrap.min.js"),
	@ResourceDependency(library = "modal", 			name = "modal.js"),
	@ResourceDependency(library = "css", 			name = "bootstrap.min.css"),
	@ResourceDependency(library = "css", 			name = "menu.css")
})
@FacesComponent(value = UIMenuItem.COMPONENT_TYPE)
public class UIMenuItem extends UIPanel {

	/**
	 * Tipo do componente.
	 */
	public static final String COMPONENT_TYPE = "com.osiris.component.bootstrap.MenuItem";

	/**
	 * Familia do componente.
	 */
	public static final String COMPONENT_FAMILY = "com.osiris.component.bootstrap";

	/**
	 * Renderizador padrão do componente.
	 */
	private static final String DEFAULT_RENDERER = "com.osiris.component.bootstrap.MenuItemRenderer";

	/**
	 * Pacote otimizado do componente.
	 */
	private static final String OPTIMIZED_PACKAGE = "com.osiris.component.bootstrap.";

	/**
	 * Classe interna para definição dos parametros da classe.
	 *
	 * @author Cristian Urbainski<cristianurbainskips@gmail.com>
	 * @since 18/07/2013
	 * @version 1.0
	 *
	 */
	protected enum PropertyKeys {
		/**
		 * Se está ativo.
		 */
		active,

		/**
		 * Label que ser� mostrado pelo componente.
		 */
		label,

		/**
		 * Localização que será aberta pelo componente.
		 */
		location,

		/**
		 * Estilo css do componente.
		 */
		style,

		/**
		 * Classe de estilo extra do componente.
		 */
		styleClass;

		/**
		 * Valor que será retornado.
		 */
		private String toString;

		/**
		 * Construtor default do componente.
		 * @param toString valor da string
		 */
		PropertyKeys(String toString) {
			this.toString = toString;
		}

		/**
		 * Construtor default do componente.
		 */
		PropertyKeys() { }

		/**
		 * Método que retorna o toString da string interna.
		 * @return toString da string interna
		 */
		public String toString() {
			return ((this.toString != null) ? this.toString : super.toString());
		}
	}

	/**
	 * Construtor defaul do componente.
	 */
	public UIMenuItem() {
		setRendererType(DEFAULT_RENDERER);
	}

	public String getFamily() {
		return COMPONENT_FAMILY;
	}

	public boolean isActive() {
		return (Boolean) getStateHelper().eval(PropertyKeys.active, false);
	}

	/**
	 * Set do active.
	 * @param active
	 */
	public void setActive(boolean active) {
		getStateHelper().put(PropertyKeys.active, active);
		handleAttribute("active", active);
	}

	/**
	 * Set do label.
	 * @param label
	 */
	public void setLabel(java.lang.String label) {
		getStateHelper().put(PropertyKeys.label, label);
		handleAttribute("label", label);
	}

	public java.lang.String getLabel() {
		return (java.lang.String) getStateHelper().eval(PropertyKeys.label, null);
	}

	/**
	 * Set do location.
	 * @param location
	 */
	public void setLocation(java.lang.String location) {
		getStateHelper().put(PropertyKeys.location, location);
		handleAttribute("location", location);
	}

	public java.lang.String getLocation() {
		return (java.lang.String) getStateHelper().eval(PropertyKeys.location, null);
	}

	public java.lang.String getStyle() {
		return (java.lang.String) getStateHelper().eval(PropertyKeys.style, null);
	}

	/**
	 * Set do style.
	 * @param style
	 */
	public void setStyle(java.lang.String style) {
		getStateHelper().put(PropertyKeys.style, style);
		handleAttribute("style", style);
	}

	public java.lang.String getStyleClass() {
		return (java.lang.String) getStateHelper().eval(PropertyKeys.styleClass, null);
	}

	/**
	 * Set do styleClass.
	 * @param styleClass
	 */
	public void setStyleClass(java.lang.String styleClass) {
		getStateHelper().put(PropertyKeys.styleClass, styleClass);
		handleAttribute("styleClass", styleClass);
	}

	/**
	 * Método hanfleAttributes copiado do primefaces.
	 *
	 * @param name nome
	 * @param value objeto
	 */
	@SuppressWarnings("unchecked")
	public void handleAttribute(String name, Object value) {
		List<String> setAttributes = (List<String>)
				this.getAttributes().get("javax.faces.component.UIComponentBase.attributesThatAreSet");

		if (setAttributes == null) {
			String cname = this.getClass().getName();
			if (cname != null && cname.startsWith(OPTIMIZED_PACKAGE)) {
				setAttributes = new ArrayList<String>(Integer.parseInt("6"));
				this.getAttributes().put("javax.faces.component.UIComponentBase.attributesThatAreSet", setAttributes);
			}
		}
		if (setAttributes != null) {
			if (value == null) {
				ValueExpression ve = getValueExpression(name);
				if (ve == null) {
					setAttributes.remove(name);
				} else if (!setAttributes.contains(name)) {
					setAttributes.add(name);
				}
			}
		}
	}
}


text:
<?php
/**
 * Shop System SDK:
 * - Terms of Use can be found under:
 * https://github.com/wirecard/paymentSDK-php/blob/master/_TERMS_OF_USE
 * - License can be found under:
 * https://github.com/wirecard/paymentSDK-php/blob/master/LICENSE
 */

// # Credit based on pay

// This example shows how SEPA Credit Transfer can be used to refund an Sofort. payment

// The method `credit` of the _transactionService_ provides the means
// to transfer credits to a specific bank account.

// ## Required objects

// To include the necessary files, we use the composer for PSR-4 autoloading.
require __DIR__ . '/../../../vendor/autoload.php';
require __DIR__ . '/../../inc/common.php';
require __DIR__ . '/../../configuration/globalconfig.php';

require __DIR__ . '/../../inc/header.php';

use Wirecard\PaymentSdk\Entity\AccountHolder;
use Wirecard\PaymentSdk\Entity\Mandate;
use Wirecard\PaymentSdk\Response\FailureResponse;
use Wirecard\PaymentSdk\Response\SuccessResponse;
use Wirecard\PaymentSdk\Transaction\SepaCreditTransferTransaction;
use Wirecard\PaymentSdk\TransactionService;

if (!isset($_POST['parentTransactionId'])) {
    ?>
    <form action="credit-based-on-pay.php" method="post">

            Parent transaction id:
            <input id="parentTransactionId" name="parentTransactionId" value="" class="form-control"/>

        <button type="submit" class="btn btn-primary">Credit</button>
    </form>
    <?php
} else {
// ### Transaction related objects

    $accountHolder = new AccountHolder();
// The account holder last name is required.
    $accountHolder->setLastName('Doe');
// The account holders first name is optional.
// For complete list of all fields please visit https://doc.wirecard.com/RestApi_Fields.html
    $accountHolder->setFirstName('Jane');

// A mandate with ID and signed date is required.
    $mandate = new Mandate('12345678');

// ### Transaction

// Create a `SepaCreditTransferTransaction` object, which contains all relevant data for the credit process.
    $transaction = new SepaCreditTransferTransaction();

    // Providing the parent transaction id is enough to make a successful "refund". If you wish to transfer
    // a different amount you can set it via `$transaction->setAmount(new Amount(10, 'EUR');`
    if (array_key_exists('parentTransactionId', $_POST)) {
        $transaction->setParentTransactionId($_POST['parentTransactionId']);
    }

    $transaction->setAccountHolder($accountHolder);
    $transaction->setMandate($mandate);

// ### Transaction Service

// The service is used to execute the credit (pending-credit) operation itself. A response object is returned.
    $transactionService = new TransactionService($config);
    $response = $transactionService->credit($transaction);

// ## Response handling

// The response from the service can be used for disambiguation.
// In case of a successful transaction, a `SuccessResponse` object is returned.
    if ($response instanceof SuccessResponse) {
        echo 'Refund via SEPA Credit Transfer successfully completed.
';
        echo getTransactionLink($baseUrl, $response);
        ?>

        <form action="../SepaDirectDebit/cancel.php" method="post">
            <input type="hidden" name="parentTransactionId" value="<?= $response->getTransactionId() ?>"/>
            <button type="submit" class="btn btn-primary">Cancel the credit</button>
        </form>
        <?php
// In case of a failed transaction, a `FailureResponse` object is returned.
    } elseif ($response instanceof FailureResponse) {
        // In our example we iterate over all errors and display them in a raw state.
        // You should handle them based on the given severity as error, warning or information.
        foreach ($response->getStatusCollection() as $status) {
            /**
             * @var $status \Wirecard\PaymentSdk\Entity\Status
             */
            $severity = ucfirst($status->getSeverity());
            $code = $status->getCode();
            $description = $status->getDescription();
            echo sprintf('%s with code %s and message "%s" occurred.
', $severity, $code, $description);
        }
    }
}

require __DIR__ . '/../../inc/footer.php';


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/edit"
        android:icon="@drawable/ic_mode_edit_black_24dp"
        android:title="@string/EditMenuItem" />

    <item android:id="@+id/show"
        android:icon="@drawable/ic_help_black_24dp"
        android:title="@string/ShowMenuItem" />

</menu>


text:
alter table "workflow" add column retention_policy TEXT;
update workflow set retention_policy = 'return (git_branch_exist == "false" and run_days_before < 2) or run_days_before < 365';
alter table "workflow" alter column retention_policy SET NOT NULL;

alter table "workflow" add column max_runs INT;
update workflow set max_runs = 255;
alter table "workflow" alter column max_runs SET NOT NULL;
alter table "workflow" alter column max_runs SET DEFAULT 255;

-- +migrate Down
alter table "workflow" drop column retention_policy;


text:
wget http://apache.rediris.es/tomcat/tomcat-8/v8.0.26/bin/apache-tomcat-8.0.26.zip
unzip apache-tomcat-8.0.26.zip

mv apache-tomcat-8.0.26 apache-tomcat

export CATALINA_HOME=$INSPWD/apache-tomcat
echo "export CATALINA_HOME=\"$INSPWD/apache-tomcat\"" >> ~/.bashrc

chmod +x $INSPWD/apache-tomcat/bin/*.sh


text:
ofxPixelPusherUnit::ofxPixelPusherUnit(PixelPusher *pusher) {
    updatePixelPusher(pusher);

    if (100 < pusher->updatePeriod && pusher->updatePeriod < 1000000) {
        sleepTime = (pusher->updatePeriod / 1000) + 1;
    }
}

ofxPixelPusherUnit::~ofxPixelPusherUnit() {
    stopThread();
    while (isThreadRunning())
        ;

    udp.Close();
}

void ofxPixelPusherUnit::updatePixelPusher(PixelPusher *pusher) {
    if (lock()) {
        this->pusher = pusher;
        unlock();
    }
}

void ofxPixelPusherUnit::start() {
    udp.Create();
    udp.Connect(pusher->getIpAddress().c_str(), SEND_PORT);

    ofThread::startThread();
}

void ofxPixelPusherUnit::threadedFunction() {
    while (isThreadRunning()) {
        if (lock()) {
            threadedUpdate();
            unlock();
            sleep(sleepTime);
        }
    }
}

void ofxPixelPusherUnit::threadedUpdate() {
    vector<uint8_t> *packet = pusher->serialize();
    if (packet->size() > 0) {
        if (100 < pusher->updatePeriod && pusher->updatePeriod < 1000000) {
            sleepTime = (pusher->updatePeriod / 1000) + 1;
        }

        uint8_t buf[packet->size()];
        for (int i = 0; i < packet->size(); i++) {
            buf[i] = (*packet)[i];
        }

        udp.Send((const char *)buf, packet->size());
    }
}

bool ofxPixelPusherUnit::isInGroup(int groupIndex, int controllerIndex) {
    if (pusher->groupOrdinal != groupIndex) {
        return false;
    }
    if (controllerIndex < 0) {
        return true;
    }
    return pusher->controllerOrdinal == controllerIndex;
}

void ofxPixelPusherUnit::setColor(int index, ofColor color) {
    if (index < pusher->getStripLength()) {
        pusher->getStrips()[index]->setPixel(color.getHex());
    }
}

void ofxPixelPusherUnit::setColor(int index, int position, ofColor color) {
    if (index < pusher->getStripLength()) {
        pusher->getStrips()[index]->setPixel(position, color.getHex());
    }
}


text:
Bulk transforms CFDI XML to PDF using C#.Net WPF

> **Developed using:**
> - Requires E-Iceblue [Spire.PDF](https://www.e-iceblue.com/Introduce/free-pdf-component.html)
> - QRCoder 1.2.9

Download Latest Version
-----------------------
####   Download version [1.0](https://github.com/ragde085/CFDI-XMLtoPDF/raw/master/CFDIXMLtoPDFwpf/Installer/CFDI%20XML%20To%20PDF%20%20-%201.0.zip)
![screenshot](https://github.com/ragde085/CFDI-XMLtoPDF/blob/master/CFDIXMLtoPDFwpf/CFDI%20XMLtoPDF%20UI.png)

Older versions
-----------------------
  Download [Beta 1](https://github.com/ragde085/CFDI-XMLtoPDF/blob/master/CFDIXMLtoPDFwpf/Installer/CFDI%20XML%20To%20PDF%20-%20Beta%201.zip)


text:
body {
  font-family: 'Helvetica', sans-serif;
  background-color: #eee;
}

.button-controls {
  margin-top: 100px;
}
.display-messages {
  margin-top: 35px;
}


text:
package com.gamerscave.acrabackend;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.gamerscave.acrabackend.utils.Saver;

/**
 * This class handles the Settings. It saves user settings and server password and username.
 * The password and username is used for authentication to prevent abuse and deletion of
 * log files when you didn't request it.
 *
 */
public class Settings {
    /**
     * Show a persistent notification from the service?
     */
    public static boolean SHOW_PERSISTENT = true;
    /**
     * Allow a background service?
     */
    public static boolean RUN_BACKGROUND = true;
    /**
     * Allow a thread updating the app while it is open?
     */
    public static boolean AUTO_REFRESH_WHILE_OPEN = true;
    /**
     * The domain
     */
    public static String DOMAIN = null;
    /**
     * The directory the scripts and logs are stored in
     */
    public static String DIRECTORY = null;
    /**
     * Script name
     */
    public static String DELETE_SCRIPT = "androiddelete.php";
    /**
     * Script name
     */
    public static String MAIN_SCRIPT = "android.php";
    /**
     * Script name
     */
    public static String LIST_FILES = "files.php";
    /**
     * Authentication password
     */
    public static String PASSWORD = null;
    /**
     * Authentication username
     */
    public static String USERNAME = null;

    public Settings(Activity c){
        boolean doesExist = Saver.loadBoolean("settingsinit", c);
        if(!doesExist) {
            c.startActivity(new Intent(c, Setup.class));
            Splash.CREATING_SETTINGS = true;
        }else {
            load(c);
            Splash.CREATING_SETTINGS = false;
        }
    }

    public Settings(Context c){
        load(c);
    }

    public static void load(Context c){
        SHOW_PERSISTENT = Saver.loadBoolean("SHOW_PERSISTENT", c);
        RUN_BACKGROUND = Saver.loadBoolean("RUN_BACKGROUND" , c);
        AUTO_REFRESH_WHILE_OPEN = Saver.loadBoolean("AUTO_REFRESH"   , c);
        DOMAIN = Saver.loadString("DOMAIN", c);
        DIRECTORY = Saver.loadString("DIRECTORY", c);
        MAIN_SCRIPT = Saver.loadString("MAIN_SCRIPT", c);
        LIST_FILES = Saver.loadString("LIST_FILES", c);
        DELETE_SCRIPT = Saver.loadString("DELETE_SCRIPT", c);
        USERNAME = Saver.loadString("USERNAME", c);
        PASSWORD = Saver.loadString("PASSWORD", c);
    }

    public static void save(Context c){
        Saver.save("SHOW_PERSISTENT", Boolean.toString(SHOW_PERSISTENT), c);
        Saver.save("RUN_BACKGROUND" , Boolean.toString(RUN_BACKGROUND), c);
        Saver.save("AUTO_REFRESH"   , Boolean.toString(AUTO_REFRESH_WHILE_OPEN), c);
        Saver.save("DOMAIN", DOMAIN, c);
        Saver.save("DIRECTORY", DIRECTORY, c);
        Saver.save("MAIN_SCRIPT", MAIN_SCRIPT, c);
        Saver.save("LIST_FILES", LIST_FILES, c);
        Saver.save("DELETE_SCRIPT", DELETE_SCRIPT, c);
        Saver.save("USERNAME", USERNAME, c);
        Saver.save("PASSWORD", PASSWORD, c);

    }
    public static void save(Context c, String domain, String dir, String core, String list, String delete, String username, String password,
                            boolean sync, boolean allowbg, boolean persistent){
        DOMAIN = domain;
        DIRECTORY = dir;
        MAIN_SCRIPT = core;
        LIST_FILES = list;
        DELETE_SCRIPT = delete;
        USERNAME = username;
        PASSWORD = password;
        AUTO_REFRESH_WHILE_OPEN = sync;
        RUN_BACKGROUND = allowbg;
        SHOW_PERSISTENT = persistent;
        Saver.save("settingsinit", "true", c);
        save(c);
    }
}


text:
package com.google.vinet.data;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import java.time.Instant;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.*;

/**
 * A TimeSlot during which an Isolate is due to have a request fulfilled.
 */
public class IsolateTimeSlot extends TimeSlot implements Datastoreable {
  /** The Datastore Entity name for an IsolateTimeSlot. */
  public static final String ISOLATE_TIME_SLOT_TABLE_NAME = "IsolateTimeSlot";
  /** The ticket associated with this TimeSlot. */
  protected final Key ticket;
  /** The date this IsolateTimeSlot is scheduled on. */
  protected final LocalDate date;
  /** The DatastoreService implementation to depend on. */
  public static DatastoreService datastore;

  /**
   * Construct an IsolateTimeSlot using the properties of the provided Datastore {@code Entity}
   *
   *
The {@code Entity} must have these properties:
   *
   *

   *

   *
   *              Property
   *
   *
   *              Type
   *
   *
   *              Description
   *
   *

   *

   *
   *              startTime
   *
   *
   *              {@link java.lang.String}
   *
   *
   *              The start time of the delivery window.
   *
   *

   *

   *
   *              endTime
   *
   *
   *              {@link java.lang.String}
   *
   *
   *              The end time of the delivery window.
   *
   *

   *

   *
   *              isolateId
   *
   *
   *              {@link java.lang.String}
   *
   *
   *             The id of this Isolate as per the {@code UserService} API.
   *
   *

   *

   *
   *              date
   *
   *
   *              {@link java.lang.String}
   *
   *
   *              The date of delivery. Note: This property must be encoded as a valid ISO date string.
   *
   *

   *

   *
   *              ticketKey
   *
   *
   *              {@link com.google.appengine.api.datastore.Key}
   *
   *
   *              The Datastore key of the ticket associated with this IsolateTimeSlot.
   *
   *

   *

   *
   * @param entity The entity to pull data from in order to construct this IsolateTimeSlot.
   * @see
   *     The Datastore documentation for the {@code Entity} class.
   */
  public IsolateTimeSlot(Entity entity) {
    this(
        Instant.parse((String) entity.getProperty("startTime")),
        Instant.parse((String) entity.getProperty("endTime")),
        new Isolate((String) entity.getProperty("isolateId")),
        LocalDate.parse((String) entity.getProperty("date")),
        KeyFactory.stringToKey((String) entity.getProperty("ticketKey")));
  }

  /**
   * Construct an IsolateTimeSlot.
   *
   * @param start The start of the TimeSlot.
   * @param end The end of the TimeSlot.
   * @param isolate The isolate associated with the TimeSlot.
   * @param date The date on which the TimeSlot is scheduled.
   * @param ticket The Datastore key of the request ticket for this TimeSlot.
   */
  public IsolateTimeSlot(Instant start, Instant end, Isolate isolate, LocalDate date, Key ticket) {
    super(start, end, isolate);
    this.date = date;
    this.ticket = ticket;
  }

  /**
   * @return the {@link Isolate} which this IsolateTimeSlot is linked to.
   */
  public Isolate getIsolate() {
    return (Isolate) registeredUser;
  }

  /**
   * Fetch an Isolate's TimeSlots from Datastore.
   * @param userId The ID of the Isolate who's TimeSlots will be fetched from Datastore.
   * @return The TimeSlots currently in Datastore associated with the provided Isolate's userID.
   */
  public static List<IsolateTimeSlot> getTimeslotsByUserId(String userId) {
    return StreamSupport.stream(queryTimeSlots(userId).asIterable().spliterator(), true)
        .map(IsolateTimeSlot::new)
        .collect(Collectors.toList());
  }

  /**
   * Create a PreparedQuery for Datastore that will return the IsolateTimeSlots associated with the provided userId.
   * @param userId The ID of the Isolate who's TimeSlots will be returned by the PreparedQuery.
   * @return A PreparedQuery which, when executed, will return the IsolateTimeSlots linked to the provided Isolate's userID.
   */
  private static PreparedQuery queryTimeSlots(String userId) {
    Query query =
        new Query(ISOLATE_TIME_SLOT_TABLE_NAME)
            .setFilter(new Query.FilterPredicate("userId", Query.FilterOperator.EQUAL, userId));

    return datastore.prepare(query);
  }

  /** Put this IsolateTimeSlot into Datastore. */
  @Override
  public void toDatastore() {
    /* TODO: Check that all instance variables are non-null before posting to Datastore. */
    final Entity entity = new Entity(ISOLATE_TIME_SLOT_TABLE_NAME);
    entity.setProperty("ticketKey", KeyFactory.keyToString(ticket));
    entity.setProperty("isolateId", this.getIsolate().getUserId());
    entity.setProperty("date", date.toString());
    entity.setProperty("startTime", start.toString());
    entity.setProperty("endTime", end.toString());

    datastore.put(entity);
  }
}


text:
"""
Test module for accumulating hook (cxflow.hooks.accumulate_variables_hook).
"""

import numpy as np
import pytest

from cxflow.hooks.accumulate_variables import AccumulateVariables

_ITERS = 9
_EXAMPLES = 5
_FEATURES = 6

def get_batch():
    batch = {'input': np.ones((_EXAMPLES, _FEATURES)),
             'target': np.zeros(_EXAMPLES),
             'accuracy': np.ones(_EXAMPLES),
             'cost': np.ones(_EXAMPLES),
             'not_iter': 1}
    return batch

def test_accumulating_present_variables():
    """Test accumulating selected variables which are present in a batch."""

    selected_vars = ["accuracy", "cost"]
    stream_name = "train"
    accum_hook = AccumulateVariables(variables=selected_vars)

    for _ in range(_ITERS):
        batch = get_batch()
        accum_hook.after_batch(stream_name, batch)

    for var in selected_vars:
        assert len(accum_hook._accumulator[stream_name][var]) == _EXAMPLES * _ITERS
        assert np.array_equal(accum_hook._accumulator[stream_name][var],
                                       np.ones(_EXAMPLES * _ITERS))

_VARS_ERROR = [(["accuracy", "cost", "classes"], KeyError),
               (["accuracy", "cost", "not_iter"], TypeError)]

@pytest.mark.parametrize('vars, error', _VARS_ERROR)
def test_raise_exception(vars, error):
    """Test raising an exception if variable is not present in a batch/variable is not iterable."""

    selected_vars = vars
    stream_name = "train"
    accum_hook = AccumulateVariables(variables=selected_vars)
    batch = get_batch()
    with pytest.raises(error):
        accum_hook.after_batch(stream_name, batch)

def test_init_accumulator():
    """Test reseting accumulator after epoch."""

    selected_vars = ["accuracy", "cost"]
    stream_name = "train"
    accum_hook = AccumulateVariables(variables=selected_vars)

    for _ in range(_ITERS):
        batch = get_batch()
        accum_hook.after_batch(stream_name, batch)

    accum_hook.after_epoch()
    assert not accum_hook._accumulator


text:
// Copyright 2016 Twitter. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.twitter.heron.scheduler;

import java.net.URI;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.twitter.heron.api.generated.TopologyAPI;
import com.twitter.heron.packing.roundrobin.RoundRobinPacking;
import com.twitter.heron.scheduler.dryrun.SubmitDryRunResponse;
import com.twitter.heron.scheduler.utils.LauncherUtils;
import com.twitter.heron.spi.common.Config;
import com.twitter.heron.spi.common.Key;
import com.twitter.heron.spi.packing.IPacking;
import com.twitter.heron.spi.packing.PackingException;
import com.twitter.heron.spi.scheduler.ILauncher;
import com.twitter.heron.spi.statemgr.IStateManager;
import com.twitter.heron.spi.statemgr.SchedulerStateManagerAdaptor;
import com.twitter.heron.spi.uploader.IUploader;
import com.twitter.heron.spi.uploader.UploaderException;
import com.twitter.heron.spi.utils.PackingTestUtils;
import com.twitter.heron.spi.utils.ReflectionUtils;

import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({LauncherUtils.class, ReflectionUtils.class})
public class SubmitterMainTest {
  private static final String TOPOLOGY_NAME = "topologyName";

  private static final String STATE_MANAGER_CLASS = "STATE_MANAGER_CLASS";
  private static final String LAUNCHER_CLASS = "LAUNCHER_CLASS";
  private static final String PACKING_CLASS = "PACKING_CLASS";
  private static final String UPLOADER_CLASS = "UPLOADER_CLASS";

  private IStateManager statemgr;
  private ILauncher launcher;
  private IUploader uploader;

  private Config config;

  private TopologyAPI.Topology topology;

  @Before
  public void setUp() throws Exception {
    // Mock objects to be verified
    IPacking packing = mock(IPacking.class);
    statemgr = mock(IStateManager.class);
    launcher = mock(ILauncher.class);
    uploader = mock(IUploader.class);

    // Mock ReflectionUtils stuff
    PowerMockito.spy(ReflectionUtils.class);
    PowerMockito.doReturn(statemgr)
        .when(ReflectionUtils.class, "newInstance", STATE_MANAGER_CLASS);
    PowerMockito.doReturn(launcher)
        .when(ReflectionUtils.class, "newInstance", LAUNCHER_CLASS);
    PowerMockito.doReturn(packing)
        .when(ReflectionUtils.class, "newInstance", PACKING_CLASS);
    PowerMockito.doReturn(uploader)
        .when(ReflectionUtils.class, "newInstance", UPLOADER_CLASS);

    config = mock(Config.class);
    when(config.getStringValue(Key.STATE_MANAGER_CLASS))
        .thenReturn(STATE_MANAGER_CLASS);
    when(config.getStringValue(Key.LAUNCHER_CLASS))
        .thenReturn(LAUNCHER_CLASS);
    when(config.getStringValue(Key.PACKING_CLASS))
        .thenReturn(PACKING_CLASS);
    when(config.getStringValue(Key.UPLOADER_CLASS))
        .thenReturn(UPLOADER_CLASS);

    when(packing.pack())
        .thenReturn(PackingTestUtils.testPackingPlan(TOPOLOGY_NAME, new RoundRobinPacking()));

    topology = TopologyAPI.Topology.getDefaultInstance();
  }

  @Test
  public void testValidateSubmit() throws Exception {
    SubmitterMain submitterMain = new SubmitterMain(config, topology);
    SchedulerStateManagerAdaptor adaptor = mock(SchedulerStateManagerAdaptor.class);
    // Topology is not running
    when(adaptor.isTopologyRunning(eq(TOPOLOGY_NAME))).thenReturn(null);
    submitterMain.validateSubmit(adaptor, TOPOLOGY_NAME);
    when(adaptor.isTopologyRunning(eq(TOPOLOGY_NAME))).thenReturn(false);
    submitterMain.validateSubmit(adaptor, TOPOLOGY_NAME);
  }

  @Test(expected = TopologySubmissionException.class)
  public void testValidateSubmitAlreadyRunning() throws Exception {
    SubmitterMain submitterMain = new SubmitterMain(config, topology);
    SchedulerStateManagerAdaptor adaptor = mock(SchedulerStateManagerAdaptor.class);
    // Topology is running
    when(adaptor.isTopologyRunning(eq(TOPOLOGY_NAME))).thenReturn(true);
    submitterMain.validateSubmit(adaptor, TOPOLOGY_NAME);
  }

  @Test(expected = TopologySubmissionException.class)
  public void testSubmitTopologyAlreadyRunning() throws Exception {
    // Topology is running
    SubmitterMain submitterMain = spy(new SubmitterMain(config, topology));
    doThrow(new TopologySubmissionException("")).when(submitterMain)
        .validateSubmit(any(SchedulerStateManagerAdaptor.class), anyString());
    try {
      submitterMain.submitTopology();
    } finally {
      verify(uploader, atLeastOnce()).close();
      verify(launcher, atLeastOnce()).close();
      verify(statemgr, atLeastOnce()).close();
    }
  }

  @Test(expected = UploaderException.class)
  public void testSubmitTopologyClassNotExist() throws Exception {
    final String CLASS_NOT_EXIST = "class_not_exist";
    when(config.getStringValue(Key.UPLOADER_CLASS)).thenReturn(CLASS_NOT_EXIST);
    SubmitterMain submitterMain = spy(new SubmitterMain(config, topology));
    doNothing().when(submitterMain)
        .validateSubmit(any(SchedulerStateManagerAdaptor.class), anyString());
    try {
      submitterMain.submitTopology();
    } finally {
      verify(uploader, never()).close();
      verify(launcher, never()).close();
      verify(statemgr, never()).close();
      when(config.getStringValue(Key.UPLOADER_CLASS)).thenReturn(UPLOADER_CLASS);
    }
  }

  @Test(expected = UploaderException.class)
  public void testSubmitTopologyUploaderException() throws Exception {
    SubmitterMain submitterMain = spy(new SubmitterMain(config, topology));
    doNothing().when(submitterMain)
        .validateSubmit(any(SchedulerStateManagerAdaptor.class), anyString());
    doThrow(new UploaderException("")).when(submitterMain).uploadPackage(eq(uploader));
    try {
      submitterMain.submitTopology();
    } finally {
      verify(uploader, never()).undo();
      verify(uploader).close();
      verify(launcher).close();
      verify(statemgr).close();
    }
  }

  @Test(expected = PackingException.class)
  public void testSubmitTopologyLauncherException() throws Exception {
    SubmitterMain submitterMain = spy(new SubmitterMain(config, topology));
    doNothing().when(submitterMain)
        .validateSubmit(any(SchedulerStateManagerAdaptor.class), anyString());
    final URI packageURI = new URI("mock://uri:924/x#ke");
    doReturn(packageURI).when(submitterMain).uploadPackage(eq(uploader));
    doThrow(new PackingException("")).when(submitterMain)
        .callLauncherRunner(Mockito.any(Config.class));
    submitterMain.submitTopology();
  }

  @Test(expected = SubmitDryRunResponse.class)
  public void testSubmitTopologyDryRun() throws Exception {
    SubmitterMain submitterMain = spy(new SubmitterMain(config, topology));
    when(config.getBooleanValue(Key.DRY_RUN)).thenReturn(true);
    try {
      submitterMain.submitTopology();
    } finally {
      /* under dry-run mode, the program should not
         1. upload topology package
         2. validate that topology is not running
       */
      verify(uploader, never()).uploadPackage();
      verify(statemgr, never()).initialize(any(Config.class));
    }
  }

  @Test
  public void testSubmitTopologySuccessful() throws Exception {
    when(config.getBooleanValue(Key.DRY_RUN)).thenReturn(false);
    SubmitterMain submitterMain = spy(new SubmitterMain(config, topology));
    doNothing().when(submitterMain)
        .validateSubmit(any(SchedulerStateManagerAdaptor.class), anyString());
    doNothing().when(submitterMain).callLauncherRunner(Mockito.any(Config.class));
    submitterMain.submitTopology();
  }
}


text:
import { BLOCK } from '../constants/tokens';
import indent from '../util/indent';

class Block {
  constructor(statements) {
    this.token = BLOCK;
    this.statements = statements;
  }

  toString() {
    return `Block(\n${indent(2, this.statements.join(',\n'))}\n)`;
  }
}

export default function creator(statements) {
  return new Block(statements);
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>VSTGUI: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxydocu.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Modules

Namespaces

Classes

Class List

Class Index

Class Hierarchy

Class Members

IFontPainter Member List
This is the complete list of members for IFontPainter, including all inherited members.

drawString(CDrawContext *context, const CString &string, const CPoint &p, bool antialias=true)=0	IFontPainter	 [pure virtual]

getStringWidth(CDrawContext *context, const CString &string, bool antialias=true)=0	IFontPainter	 [pure virtual]

~IFontPainter()	IFontPainter	 [inline, virtual]

<address style="text-align: right;">Generated on Fri Nov 22 11:09:33 2013 for VSTGUI by

 1.6.1 </address>


text:
import sys

from mako import exceptions, compat
from mako.template import Template
from mako.lookup import TemplateLookup
from mako.compat import u
from test.util import result_lines
from test import TemplateTest
from test import requires_pygments_14, requires_no_pygments_exceptions

class ExceptionsTest(TemplateTest):
    def test_html_error_template(self):
        """test the html_error_template"""
        code = """
% i = 0
"""
        try:
            template = Template(code)
            template.render_unicode()
            assert False
        except exceptions.CompileException:
            html_error = exceptions.html_error_template().render_unicode()
            assert ("CompileException: Fragment 'i = 0' is not "
                    "a partial control statement at line: 2 char: 1") in html_error
            assert '


text:
package gnu.javax.swing.text.html.parser;

import gnu.java.lang.CPStringBuilder;

import gnu.javax.swing.text.html.parser.models.node;
import gnu.javax.swing.text.html.parser.models.transformer;

import java.util.BitSet;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.ListIterator;

import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.parser.*;

/**
 *
The HTML content validator, is responsible for opening and
 * closing elements with optional start/end tags, detecting
 * the wrongly placed html tags and reporting errors. The working instance
 * is the inner class inside the {@link javax.swing.text.html.parser.Parser }
 *

 *
This class could potentially
 * provide basis for automated closing and insertion of the html tags,
 * correcting the found html errors.
 * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
 */
public abstract class htmlValidator
{
  /**
   * The tag reference, holding additional information that the tag
   * has been forcibly closed.
   */
  protected class hTag
  {
    protected final Element element;
    protected final HTML.Tag tag;
    protected final TagElement tgElement;
    protected boolean forcibly_closed;
    protected node validationTrace;

    protected hTag(TagElement an_element)
    {
      element = an_element.getElement();
      tag = an_element.getHTMLTag();
      tgElement = an_element;

      if (element.content != null)
        validationTrace = transformer.transform(element.content, dtd);
    }

    /**
     * This is called when the tag must be forcibly closed because
     * it would make the newly appearing tag invalid.
     * The parser is not notified about such event (just the error
     * is reported). For such tags, the closing message does not
     * appear when later reaching the end of stream. The exception is
     * the <head> tag: the parser is notified about its silent closing
     * when <body> or other html content appears.
     */
    protected void forciblyCloseDueContext()
    {
      forcibly_closed = true;
    }

    /**
     * This is called when the tag must be forcibly closed after
     * reaching the end of stream. The parser is notified as if
     * closing the tag explicitly.
     */
    protected void forciblyCloseDueEndOfStream()
    {
      forcibly_closed = true;
      handleSupposedEndTag(element);
    }
  }

  /**
   * The DTD, providing information about the valid document structure.
   */
  protected final DTD dtd;

  /**
  * The stack, holding the current tag context.
  */
  protected final LinkedList stack = new LinkedList();

  /**
   * Creates a new tag stack, using the given DTD.
   * @param a_dtd A DTD, providing the information about the valid
   * tag content.
   */
  public htmlValidator(DTD a_dtd)
  {
    dtd = a_dtd;
  }

  /**
   * Close all opened tags (called at the end of parsing).
   */
  public void closeAll()
  {
    hTag h;
    while (!stack.isEmpty())
      {
        h = (hTag) stack.getLast();
        if (!h.forcibly_closed && !h.element.omitEnd())
          s_error("Unclosed <" + h.tag + ">, closing at the end of stream");

        handleSupposedEndTag(h.element);

        closeTag(h.tgElement);
      }
  }

  /**
   * Remove the given tag from the stack or (if found) from the list
   * of the forcibly closed tags.
   */
  public boolean closeTag(TagElement tElement)
  {
    HTML.Tag tag = tElement.getHTMLTag();
    hTag x;
    hTag close;

    if (!stack.isEmpty())
      {
        ListIterator iter = stack.listIterator(stack.size());

        while (iter.hasPrevious())
          {
            x = (hTag) iter.previous();
            if (tag.equals(x.tag))
              {
                if (x.forcibly_closed && !x.element.omitEnd())
                  s_error("The tag <" + x.tag +
                          "> has already been forcibly closed"
                         );

                // If the tag has a content model defined, forcibly close all
                // tags that were opened after the tag being currently closed.
                closing:
                if (x.element.content != null)
                  {
                    iter = stack.listIterator(stack.size());
                    while (iter.hasPrevious())
                      {
                        close = (hTag) iter.previous();
                        if (close == x)
                          break closing;
                        handleSupposedEndTag(close.element);
                        iter.remove();
                      }
                  }

                stack.remove(x);
                return true;
              }
          }
      }
    s_error("Closing unopened <" + tag + ">");
    return false;
  }

  /**
   * Add the given HTML tag to the stack of the opened tags. Forcibly closes
   * all tags in the stack that does not allow this tag in they content (error
   * is reported).
   * @param element
   */
  public void openTag(TagElement tElement, htmlAttributeSet parameters)
  {
    // If this is a fictional call, the message from the parser
    // has recursively returned - ignore.
    if (tElement.fictional())
      return;

    validateParameters(tElement, parameters);

    // If the stack is empty, start from HTML
    if (stack.isEmpty() && tElement.getHTMLTag() != HTML.Tag.HTML)
      {
        Element html = dtd.getElement(HTML.Tag.HTML.toString());
        openFictionalTag(html);
      }

    Object v = tagIsValidForContext(tElement);
    if (v != Boolean.TRUE)
      {
        // The tag is not valid for context, the content
        // model suggest to open another tag.
        if (v instanceof Element)
          {
            int n = 0;
            while (v instanceof Element && (n++ < 100))
              {
                Element fe = (Element) v;

                // notify the content model that we add the proposed tag
                node ccm = getCurrentContentModel();
                if (ccm != null)
                  ccm.show(fe);
                openFictionalTag(fe);

                Object vv = tagIsValidForContext(tElement);
                if (vv instanceof Element) // One level of nesting is supported.
                  {
                    openFictionalTag((Element) vv);

                    Object vx = tagIsValidForContext(tElement);
                    if (vx instanceof Element)
                      openFictionalTag((Element) vx);
                  }
                else if (vv == Boolean.FALSE)
                  {
                    // The tag is still not valid for the current
                    // content after opening a fictional element.
                    if (fe.omitEnd())
                      {
                        // close the previously opened fictional tag.
                        closeLast();
                        vv = tagIsValidForContext(tElement);
                        if (vv instanceof Element)

                          // another tag was suggested by the content model
                          openFictionalTag((Element) vv);
                      }
                  }
                v = tagIsValidForContext(tElement);
              }
          }
        else // If the current element has the optional end tag, close it.
          {
            if (!stack.isEmpty())
              {
                closing:
                do
                  {
                    hTag last = (hTag) stack.getLast();
                    if (last.element.omitEnd())
                      {
                        closeLast();
                        v = tagIsValidForContext(tElement);
                        if (v instanceof Element) // another tag was suggested by the content model
                          {
                            openFictionalTag((Element) v);
                            break closing;
                          }
                      }
                    else
                      break closing;
                  }
                while (v == Boolean.FALSE && !stack.isEmpty());
              }
          }
      }

    stack.add(new hTag(tElement));
  }

  /**
   * Clear the stack.
   */
  public void restart()
  {
    stack.clear();
  }

  /**
   * Check if this tag is valid for the current context. Return Boolean.True if
   * it is OK, Boolean.False if it is surely not OK or the Element that the
   * content model recommends to insert making the situation ok. If Boolean.True
   * is returned, the content model current position is moved forward. Otherwise
   * this position remains the same.
   *
   * @param tElement
   * @return
   */
  public Object tagIsValidForContext(TagElement tElement)
  {
    // Check the current content model, if one is available.
    node cv = getCurrentContentModel();

    if (cv != null)
      return cv.show(tElement.getElement());

    // Check exclusions and inclusions.
    ListIterator iter = stack.listIterator(stack.size());
    hTag t = null;
    final int idx = tElement.getElement().index;

    // Check only known tags.
    if (idx >= 0)
      {
        BitSet inclusions = new BitSet();
        while (iter.hasPrevious())
          {
            t = (hTag) iter.previous();
            if (! t.forcibly_closed)
              {
                if (t.element.exclusions != null
                    && t.element.exclusions.get(idx))
                  return Boolean.FALSE;

                if (t.element.inclusions != null)
                  inclusions.or(t.element.inclusions);
              }
          }
        if (! inclusions.get(idx))
          {
            // If we need to insert something, and cannot do this, but
            // it is allowed to insert the paragraph here, insert the
            // paragraph.
            Element P = dtd.getElement(HTML_401F.P);
            if (inclusions.get(P.index))
              return P;
            else
              return Boolean.FALSE;
          }
      }
    return Boolean.TRUE;
  }

  /**
   * Validate tag without storing in into the tag stack. This is called
   * for the empty tags and results the subsequent calls to the openTag
   * and closeTag.
   */
  public void validateTag(TagElement tElement, htmlAttributeSet parameters)
  {
    openTag(tElement, parameters);
    closeTag(tElement);
  }

  /**
   * Check for mandatory elements, subsequent to the last tag:
   * @param tElement The element that will be inserted next.
   */
  protected void checkContentModel(TagElement tElement, boolean first)
  {
    if (stack.isEmpty())
      return;

    hTag last = (hTag) stack.getLast();
    if (last.validationTrace == null)
      return;

    Object r = last.validationTrace.show(tElement.getElement());
    if (r == Boolean.FALSE)
      s_error("The <" + last.element + "> does not match the content model " +
              last.validationTrace
             );
    else if (r instanceof Element) // The content model recommends insertion of this element
      {
        if (!first)
          closeTag(last.tgElement);
        handleSupposedStartTag((Element) r);
        openTag(new TagElement((Element) r), null);
      }
  }

  /**
   * The method is called when the tag must be closed because
   * it does not allow the subsequent elements inside its context
   * or the end of stream has been reached. The parser is only
   * informed if the element being closed does not require the
   * end tag (the "omitEnd" flag is set).
   * The closing message must be passed to the parser mechanism
   * before passing message about the opening the next tag.
   *
   * @param element The tag being fictionally (forcibly) closed.
   */
  protected abstract void handleSupposedEndTag(Element element);

  /**
   * The method is called when the validator decides to open the
   * tag on its own initiative. This may happen if the content model
   * includes the element with the optional (supposed) start tag.
   *
   * @param element The tag being opened.
   */
  protected abstract void handleSupposedStartTag(Element element);

  /**
   * Handles the error message. This method must be overridden to pass
   * the message where required.
   * @param msg The message text.
   */
  protected abstract void s_error(String msg);

  /**
   * Validate the parameters, report the error if the given parameter is
   * not in the parameter set, valid for the given attribute. The information
   * about the valid parameter set is taken from the Element, enclosed
   * inside the tag. The method does not validate the default parameters.
   * @param tag The tag
   * @param parameters The parameters of this tag.
   */
  protected void validateParameters(TagElement tag, htmlAttributeSet parameters)
  {
    if (parameters == null ||
        parameters == htmlAttributeSet.EMPTY_HTML_ATTRIBUTE_SET ||
        parameters == SimpleAttributeSet.EMPTY
       )
      return;

    Enumeration enumeration = parameters.getAttributeNames();

    while (enumeration.hasMoreElements())
      {
        validateAttribute(tag, parameters, enumeration);
      }

    // Check for missing required values.
    AttributeList a = tag.getElement().getAttributes();

    while (a != null)
      {
        if (a.getModifier() == DTDConstants.REQUIRED)
          if (parameters.getAttribute(a.getName()) == null)
            {
              s_error("Missing required attribute '" + a.getName() + "' for <" +
                      tag.getHTMLTag() + ">"
                     );
            }
        a = a.next;
      }
  }

  private node getCurrentContentModel()
  {
    if (!stack.isEmpty())
      {
        hTag last = (hTag) stack.getLast();
        return last.validationTrace;
      }
    else
      return null;
  }

  private void closeLast()
  {
    handleSupposedEndTag(((hTag) stack.getLast()).element);
    stack.removeLast();
  }

  private void openFictionalTag(Element e)
  {
    handleSupposedStartTag(e);
    stack.add(new hTag(new TagElement(e, true)));
    if (!e.omitStart())
      s_error("<" + e + "> is expected (supposing it)");
  }

  private void validateAttribute(TagElement tag, htmlAttributeSet parameters,
                                 Enumeration enumeration
                                )
  {
    Object foundAttribute;
    AttributeList dtdAttribute;
    foundAttribute = enumeration.nextElement();
    dtdAttribute = tag.getElement().getAttribute(foundAttribute.toString());
    if (dtdAttribute == null)
      {
        CPStringBuilder valid =
          new CPStringBuilder("The tag <" + tag.getHTMLTag() +
			      "> cannot contain the attribute '" + foundAttribute +
			      "'. The valid attributes for this tag are: "
			      );

        AttributeList a = tag.getElement().getAttributes();

        while (a != null)
          {
            valid.append(a.name.toUpperCase());
            valid.append(' ');
            a = a.next;
          }
        s_error(valid.toString());
      }

    else
      {
        String value = parameters.getAttribute(foundAttribute).toString();

        if (dtdAttribute.type == DTDConstants.NUMBER)
          validateNumberAttribute(tag, foundAttribute, value);

        if (dtdAttribute.type == DTDConstants.NAME ||
            dtdAttribute.type == DTDConstants.ID
           )
          validateNameOrIdAttribute(tag, foundAttribute, value);

        if (dtdAttribute.values != null)
          validateAttributeWithValueList(tag, foundAttribute, dtdAttribute,
                                         value
                                        );
      }
  }

  private void validateAttributeWithValueList(TagElement tag,
                                              Object foundAttribute,
                                              AttributeList dtdAttribute,
                                              String value
                                             )
  {
    if (!dtdAttribute.values.contains(value.toLowerCase()) &&
        !dtdAttribute.values.contains(value.toUpperCase())
       )
      {
        CPStringBuilder valid;
        if (dtdAttribute.values.size() == 1)
          valid =
            new CPStringBuilder("The attribute '" + foundAttribute +
				"' of the tag <" + tag.getHTMLTag() +
				"> cannot have the value '" + value +
				"'. The only valid value is "
				);
        else
          valid =
            new CPStringBuilder("The attribute '" + foundAttribute +
				"' of the tag <" + tag.getHTMLTag() +
				"> cannot have the value '" + value + "'. The " +
				dtdAttribute.values.size() +
				" valid values are: "
				);

        Enumeration vv = dtdAttribute.values.elements();
        while (vv.hasMoreElements())
          {
            valid.append('"');
            valid.append(vv.nextElement());
            valid.append("\"  ");
          }
        s_error(valid.toString());
      }
  }

  private void validateNameOrIdAttribute(TagElement tag, Object foundAttribute,
                                         String value
                                        )
  {
    boolean ok = true;

    if (!Character.isLetter(value.charAt(0)))
      ok = false;

    char c;
    for (int i = 0; i < value.length(); i++)
      {
        c = value.charAt(i);
        if (!(
              Character.isLetter(c) || Character.isDigit(c) ||
              "".indexOf(c) >= 0
            )
           )
          ok = false;
      }
    if (!ok)
      s_error("The '" + foundAttribute + "' attribute of the tag <" +
              tag.getHTMLTag() + "> must start from letter and consist of " +
              "letters, digits, hypens, colons, underscores and periods. " +
              "It cannot be '" + value + "'"
             );
  }

  private void validateNumberAttribute(TagElement tag, Object foundAttribute,
                                       String value
                                      )
  {
    try
      {
        Integer.parseInt(value);
      }
    catch (NumberFormatException ex)
      {
        s_error("The '" + foundAttribute + "' attribute of the tag <" +
                tag.getHTMLTag() + "> must be a valid number and not '" +
                value + "'"
               );
      }
  }
}


text:
package com.ufcg.si1.model;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;

@Entity
@Table(name = "tb_unidade_saude")
public abstract class UnidadeSaude {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id_unidade_saude", nullable = false, unique = true)
	private Long id;

	@Column(name = "descricao_unidade_saude")
	private String descricao;

	@OneToMany(cascade = CascadeType.ALL)
	private List<Especialidade> especialidades;

	@Column(name = "bairro_unidade_saude")
	private String bairro;

	public UnidadeSaude() {

	}

	public UnidadeSaude(String descricao, String bairro) {
		this.especialidades = new ArrayList<Especialidade>();
		this.bairro = bairro;
		this.descricao = descricao;
	}

	public String getDescricao() {
		return this.descricao;
	}

	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}

	public List<Especialidade> getEspecialidades() {

		return this.especialidades;
	}

	public void adicionarEspecialidade(Especialidade esp) {
		this.especialidades.add(esp);
	}

	public Long getId() {
		return this.id;
	}

	public void setId(Long cod) {
		this.id = cod;
	}

	public String getBairro() {
		return this.bairro;
	}

	public void setBairro(String bairro) {
		this.bairro = bairro;
	}

	public abstract double calculaMediaMedicoPaciente();

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		UnidadeSaude other = (UnidadeSaude) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

}


text:
<?php

namespace Esky\Enum;

use Esky\Enum\Mocks;

class Enum_isEqual_Test extends \PHPUnit_Framework_TestCase
{
    public function test_it_returns_true_when_enum_with_the_same_value_is_passed()
    {
        $one = new Mocks\TestEnum(Mocks\TestEnum::ONE);
        $secondOne = new Mocks\TestEnum(Mocks\TestEnum::ONE);

        $equal = $one->isEqual($secondOne);

        $this->assertTrue($equal);
    }

    public function test_it_returns_false_when_enum_with_different_value_is_passed()
    {
        $one = new Mocks\TestEnum(Mocks\TestEnum::ONE);
        $secondOne = new Mocks\TestEnum(Mocks\TestEnum::ONE);

        $equal = $one->isEqual($secondOne);

        $this->assertTrue($equal);
    }

    public function test_it_returns_true_when_basic_type_with_the_same_value_is_passed()
    {
        $one = new Mocks\TestEnum(Mocks\TestEnum::ONE);
        $value = Mocks\TestEnum::TWO;

        $equal = $one->isEqual($value);

        $this->assertFalse($equal);
    }

    public function test_it_returns_false_when_basic_type_with_different_value_is_passed()
    {
        $one = new Mocks\TestEnum(Mocks\TestEnum::ONE);
        $value = Mocks\TestEnum::TWO;

        $equal = $one->isEqual($value);

        $this->assertFalse($equal);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.PlatformUI;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface
{
    /// <summary>
    /// Interaction logic for ExtractInterfaceDialog.xaml
    /// </summary>
    internal partial class ExtractInterfaceDialog : DialogWindow
    {
        private readonly ExtractInterfaceDialogViewModel _viewModel;

        /// <summary>
        /// For test purposes only. The integration tests need to know when the dialog is up and
        /// ready for automation.
        /// </summary>
        internal static event Action TEST_DialogLoaded;

        // Expose localized strings for binding
        public string ExtractInterfaceDialogTitle { get { return ServicesVSResources.ExtractInterface; } }
        public string NewInterfaceName { get { return ServicesVSResources.NewInterfaceName; } }
        public string GeneratedName { get { return ServicesVSResources.GeneratedName; } }
        public string NewFileName { get { return ServicesVSResources.NewFileName; } }
        public string SelectPublicMembersToFormInterface { get { return ServicesVSResources.SelectPublicMembersToFormInterface; } }
        public string SelectAll { get { return ServicesVSResources.SelectAll; } }
        public string DeselectAll { get { return ServicesVSResources.DeselectAll; } }
        public string OK { get { return ServicesVSResources.OK; } }
        public string Cancel { get { return ServicesVSResources.Cancel; } }

        // Use C# Extract Interface helpTopic for C# and VB.
        internal ExtractInterfaceDialog(ExtractInterfaceDialogViewModel viewModel)
            : base(helpTopic: "vs.csharp.refactoring.extractinterface")
        {
            _viewModel = viewModel;
            SetCommandBindings();

            InitializeComponent();
            DataContext = viewModel;

            Loaded += ExtractInterfaceDialog_Loaded;
        }

        private void ExtractInterfaceDialog_Loaded(object sender, RoutedEventArgs e)
        {
            interfaceNameTextBox.Focus();
            interfaceNameTextBox.SelectAll();

            var handler = TEST_DialogLoaded;
            if (handler != null)
            {
                handler();
            }
        }

        private void SetCommandBindings()
        {
            CommandBindings.Add(new CommandBinding(
                new RoutedCommand(
                    "SelectAllClickCommand",
                    typeof(ExtractInterfaceDialog),
                    new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.S, ModifierKeys.Alt) })),
                Select_All_Click));

            CommandBindings.Add(new CommandBinding(
                new RoutedCommand(
                    "DeselectAllClickCommand",
                    typeof(ExtractInterfaceDialog),
                    new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.D, ModifierKeys.Alt) })),
                Deselect_All_Click));
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if (_viewModel.TrySubmit())
            {
                DialogResult = true;
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void Select_All_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.SelectAll();
        }

        private void Deselect_All_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.DeselectAll();
        }

        private void SelectAllInTextBox(object sender, RoutedEventArgs e)
        {
            TextBox textbox = e.OriginalSource as TextBox;
            if (textbox != null && Mouse.LeftButton == MouseButtonState.Released)
            {
                textbox.SelectAll();
            }
        }

        private void OnListViewPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.None)
            {
                ToggleCheckSelection();
                e.Handled = true;
            }
        }

        private void OnListViewDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                ToggleCheckSelection();
                e.Handled = true;
            }
        }

        private void ToggleCheckSelection()
        {
            var selectedItems = Members.SelectedItems.OfType<ExtractInterfaceDialogViewModel.MemberSymbolViewModel>().ToArray();
            var allChecked = selectedItems.All(m => m.IsChecked);
            foreach (var item in selectedItems)
            {
                item.IsChecked = !allChecked;
            }
        }
    }
}


text:
// Copyright (c) 2022, Compiler Explorer Authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

'use strict';

import { Toggles } from '../widgets/toggles';
import * as monaco from 'monaco-editor';
import _ from 'underscore';
import $ from 'jquery';
import { MonacoPane } from './pane';
import { ga } from '../analytics';
import * as monacoConfig from '../monaco-config';
import { PPViewState } from './pp-view.interfaces';
import { Container } from 'golden-layout';
import { MonacoPaneState } from './pane.interfaces';

export class PP extends MonacoPane<monaco.editor.IStandaloneCodeEditor, PPViewState> {
    options: any;

    constructor(hub: any, container: Container, state: PPViewState & MonacoPaneState) {
        super(hub, container, state);
        this.eventHub.emit('ppViewOpened', this.compilerInfo.compilerId);
        this.eventHub.emit('requestSettings');
        this.onOptionsChange();
        if (state && state.ppOutput) {
            this.showPpResults(state.ppOutput);
        } else {
            this.showCompilationLoadingMessage();
        }
    }

    override getInitialHTML(): string {
        return $('#pp').html();
    }

    override createEditor(editorRoot: HTMLElement): monaco.editor.IStandaloneCodeEditor {
        return monaco.editor.create(editorRoot, monacoConfig.extendConfig({
            language: 'plaintext',
            readOnly: true,
            glyphMargin: true,
            lineNumbersMinChars: 3,
        }));
    }

    override registerOpeningAnalyticsEvent(): void {
        ga.proxy('send', {
            hitType: 'event',
            eventCategory: 'OpenViewPane',
            eventAction: 'PP',
        });
    }

    override registerButtons(state: PPViewState & MonacoPaneState): void {
        super.registerButtons(state);
        this.options = new Toggles(this.domRoot.find('.options'), ((state as unknown) as Record<string, boolean>));
        this.options.on('change', this.onOptionsChange.bind(this));
    }

    onOptionsChange() {
        const options = this.options.get();
        this.updateState();
        // update parameters for the compiler and recompile
        this.showCompilationLoadingMessage();
        this.eventHub.emit('ppViewOptionsUpdated', this.compilerInfo.compilerId, {
            'filter-headers': options['filter-headers'],
            'clang-format': options['clang-format'],
        }, true);
    }

    showCompilationLoadingMessage() {
        this.showPpResults('<Compiling...>');
    }

    override resize() {
        const topBarHeight = this.topBar.outerHeight(true) as number;
        this.editor.layout({
            width: this.domRoot.width() as number,
            height: this.domRoot.height() as number - topBarHeight,
        });
    }

    override onCompileResult(compilerId: number, compiler: any, result: any) {
        if (this.compilerInfo.compilerId !== compilerId) return;

        if (result.hasPpOutput) {
            this.showPpResults(result.ppOutput);
        } else if (compiler.supportsPpView) {
            this.showPpResults('<No output>');
        }

        const lang = compiler.lang === 'c' ? 'c' : compiler.lang === 'c++' ? 'cpp' : 'plaintext';
        const model = this.editor.getModel();
        if (model != null && this.getCurrentEditorLanguage() !== lang) {
            monaco.editor.setModelLanguage(model, lang);
        }
    }

    getCurrentEditorLanguage() {
        return this.editor.getModel()?.getLanguageId();
    }

    override getDefaultPaneName() {
        return 'Preprocessor Output';
    }

    showPpResults(results) {
        if (typeof results === 'object') {
            if (results.numberOfLinesFiltered > 0) {
                this.editor.setValue(`/* <${results.numberOfLinesFiltered} lines filtered> */\n\n`
                                     + results.output.trimStart());
            } else {
                this.editor.setValue(results.output.trimStart());
            }
        } else {
            this.editor.setValue(results);
        }

        if (!this.isAwaitingInitialResults) {
            if (this.selection) {
                this.editor.setSelection(this.selection);
                this.editor.revealLinesInCenter(this.selection.startLineNumber,
                    this.selection.endLineNumber);
            }
            this.isAwaitingInitialResults = true;
        }
    }

    override onCompiler(id, compiler, options, editorid, treeid) {
        if (id === this.compilerInfo.compilerId) {
            this.compilerInfo.compilerName = compiler ? compiler.name : '';
            this.compilerInfo.editorId = editorid;
            this.compilerInfo.treeId = treeid;
            this.updateTitle();
            if (compiler && !compiler.supportsPpView) {
                this.editor.setValue('<Preprocessor output is not supported for this compiler>');
            }
        }
    }

    override updateState() {
        this.container.setState(this.currentState());
    }

    currentState() {
        const options = this.options.get();
        const state = {
            id: this.compilerInfo.compilerId,
            editorid: this.compilerInfo.editorId,
            treeid: this.compilerInfo.treeId,
            selection: this.selection,
            'filter-headers': options['filter-headers'],
            'clang-format': options['clang-format'],
        };
        this.paneRenaming.addState(state);
        this.fontScale.addState(state);
        return state;
    }

    override onCompilerClose(id) {
        if (id === this.compilerInfo.compilerId) {
            // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
            // the hierarchy. We can't modify while it's being iterated over.
            this.close();
            _.defer(function (self) {
                self.container.close();
            }, this);
        }
    }

    override close() {
        this.eventHub.unsubscribe();
        this.eventHub.emit('ppViewClosed', this.compilerInfo.compilerId);
        this.editor.dispose();
    }
}


text:
package git4idea.branch;

import com.intellij.notification.NotificationType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ui.UIUtil;
import git4idea.GitBranch;
import git4idea.GitPlatformFacade;
import git4idea.GitVcs;
import git4idea.Notificator;
import git4idea.commands.Git;
import git4idea.commands.GitCommandResult;
import git4idea.commands.GitCompoundResult;
import git4idea.jgit.GitHttpAdapter;
import git4idea.push.GitSimplePushResult;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import git4idea.ui.branch.GitMultiRootBranchConfig;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Kirill Likhodedov
 */
class GitDeleteRemoteBranchOperation extends GitBranchOperation {
  private final String myBranchName;

  public GitDeleteRemoteBranchOperation(@NotNull Project project, @NotNull GitPlatformFacade facade, @NotNull Git git,
                                        @NotNull GitBranchUiHandler handler, @NotNull List<GitRepository> repositories,
                                        @NotNull String name) {
    super(project, facade, git, handler, repositories);
    myBranchName = name;
  }

  @Override
  protected void execute() {
    final Collection<GitRepository> repositories = getRepositories();
    final Collection<String> trackingBranches = findTrackingBranches(myBranchName, repositories);
    String currentBranch = GitBranchUtil.getCurrentBranchOrRev(repositories);
    boolean currentBranchTracksBranchToDelete = false;
    if (trackingBranches.contains(currentBranch)) {
      currentBranchTracksBranchToDelete = true;
      trackingBranches.remove(currentBranch);
    }

    final AtomicReference<DeleteRemoteBranchDecision> decision = new AtomicReference<DeleteRemoteBranchDecision>();
    final boolean finalCurrentBranchTracksBranchToDelete = currentBranchTracksBranchToDelete;
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        decision.set(confirmBranchDeletion(myBranchName, trackingBranches, finalCurrentBranchTracksBranchToDelete, repositories));
      }
    });

    if (decision.get().delete()) {
      boolean deletedSuccessfully = doDeleteRemote(myBranchName, repositories);
      if (deletedSuccessfully) {
        final Collection<String> successfullyDeletedLocalBranches = new ArrayList<String>(1);
        if (decision.get().deleteTracking()) {
          for (final String branch : trackingBranches) {
            getIndicator().setText("Deleting " + branch);
            new GitDeleteBranchOperation(myProject, myFacade, myGit, myUiHandler, repositories, branch) {
              @Override
              protected void notifySuccess(@NotNull String message) {
                // do nothing - will display a combo notification for all deleted branches below
                successfullyDeletedLocalBranches.add(branch);
              }
            }.execute();
          }
        }
        notifySuccessfulDeletion(myBranchName, successfullyDeletedLocalBranches);
      }
    }

  }

  @Override
  protected void rollback() {
    throw new UnsupportedOperationException();
  }

  @NotNull
  @Override
  public String getSuccessMessage() {
    throw new UnsupportedOperationException();
  }

  @NotNull
  @Override
  protected String getRollbackProposal() {
    throw new UnsupportedOperationException();
  }

  @NotNull
  @Override
  protected String getOperationName() {
    throw new UnsupportedOperationException();
  }

  @NotNull
  private static Collection<String> findTrackingBranches(@NotNull String remoteBranch, @NotNull Collection<GitRepository> repositories) {
    return new GitMultiRootBranchConfig(repositories).getTrackingBranches(remoteBranch);
  }

  private boolean doDeleteRemote(@NotNull String branchName, @NotNull Collection<GitRepository> repositories) {
    GitCompoundResult result = new GitCompoundResult(myProject);
    for (GitRepository repository : repositories) {
      Pair<String, String> pair = splitNameOfRemoteBranch(branchName);
      String remote = pair.getFirst();
      String branch = pair.getSecond();
      GitCommandResult res = pushDeletion(repository, remote, branch);
      result.append(repository, res);
      repository.update();
    }
    if (!result.totalSuccess()) {
      Notificator.getInstance(myProject).notifyError("Failed to delete remote branch " + branchName,
                                                             result.getErrorOutputWithReposIndication());
    }
    return result.totalSuccess();
  }

  /**
   * Returns the remote and the "local" name of a remote branch.
   * Expects branch in format "origin/master", i.e. remote/branch
   */
  private static Pair<String, String> splitNameOfRemoteBranch(String branchName) {
    int firstSlash = branchName.indexOf('/');
    String remoteName = firstSlash > -1 ? branchName.substring(0, firstSlash) : branchName;
    String remoteBranchName = branchName.substring(firstSlash + 1);
    return Pair.create(remoteName, remoteBranchName);
  }

  @NotNull
  private GitCommandResult pushDeletion(@NotNull GitRepository repository, @NotNull String remoteName, @NotNull String branchName) {
    GitRemote remote = getRemoteByName(repository, remoteName);
    if (remote == null) {
      String error = "Couldn't find remote by name: " + remoteName;
      LOG.error(error);
      return GitCommandResult.error(error);
    }

    String remoteUrl = remote.getFirstUrl();
    if (remoteUrl == null) {
      LOG.warn("No urls are defined for remote: " + remote);
      return GitCommandResult.error("There is no urls defined for remote " + remote.getName());
    }
    if (GitHttpAdapter.shouldUseJGit(remoteUrl)) {
      String fullBranchName = branchName.startsWith(GitBranch.REFS_HEADS_PREFIX) ? branchName : GitBranch.REFS_HEADS_PREFIX + branchName;
      String spec = ":" + fullBranchName;
      GitSimplePushResult simplePushResult = GitHttpAdapter.push(repository, remote.getName(), remoteUrl, spec);
      return convertSimplePushResultToCommandResult(simplePushResult);
    }
    else {
      return pushDeletionNatively(repository, remoteName, remoteUrl, branchName);
    }
  }

  @NotNull
  private GitCommandResult pushDeletionNatively(@NotNull GitRepository repository, @NotNull String remoteName, @NotNull String url,
                                                @NotNull String branchName) {
    return myGit.push(repository, remoteName, url,":" + branchName);
  }

  @NotNull
  private static GitCommandResult convertSimplePushResultToCommandResult(@NotNull GitSimplePushResult result) {
    boolean success = result.getType() == GitSimplePushResult.Type.SUCCESS;
    return new GitCommandResult(success, -1, success ? Collections.<String>emptyList() : Collections.singletonList(result.getOutput()),
                                success ? Collections.singletonList(result.getOutput()) : Collections.<String>emptyList(), null);
  }

  @Nullable
  private static GitRemote getRemoteByName(@NotNull GitRepository repository, @NotNull String remoteName) {
    for (GitRemote remote : repository.getRemotes()) {
      if (remote.getName().equals(remoteName)) {
        return remote;
      }
    }
    return null;
  }

  private void notifySuccessfulDeletion(@NotNull String remoteBranchName, @NotNull Collection<String> localBranches) {
    String message = "";
    if (!localBranches.isEmpty()) {
      message = "Also deleted local " + StringUtil.pluralize("branch", localBranches.size()) + ": " + StringUtil.join(localBranches, ", ");
    }
    Notificator.getInstance(myProject).notify(GitVcs.NOTIFICATION_GROUP_ID, "Deleted remote branch " + remoteBranchName,
                                                      message, NotificationType.INFORMATION);
  }

  private DeleteRemoteBranchDecision confirmBranchDeletion(@NotNull String branchName, @NotNull Collection<String> trackingBranches,
                                                           boolean currentBranchTracksBranchToDelete,
                                                           @NotNull Collection<GitRepository> repositories) {
    String title = "Delete Remote Branch";
    String message = "Delete remote branch " + branchName;

    boolean delete;
    final boolean deleteTracking;
    if (trackingBranches.isEmpty()) {
      delete = Messages.showYesNoDialog(myProject, message, title, "Delete", "Cancel", Messages.getQuestionIcon()) == Messages.OK;
      deleteTracking = false;
    }
    else {
      if (currentBranchTracksBranchToDelete) {
        message += "\n\nCurrent branch " + GitBranchUtil.getCurrentBranchOrRev(repositories) + " tracks " + branchName + " but won't be deleted.";
      }
      final String checkboxMessage;
      if (trackingBranches.size() == 1) {
        checkboxMessage = "Delete tracking local branch " + trackingBranches.iterator().next() + " as well";
      }
      else {
        checkboxMessage = "Delete tracking local branches " + StringUtil.join(trackingBranches, ", ");
      }

      final AtomicBoolean deleteChoice = new AtomicBoolean();
      delete = Messages.OK == Messages.showYesNoDialog(message, title, "Delete", "Cancel", Messages.getQuestionIcon(), new DialogWrapper.DoNotAskOption() {
        @Override
        public boolean isToBeShown() {
          return true;
        }

        @Override
        public void setToBeShown(boolean value, int exitCode) {
          deleteChoice.set(!value);
        }

        @Override
        public boolean canBeHidden() {
          return true;
        }

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

        @Override
        public String getDoNotShowMessage() {
          return checkboxMessage;
        }
      });
      deleteTracking = deleteChoice.get();
    }
    return new DeleteRemoteBranchDecision(delete, deleteTracking);
  }

  private static class DeleteRemoteBranchDecision {
    private final boolean delete;
    private final boolean deleteTracking;

    private DeleteRemoteBranchDecision(boolean delete, boolean deleteTracking) {
      this.delete = delete;
      this.deleteTracking = deleteTracking;
    }

    public boolean delete() {
      return delete;
    }

    public boolean deleteTracking() {
      return deleteTracking;
    }
  }

}


text:
<?php

namespace PDFfiller\OAuth2\Client\Provider\Exceptions;

use PDFfiller\OAuth2\Client\Provider\Core\Exception;

/**
 * Class MethodNotSupportedException
 * @package PDFfiller\OAuth2\Client\Provider\Exceptions
 */
class MethodNotSupportedException extends Exception
{
}


text:
package ro.ase.cts.seminar3;

import ro.ase.cts.seminar3.singleton.Conexiune;

public class ModulConfigurareCaracter {
	public ModulConfigurareCaracter(){

		//ConexiuneBD conexiune = null;
		Conexiune conexiune = null;
		try{
/*			conexiune =
				new ConexiuneBD();*/
			conexiune = Conexiune.getConexiune();
		}
		finally{
			//conexiune.inchide();
		}

	}
}