text:
layout: post
title: "A Massive Ransomware Attack Targets Organizations Around the Globe"
description: "A global cyber-attack using leaked NSA tools is targeting organizations worldwide including UK's National Health Service, Spain's Telefonica telecom, and many more."
date: 2017-05-13 8:30
category: Security, Data Breach, Cyberattack
author:
  name: "Ado Kukic"
  url: "https://twitter.com/kukicado"
  mail: "ado@auth0.com"
  avatar: "https://s.gravatar.com/avatar/99c4080f412ccf46b9b564db7f482907?s=200"
design:
  image: https://cdn.auth0.com/blog/this-the-season-for-cyber-criminals/logo.png
  bg_color: "#191716"
related:
  - 2016-11-30-different-ways-to-implement-multifactor
  - 2015-12-17-json-web-token-signing-algorithms-overview
tags:
  - security
  - data-breach
  - ransomware
  - wannacry
---

A ransomware, called [**WannaCry**](http://money.cnn.com/2017/05/12/technology/ransomware-attack-nsa-microsoft/), is making rounds across the globe and infecting vulnerable systems worldwide. Amongst the affected include FedEx, UK's National Health Service, Spain's Telefonica telecom, Russia's Interior Ministry, and many more. Hackers exploiting leaked NSA secrets and tools are said to be behind the massive attack, although no specific group has been identified as of yet.

The **WannaCry** ransomware encrypts a computer's file system and demands payment to restore access to the files. If a payment is not made in 7 days, the ransomware will delete all of the files on the machine. The attack, circulated initially through email, targets Windows machines that have not received the March 2017 security update where Microsoft fixed the vulnerability that makes this particular attack possible.

![WannaCry Ransomware](https://cdn.auth0.com/blog/wannacry/wannacry.png)

Ransomware attacks are nothing new. In 2016, a [Los Angeles hospital paid $17,000](https://www.nytimes.com/2016/02/19/business/los-angeles-hospital-pays-hackers-17000-after-attack.html) to regain access when hackers seized control. In fact, in our [Security Trends for 2016](https://auth0.com/blog/security-trends-for-2016/), we mentioned that **cyber extorsion** is likely to evolve and keep security specialists up at night, and we hate that we were right. The **WannaCry** cyber-attack is looking to be one of the biggest attacks recorded!

The **WannaCry** cyber-attack has been reported in 99 countries and over 75,000 attacks have been carried out so far, but perhaps the most concerning is the attack on UK's National Health Service (NHS), as it has life-or-death implications. An important thing to note is that these numbers are only from victims that have self-reported the attack, which means that the scope of this cyber-attack is most likely larger than reported.

Companies can protect themselves and their users agains cyber-attacks by developing strong incident response capabilities to complement their traditional security measures. As prevention can not be successful everytime, being capable of detecting and responding to incidents quickly is crucial. For individuals, the best way to prevent becoming a victim of ransomware and other cyber-attacks is to always keep your operating system up-to-date by enabling automatic updates. It may be annoying to see the *"You need to restart your computer to apply updates"* message, but a 5-10 minute downtime beats losing years worth of data.

## Personal Information Security Guide

Although you may not be affected by the **WannaCry** ransomware, it may be a good time to review our [personal information security guide](https://auth0.com/blog/personal-information-security-identity-guide/) which has plenty of tips on securing your personal information online, detecting phising scams, backing up data, and much more.

Top things to remember when it comes to choosing a good password:

* Don't reuse the same password for multiple accounts.
* Combine alphanumeric, special, lower and uppercase characters.
* Your password should be at least 10 characters long.
* If possible, enable [multifactor authentication](https://auth0.com/multifactor-authentication) for your account.

Be sure to check out the [personal information security guide](https://auth0.com/blog/personal-information-security-identity-guide/) to learn how to secure your wireless network, backup your data so that it is not lost if you become a victim of ransomware such as **WannaCry**, detect phishing scams, and more.


text:
class AddSerializedIdsToSearches < ActiveRecord::Migration
  def self.up
    add_column :searches, :parent_ids,  :text
    add_column :searches, :child_ids,   :text
  end

  def self.down
    remove_column :searches, :child_ids
    remove_column :searches, :parent_ids
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.abplus.dxf.section.table;

import com.abplus.dxf.Entity;
import com.abplus.dxf.Lexer;
import com.abplus.dxf.section.Tables;

import java.io.IOException;

public class Layer extends AbstractTable {

    public static final String TABLE_NAME = "LAYER";

    public Layer(Lexer lex, Tables.Callback cb) throws IOException {
        super(lex, cb);
    }

    protected boolean handleRecord(Tables.Callback cb, Entity rec) {
        return cb.handleLayer(rec);
    }
}


text:
import { NgModule } from '@angular/core';//从库模块中导入NgModule装饰器
import { BrowserModule } from '@angular/platform-browser';//从angular库中导入angular模块
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppRoutingModule } from './app-routing.module';

//模拟Web API
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';

//导入自己写好的组件
import { AppComponent } from './app.component';
import { HeroesComponent }  from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
import { DashBoardComponent } from './dashboard.component';
import { HeroSearchComponent } from './hero-search.component';
import { HeroService } from "./hero.service";
import { ClickMeComponent } from "./click-me.component";
import { KeyUpComponent_v1 } from "./keyup.component";
import { LoopbackComponent } from './loop-back.component';
import {LitterTourComponent} from "./litter-tour.component";
import {HeroFormComponent} from "./hero-form.component";

//标记为angular模块类(ngModule类),接收元数据对象,告诉angular如何编译和启动应用
@NgModule({//装饰器负责把元数据装饰到类上,接收的是描述模块属性的元数据对象
  imports: [//本模块声明的组件模板需要的类所在的其他模块
    BrowserModule,//应用模块需要BrowserModule的某些素材
    FormsModule,
    AppRoutingModule,
    HttpModule, //注册Http服务
    InMemoryWebApiModule.forRoot(InMemoryDataService)//InMemoryWebApiModule将Http客户端默认的后端服务 — 这是一个辅助服务,负责与远程服务器对话 — 替换成了内存 Web API服务:
  ],
  //声明本模块中的视图类(组件、指令、管道)
  declarations: [ //包含了所有由我们创建的并属于应用模块的组件、管道和指令。声明关联模块的任务。
    AppComponent,//告诉angular哪个组件属于APPModule
    HeroesComponent,
    HeroDetailComponent,
    DashBoardComponent,
    HeroSearchComponent,
    ClickMeComponent,
    KeyUpComponent_v1,
    LoopbackComponent,
    LitterTourComponent,
    HeroFormComponent
  ],
  // exports:[ AppComponent ],//declarations的子集,可用于其他模块的组件模板,此处不需要
  //服务的创建者,加入全局服务列表中,可用于应用的任何部分
  providers: [//供每个视图使用,守卫服务
    HeroService
  ],//注入器为服务注册一个提供商,用来创建或返回服务,供应商可以放在根模块,也可以放在组件上
  //指定应用的主视图(根组件),其他视图的宿主,只有根模块设置。angular创建它并插入index.html宿主页面
  bootstrap: [ AppComponent ]
})
export class AppModule { }


text:
$(document).ready(function() {
        var curSource = "/marketing/newsletterscalendar/";
        var date = new Date();
        var m = moment(date).format('YYYY-MM-DD');
$('#newsletters').fullCalendar({
        defaultDate: m,
        contentHeight: 500,
        aspectRatio: 8,
        handleWindowResize: true, // Изменять размер календаря пропорционально изменению окна браузера
        editable: false, // Редактирование запрещено, т.к. источник событий json-feed из БД
        isRTL: false, // Отображать календарь в обратном порядке (true/false)
        // hiddenDays: [], // Скрыть дни недели [перечислить номера дней недели ч-з запятую]
        // hiddenDays: [ 1, 2, 3, 4, 5 ],
        weekMode: 'liquid',
        weekNumbers: true,
        weekends: true,
        defaultView: 'month',
        selectable: false,
        editable: false,
        lang: 'ru',
        more: 3,
        firstday: 1,
        theme: false,
        buttonIcons: {
            prev: 'left-single-arrow',
            next: 'right-single-arrow',
            prevYear: 'left-double-arrow',
            nextYear: 'right-double-arrow'
        },
        themeButtonsIcons: {
            prev: 'circle-triangle-w',
            next: 'circle-triangle-e',
            prevYear: 'seek-prev',
            nextYear: 'seek-next'
        },
        header: {
            left: 'prev,today,next',
            center: 'title,filter',
            right: 'listMonth,month,agendaWeek,agendaDay',
        },

        eventLimit: true,
        eventLimitClick: 'popover',
        views: {
            agenda: {
                eventLimit: 15,
            }
        },
        businessHours: {
            start: '9:00', // время начала
            end: '21:00', // время окончания
            dow: [ 1, 2, 3, 4, 5, 6, 7 ]
            // days of week. an array of zero-based day of week integers (0=Sunday) дни недели, начиная с 0 (0-ВСК)
        },
        eventSources: [
            {
                url: curSource,
                type: 'GET',
                color: 'blue',
                textColor: 'white',
                cache: false,
                success: function() {
                },
                error: function() {
                    alert("Ошибка получения источника событий");
                },
            },
        ],
        eventClick:  function(event, jsEvent, view) {
            window.location = "view?id=" + event.id;
        },

});
});


text:
Input::
//// [/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }
interface ReadonlyArray<T> {}
declare const console: { log(msg: any): void; };

//// [/src/src/main/a.ts]
import { b } from './b';
const a = b;

//// [/src/src/main/b.ts]
export const b = 0;

//// [/src/src/main/tsconfig.json]
{"compilerOptions":{"composite":true,"outDir":"../../dist/"},"references":[{"path":"../other"}]}

//// [/src/src/other/other.ts]
export const Other = 0;

//// [/src/src/other/tsconfig.json]
{"compilerOptions":{"composite":true,"outDir":"../../dist/"}}

//// [/src/tsconfig.base.json]

Output::
/lib/tsc --b /src/src/main --verbose
[12:00:00 AM] Projects in this build:
    * src/src/other/tsconfig.json
    * src/src/main/tsconfig.json

[12:00:00 AM] Project 'src/src/other/tsconfig.json' is out of date because output file 'src/dist/other.js' does not exist

[12:00:00 AM] Building project '/src/src/other/tsconfig.json'...

[12:00:00 AM] Project 'src/src/main/tsconfig.json' is out of date because output file 'src/dist/a.js' does not exist

[12:00:00 AM] Building project '/src/src/main/tsconfig.json'...

src/src/main/tsconfig.json:1:76 - error TS6377: Cannot write file '/src/dist/tsconfig.tsbuildinfo' because it will overwrite '.tsbuildinfo' file generated by referenced project '/src/src/other'

1 {"compilerOptions":{"composite":true,"outDir":"../../dist/"},"references":[{"path":"../other"}]}
                                                                             ~~~~~~~~~~~~~~~~~~~

Found 1 error.

exitCode:: ExitStatus.DiagnosticsPresent_OutputsGenerated

//// [/src/dist/other.d.ts]
export declare const Other = 0;

//// [/src/dist/other.js]
"use strict";
exports.__esModule = true;
exports.Other = void 0;
exports.Other = 0;

//// [/src/dist/tsconfig.tsbuildinfo]
{"program":{"fileNames":["../../lib/lib.d.ts","../src/other/other.ts"],"fileInfos":[{"version":"3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true},"-2951227185-export const Other = 0;\r\n"],"options":{"composite":true,"outDir":"./"},"referencedMap":[],"exportedModulesMap":[],"semanticDiagnosticsPerFile":[1,2]},"version":"FakeTSVersion"}

//// [/src/dist/tsconfig.tsbuildinfo.readable.baseline.txt]
{
  "program": {
    "fileNames": [
      "../../lib/lib.d.ts",
      "../src/other/other.ts"
    ],
    "fileInfos": {
      "../../lib/lib.d.ts": {
        "version": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };",
        "signature": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };",
        "affectsGlobalScope": true
      },
      "../src/other/other.ts": {
        "version": "-2951227185-export const Other = 0;\r\n",
        "signature": "-2951227185-export const Other = 0;\r\n"
      }
    },
    "options": {
      "composite": true,
      "outDir": "./"
    },
    "referencedMap": {},
    "exportedModulesMap": {},
    "semanticDiagnosticsPerFile": [
      "../../lib/lib.d.ts",
      "../src/other/other.ts"
    ]
  },
  "version": "FakeTSVersion",
  "size": 754
}


text:
package es.uned.lsi.eped.pract2016.parser;

import es.uned.lsi.eped.DataStructures.CollectionIF;
import es.uned.lsi.eped.DataStructures.IteratorIF;
import es.uned.lsi.eped.pract2016.AcademiaIF;
import es.uned.lsi.eped.pract2016.DoctorC;
import es.uned.lsi.eped.pract2016.DoctorIF;
import es.uned.lsi.eped.pract2016.OperationsParser;

class ParserCScenarario implements OperationsParser {

	@Override
	public void getSiblings(AcademiaIF academia, int doctorId) {
		DoctorC doctor = (DoctorC) academia.getDoctor(doctorId);
		if (doctor != null) {
			CollectionIF<DoctorIF> siblings = doctor.getSiblings();
			IteratorIF<DoctorIF> siblingsIterator = siblings.iterator();
			//System.out.println(String.format("Los hermanos de \"%d\" son %s",
			//		doctorId, getStringForElementsIn(siblingsIterator)));
		}
	}

	@Override
	public void getDescendants(AcademiaIF academia, int doctorId, int generations) {
		DoctorC doctor = (DoctorC) academia.getDoctor(doctorId);
		if (doctor != null) {
			CollectionIF<DoctorIF> supervisors = doctor.getDescendants(generations);
			IteratorIF<DoctorIF> supervisorsIterator = supervisors.iterator();
			//System.out.println(String.format("Los descendientes de \"%d\" hasta %d generaciones son %s",
			//		doctorId, generations, getStringForElementsIn(supervisorsIterator)));
		}
	}

	@Override
	public void getStudents(AcademiaIF academia, int doctorId) {
		DoctorC doctor = (DoctorC) academia.getDoctor(doctorId);
		if (doctor != null) {
			CollectionIF<DoctorIF> students = doctor.getStudents();
			IteratorIF<DoctorIF> studentsIterator = students.iterator();
			//System.out.println(String.format("\"%d\" ha dirigido la tesis de %s",
			//		doctorId, getStringForElementsIn(studentsIterator)));
		}
	}

	@Override
	public void getAncestors(AcademiaIF academia, int doctorId, int generations) {
		DoctorC doctor = (DoctorC) academia.getDoctor(doctorId);
		if (doctor != null) {
			CollectionIF<DoctorIF> supervisors = doctor.getAncestors(generations);
			IteratorIF<DoctorIF> supervisorsIterator = supervisors.iterator();
			//System.out.println(String.format("Los ancestros de \"%d\" hasta %d generaciones son %s",
			//		doctorId, generations, getStringForElementsIn(supervisorsIterator)));
		}
	}

	@Override
	public void getDirectors(AcademiaIF academia, int doctorId) {
		DoctorC doctor = (DoctorC) academia.getDoctor(doctorId);
		if (doctor != null) {
			CollectionIF<DoctorIF> supervisors = doctor.getSupervisors();
			//System.out.println(String.format("Tesis de \"%d\" codirigida por %s", doctorId,
			//		getStringForElementsIn(supervisors.iterator())));
		}
	}

	private String getStringForElementsIn(IteratorIF<DoctorIF> it) {
		final StringBuilder sb = new StringBuilder();
		while (it.hasNext()) {
			DoctorC supervisor = (DoctorC) it.getNext();
			sb.append("\"")
					.append(supervisor.getId())
					.append("\"");
			if (it.hasNext()) {
				sb.append(",");
			}
			sb.append(" ");
		}
		return sb.toString();
	}
}


text:
var createPage = require('./util').createPage;
var difference = require('mout/array/difference');
var forEach = require('mout/array/forEach');
var forOwn = require('mout/object/forOwn');
var keys = require('mout/object/keys');
var moment = require('moment');
var processMagazine = require('./magazine');
var Workflow = require('./workflow');
var sort = require('mout/array/sort');
var system = require('system');
var util = require('./util');

var magazineAccessArray = [];
var magazineAccess = util.getMagazineAccess();
var magazines = [];
var workflow = new Workflow(createPage());

forOwn(magazineAccess, function (val, key) {
  magazineAccessArray.push({
    name: key,
    lastProcessed: moment(val)
  });
});
magazineAccessArray = sort(magazineAccessArray, function (a, b) {
  return b.lastProcessed < a.lastProcessed;
});

var systemArgs = util.parseSystemArgs(system.args);
systemArgs.exclude = systemArgs.exclude ? systemArgs.exclude.split(',') : [];
systemArgs.mags = systemArgs.mags ? systemArgs.mags.split(',') : [];
systemArgs.output = systemArgs.output || 'images/';

if (!/\/$/.test(systemArgs.output)) {
  systemArgs.output += '/';
}

function validateRequested(name) {
  var lowerName = name.toLowerCase();
  var isExcluded = systemArgs.exclude.indexOf(lowerName) > -1;

  if (!systemArgs.mags.length && !isExcluded) {
    return true;
  }
  if (isExcluded) {
    return false;
  }
  return systemArgs.mags.indexOf(lowerName) > -1;
}

workflow.addStep('Load signin page', function (done) {
  var page = workflow._page;
  page.open('https://flipboard.com/signin', function (status) {
    if (status !== 'success') {
      return;
    }
    if (page.injectJs('node_modules/jquery/dist/jquery.min.js')) {
      setTimeout(done, 5000);
    }
  });
});

workflow.addStep('Log in', function (done) {
  workflow._page.evaluate(function(user, pass) {
    var $form = $('.login-form-content');
    var $fields = $form.find('.fields');
    $fields.find('input[type=text]').val(user);
    $fields.find('input[type=password]').val(pass);
    $form.find('button.button').click();
  }, systemArgs.user, systemArgs.pass);
  setTimeout(done, 5000);
});

workflow.addStep('Load magazines', function (done) {
  var page = workflow._page;
  page.open('https://flipboard.com/profile', function (status) {
    if (status !== 'success') {
      return;
    }
    if (page.injectJs('node_modules/jquery/dist/jquery.min.js')) {
      setTimeout(done, 5000);
    }
  });
});

workflow.addStep('Compile magazines', function () {
  var page = workflow._page;

  var mags = page.evaluate(function (magazineAccess) {
    var items = {};
    var name;
    var path;

    /**
     * Convert the magazine path to the edit path that will be used.
     * @param {string} path - The magazine path to convert.
     * @return {string}
     */
    function getMagPath(path) {
      return path.replace(/@([^\/]*).*-([^-]*)$/, 'editor/sid%252F$2%252F$1');
    }

    $('.magazine-tile').each(function (idx, mag) {
      name = $(mag).find('h3.truncated-text').html();
      path = $(mag).find('.section-link').attr('href');

      if (name === "Create Magazine") {
        return;
      }

      items[name] = {
        lastProcessed: magazineAccess[name],
        name: name,
        url: 'https://flipboard.com' + getMagPath(path)
      };
    });
    return items;
  }, magazineAccess);

  // Check if any are in mags and not magazineAccess
  forEach(difference(keys(mags), keys(magazineAccess)), function (val) {
    magazines.push(mags[val]);
  });

  var name;
  forEach(magazineAccessArray, function (val) {
    name = val.name;
    // Name isn't in the access list, so it must be new. Add to the front.
    if (!(name in mags)) {
      return;
    }
    magazines.push(mags[name]);
  });
});

workflow.addStep('Process magazines', function (done) {
  var _path;
  var idx = 0;
  var item;
  var processing = false;

  function callback(skipped) {
    skipped || util.updateProcessTime(item.name, moment().toISOString());
    processing = false;
    idx++;
  }

  var interval = setInterval(function () {
    if (processing) {
      return;
    }

    if (idx === magazines.length) {
      clearInterval(interval);
      return done();
    }

    item = magazines[idx];
    console.log(item.name + ':', unescape(item.url));

    if (!validateRequested(item.name)) {
      return callback(true);
    }
    processing = true;
    processMagazine({
      dest: systemArgs.output,
      done: callback,
      mag: item
    });
  }, 1000);
});

workflow.addStep('Donezo', function () {
  phantom.exit();
});

workflow.process();


text:
package com.google.api.ads.adwords.jaxws.v201601.cm;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for LocationTargetingStatus.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="LocationTargetingStatus">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="ACTIVE"/>
 *     <enumeration value="OBSOLETE"/>
 *     <enumeration value="PHASING_OUT"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "LocationTargetingStatus")
@XmlEnum
public enum LocationTargetingStatus {

    /**
     *
     *                 The location is active.
     *
     *
     */
    ACTIVE,

    /**
     *
     *                 The location is not available for targeting.
     *
     *
     */
    OBSOLETE,

    /**
     *
     *                 The location is phasing out, it will marked obsolete soon.
     *
     *
     */
    PHASING_OUT;

    public String value() {
        return name();
    }

    public static LocationTargetingStatus fromValue(String v) {
        return valueOf(v);
    }

}


text:
<?php

namespace app\modules\admin\components;

use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

class AdminController extends Controller
{
    public function behaviors()
    {
        return [
            'authBehavior' => 'app\modules\admin\components\AuthBehavior',
            'verbFilter' => [
                'class' => 'yii\filters\VerbFilter',
                'actions' => [
                    'index' => ['get'],
                    'read'  => ['get'],
                    'write' => ['post'],
                    'delete' => ['post'],
                ],
            ],
        ];
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2005-2015 The Kuali Foundation

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

    http://www.opensource.org/licenses/ecl2.php

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

-->
<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

  <!-- Maintenance View -->

  <bean id="TravelExpenseItemMaintenanceDocument" parent="uifMaintenanceDocumentEntry">
    <property name="dataObjectClass" value="edu.sampleu.travel.dataobject.TravelExpenseItem"/>
    <property name="documentTypeName" value="TravelExpenseItemMaintenanceDocument"/>
    <property name="lockingKeys">
      <list>
        <value>travelExpenseItemId</value>
      </list>
    </property>
  </bean>

  <bean id="TravelExpenseItem-MaintenanceView" parent="Uif-MaintenanceView">
    <property name="headerText" value="Travel Expense Maintenance"/>
    <property name="dataObjectClassName" value="edu.sampleu.travel.dataobject.TravelExpenseItem"/>
    <property name="items">
      <list merge="true">
        <bean parent="Uif-MaintenanceGridSection">
          <property name="headerText" value="Travel Expense Information"/>
          <property name="items">
            <list>
              <bean parent="Uif-InputField" p:propertyName="travelExpenseItemId" p:defaultValue="@{ #sequence('TRVL_EXP_ITM_ID_S') }" />
              <bean parent="Uif-InputField" p:propertyName="travelAuthorizationDocumentId"/>
              <bean parent="Uif-InputField" p:propertyName="travelCompanyName" p:widgetInputOnly="true">
                <property name="quickfinder">
                  <bean parent="Uif-QuickFinder"
                        p:dataObjectClassName="edu.sampleu.travel.dataobject.TravelCompany" >
                    <property name="fieldConversions">
                      <map>
                        <entry key="travelCompanyName" value="travelCompanyName" />
                      </map>
                    </property>
                  </bean>
                </property>
              </bean>
              <bean parent="Uif-InputField" p:propertyName="travelExpenseTypeCd"/>
              <bean parent="Uif-InputField" p:propertyName="expenseDesc"/>
              <bean parent="Uif-InputField" p:propertyName="expenseDate"/>
              <bean parent="Uif-InputField" p:propertyName="expenseAmount"/>
              <bean parent="Uif-InputField" p:propertyName="reimbursable"/>
              <bean parent="Uif-InputField" p:propertyName="taxable"/>
            </list>
          </property>
        </bean>
      </list>
    </property>
  </bean>

</beans>


text:
require "spec_helper"
MetricFu.reporting_require { "graphs/graph" }

describe MetricFu do
  describe "responding to #graph" do
    it "should return an instance of Graph" do
      expect(MetricFu.graph).to be_a(Graph)
    end
  end
end

describe MetricFu::Graph do
  before(:each) do
    @graph = MetricFu::Graph.new
  end

  describe "setting the date on the graph" do
    # TODO better test
    it "should set the date once for one data point" do
      metric_file = "metric_fu/tmp/_data/20101105.yml"
      expect(MetricFu::Utility).to receive(:glob).and_return([metric_file].sort)
      expect(MetricFu::Utility).to receive(:load_yaml).with(metric_file).and_return("Metrics")
      double_grapher = double
      expect(double_grapher).to receive(:get_metrics).with("Metrics", "11/5")
      expect(double_grapher).to receive(:graph!)

      @graph.graphers = [double_grapher]
      @graph.generate
    end

    # TODO better test
    it "should set the date when the data directory isn't in the default place" do
      metric_file = "/some/kind/of/weird/directory/somebody/configured/_data/20101105.yml"
      expect(MetricFu::Utility).to receive(:glob).and_return([metric_file].sort)
      expect(MetricFu::Utility).to receive(:load_yaml).with(metric_file).and_return("Metrics")
      double_grapher = double
      expect(double_grapher).to receive(:get_metrics).with("Metrics", "11/5")
      expect(double_grapher).to receive(:graph!)

      @graph.graphers = [double_grapher]
      @graph.generate
    end
  end
end


text:
//
//  SheetViewController.m
//  CJPopupViewDemo
//
//  Created by ciyouzen on 8/27/15.
//  Copyright (c) 2015 dvlproad. All rights reserved.
//

#import "SheetViewController.h"

@interface SheetViewController () <UIActionSheetDelegate>

@end

@implementation SheetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (IBAction)show_UIActionSheet:(id)sender{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle: @"File Management"
                                                            delegate:self
                                                   cancelButtonTitle:@"Cancel"
                                              destructiveButtonTitle:@"Delete File"
                                                   otherButtonTitles:@"Rename File", @"Email File", nil];
    [actionSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    printf("User Pressed Button %ld\n", buttonIndex + 1);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Config\Config;
use AppBundle\Oauth2\Provider\ShopifyProvider;
use AppBundle\Oauth2\ShopifyOauth2Provider;
use AppBundle\Service\Syncer;
use AppBundle\Store\SeoShopStore;
use AppBundle\Store\ShopifyStore;
use AppBundle\Store\StoreFactory;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use sandeepshetty\shopify_api;

class IndexController extends Controller
{
    /**
     * @Route("/", name="main")
     */
    public function indexAction(Request $request)
    {
        $shopifyConfig = $this->get('session')->get(Config::STORE_CONFIG_SHOPIFY_SESSION_KEY);
        $seoShopConfig = $this->get('session')->get(Config::STORE_CONFIG_SEOSHOP_SESSION_KEY);
        $isActiveShopifyToken = false;
        $isActiveSeoShopToken = false;
        if (isset($shopifyConfig[Config::STORE_CONFIG_SECTION][ShopifyStore::CONFIG_ACCESS_TOKEN])
            && !empty($shopifyConfig[Config::STORE_CONFIG_SECTION][ShopifyStore::CONFIG_ACCESS_TOKEN])){
            $isActiveShopifyToken = true;
        }

        if (isset($seoShopConfig[Config::STORE_CONFIG_SECTION][SeoShopStore::CONFIG_ACCESS_TOKEN])
            && !empty($seoShopConfig[Config::STORE_CONFIG_SECTION][SeoShopStore::CONFIG_ACCESS_TOKEN])){
            $isActiveSeoShopToken = true;
        }
        $params = [
            'isActiveShopifyToken' => $isActiveShopifyToken,
            'isActiveSeoShopToken' => $isActiveSeoShopToken,
            'shopifyStoreType' => ShopifyStore::STORE_TYPE,
            'seoshopStoreType' => SeoShopStore::STORE_TYPE
        ];
        return $this->render("AppBundle:Index:index.html.twig",$params);

    }

    /**
     * @Route("/sync/{storeTypeFrom}/{storeTypeTo}", name="sync")
     */
    public function syncAction($storeTypeFrom, $storeTypeTo, Request $request)
    {
        $result = [];
        $session = $this->get('session');
        $storeFromConfigKey = Config::getConfigKeyByStoreType($storeTypeFrom);
        $storeToConfigKey = Config::getConfigKeyByStoreType($storeTypeTo);
        if ($storeFromConfigKey && $storeToConfigKey){
            $storeFromConfig = $session->get($storeFromConfigKey);
            $storeToConfig = $session->get($storeToConfigKey);
            if ($storeFromConfig && $storeToConfig){
                /** @var Syncer $syncer */
                $syncer = $this->get('app.syncer');
                $result = $syncer->syncData($storeFromConfig,$storeToConfig, true);
            }
        }
        return $this->render("AppBundle:Index:sync.html.twig",['result'=>$result]);
    }

}


text:
package com.subdigit.request;

import com.google.common.net.MediaType;
import com.subdigit.broker.RequestResponseBroker;

public abstract class WebRequest<UserType> extends BasicRequest<String>
{
	public static final MediaType DEFAULT_MEDIATYPE		= MediaType.JSON_UTF_8;
	public static final String KEY_ACTION				= "action";
	public static final String KEY_VERSION				= "version";
	public static final String KEY_FORMAT				= "format";

	private RequestResponseBroker<?,?,?> _broker;
	private String _version;
	private Action _action;
	private MediaType _mediaType;

	// This is to kill any use of this without passing in a valid request.
	@SuppressWarnings("unused")
	private WebRequest(){}
	public WebRequest(RequestResponseBroker<?,?,?> broker){ this(broker, null); }
	public WebRequest(RequestResponseBroker<?,?,?> broker, Action value)
	{
		initialize(broker, value);
	}

	public boolean initialize(RequestResponseBroker<?,?,?> broker, Action value)
	{
		boolean initialized = super.initialize();

		if(broker == null) throw new NullPointerException();

		_version		= "1";
		_action			= value;
		_mediaType		= getDefaultMediaType();
		_broker			= broker;

		addParameters(_broker.extractRequestData());

		// Override only if we have a version parameter
		if(hasVersionParameter()) setVersion(extractVersion());
		// Override only if we have an action parameter
		if(hasActionParameter()) setAction(extractAction());
		setMediaType(extractMediaType());

		setInitialized(initialized);
		return initialized;
	}

	public RequestResponseBroker<?,?,?> getBroker(){ return _broker; }
	public void setBroker(RequestResponseBroker<?,?,?> value){ _broker = value; }

	public String getVersion(){ return _version; }
	public void setVersion(String value){ _version = value; }
	public String extractVersion()
	{
		if(getVersionParameter() != null) return getParameter(getVersionParameter());
		else return null;
	}
	public String getVersionParameter(){ return KEY_VERSION; }
	public boolean hasVersionParameter(){ return (extractVersion() != null)?true:false; }

	public Action getAction(){ return _action; }
	public void setAction(Action value){ _action = value; }
	public Action extractAction()
	{
		Action action = null;

		if(getActionParameter() != null && getParameter(getActionParameter()) != null){
			try {
				action = Action.valueOf(getParameter(getActionParameter()).toUpperCase());
			} catch(IllegalArgumentException e){
				action = Action.UNKNOWN;
			}
		}

		return action;
	}
	public String getActionParameter(){ return KEY_ACTION; }
	public boolean hasActionParameter(){ return (extractAction() != null)?true:false; }

	public MediaType getDefaultMediaType(){ return DEFAULT_MEDIATYPE; }
	public MediaType getMediaType(){ return _mediaType; }
	public void setMediaType(MediaType value){ _mediaType = value; }
	private MediaType extractMediaType()
	{
		MediaType mediaType = null;
		String key = KEY_FORMAT;
		String format = null;

		// See if we have a format override and use that first.
		if(key != null){
			format = getParameter(key);
			if(format != null){
				if(format.equalsIgnoreCase(MediaType.JSON_UTF_8.subtype())) mediaType = MediaType.JSON_UTF_8;
				else if(format.equalsIgnoreCase(MediaType.XML_UTF_8.subtype())) mediaType = MediaType.XML_UTF_8;
				else if(format.equalsIgnoreCase(MediaType.HTML_UTF_8.subtype())) mediaType = MediaType.HTML_UTF_8;
			}
		}

		// No format variable, so rely on what the client accepts, in order of our
		// preferences.
		if(mediaType == null){
			MediaType[] preferredMediaTypes = {MediaType.JSON_UTF_8, MediaType.XML_UTF_8, MediaType.HTML_UTF_8};
			mediaType = _broker.getAcceptedMediaType(preferredMediaTypes);
		}

		// Default it.
		if(mediaType == null) mediaType = getDefaultMediaType();

		return mediaType;
	}
	public String getMediaTypeAsString()
	{
		MediaType mediaType = _mediaType;

		if(mediaType == null) mediaType = DEFAULT_MEDIATYPE;

		return mediaType.withoutParameters().toString();
	}

	public abstract UserType getAuthenticatedUser();
	public abstract void setAuthenticatedUser(UserType user);

	public enum Action
	{
		GET,
		CREATE,
		UPDATE,
		DELETE,
		UNKNOWN;

		// I like my enums printed out in lower case, kthxbai.
		public String toString(){ return name().toLowerCase(); }

		// http://stackoverflow.com/a/2965252
		public static Action fromString(String text) throws IllegalArgumentException
		{
			if(text != null){
				for(Action action : Action.values()){
					if(text.equalsIgnoreCase(action.toString())){
						return action;
					}
				}
			}

			throw new IllegalArgumentException();
		}
	}
}


text:
A package yaml contains 54 kute popo emojis, used to add custom emojis to [Slack](https://get.slack.help/hc/en-us/articles/206870177-Creating-custom-emoji).

### Preview
![alt text](https://raw.githubusercontent.com/damhonglinh/popo-emoji/master/popo-emojis-preview.png "Popo Emojis Preview")

### Usage
Download the [yaml file](https://raw.githubusercontent.com/damhonglinh/popo-emoji/master/popo.yaml) and follow the instructions from https://github.com/lambtron/emojipacks#usage.

### Emojs album
http://imgur.com/a/9T8tt


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_CXX11_TENSOR_TENSOR_MAP_H
#define EIGEN_CXX11_TENSOR_TENSOR_MAP_H

namespace Eigen {

/** \class TensorMap
  * \ingroup CXX11_Tensor_Module
  *
  * \brief A tensor expression mapping an existing array of data.
  *
  */
/// template <class> class MakePointer_ is added to convert the host pointer to the device pointer.
/// It is added due to the fact that for our device compiler T* is not allowed.
/// If we wanted to use the same Evaluator functions we have to convert that type to our pointer T.
/// This is done through our MakePointer_ class. By default the Type in the MakePointer_<T> is T* .
/// Therefore, by adding the default value, we managed to convert the type and it does not break any
/// existing code as its default value is T*.
template<typename PlainObjectType, int Options_, template <class> class MakePointer_> class TensorMap : public TensorBase<TensorMap<PlainObjectType, Options_, MakePointer_> >
{
  public:
    typedef TensorMap<PlainObjectType, Options_, MakePointer_> Self;
    typedef typename PlainObjectType::Base Base;
    typedef typename Eigen::internal::nested<Self>::type Nested;
    typedef typename internal::traits<PlainObjectType>::StorageKind StorageKind;
    typedef typename internal::traits<PlainObjectType>::Index Index;
    typedef typename internal::traits<PlainObjectType>::Scalar Scalar;
    typedef typename NumTraits<Scalar>::Real RealScalar;
    typedef typename Base::CoeffReturnType CoeffReturnType;

  /*    typedef typename internal::conditional<
                         bool(internal::is_lvalue<PlainObjectType>::value),
                         Scalar *,
                         const Scalar *>::type
                     PointerType;*/
    typedef typename MakePointer_<Scalar>::Type PointerType;
    typedef PointerType PointerArgType;

    static const int Options = Options_;

    static const Index NumIndices = PlainObjectType::NumIndices;
    typedef typename PlainObjectType::Dimensions Dimensions;

    enum {
      IsAligned = ((int(Options_)&Aligned)==Aligned),
      Layout = PlainObjectType::Layout,
      CoordAccess = true,
      RawAccess = true
    };

    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr) : m_data(dataPtr), m_dimensions() {
      // The number of dimensions used to construct a tensor must be equal to the rank of the tensor.
      EIGEN_STATIC_ASSERT((0 == NumIndices || NumIndices == Dynamic), YOU_MADE_A_PROGRAMMING_MISTAKE)
    }

#if EIGEN_HAS_VARIADIC_TEMPLATES
    template<typename... IndexTypes> EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, Index firstDimension, IndexTypes... otherDimensions) : m_data(dataPtr), m_dimensions(firstDimension, otherDimensions...) {
      // The number of dimensions used to construct a tensor must be equal to the rank of the tensor.
      EIGEN_STATIC_ASSERT((sizeof...(otherDimensions) + 1 == NumIndices || NumIndices == Dynamic), YOU_MADE_A_PROGRAMMING_MISTAKE)
    }
#else
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, Index firstDimension) : m_data(dataPtr), m_dimensions(firstDimension) {
      // The number of dimensions used to construct a tensor must be equal to the rank of the tensor.
      EIGEN_STATIC_ASSERT((1 == NumIndices || NumIndices == Dynamic), YOU_MADE_A_PROGRAMMING_MISTAKE)
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, Index dim1, Index dim2) : m_data(dataPtr), m_dimensions(dim1, dim2) {
      EIGEN_STATIC_ASSERT(2 == NumIndices || NumIndices == Dynamic, YOU_MADE_A_PROGRAMMING_MISTAKE)
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, Index dim1, Index dim2, Index dim3) : m_data(dataPtr), m_dimensions(dim1, dim2, dim3) {
      EIGEN_STATIC_ASSERT(3 == NumIndices || NumIndices == Dynamic, YOU_MADE_A_PROGRAMMING_MISTAKE)
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, Index dim1, Index dim2, Index dim3, Index dim4) : m_data(dataPtr), m_dimensions(dim1, dim2, dim3, dim4) {
      EIGEN_STATIC_ASSERT(4 == NumIndices || NumIndices == Dynamic, YOU_MADE_A_PROGRAMMING_MISTAKE)
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, Index dim1, Index dim2, Index dim3, Index dim4, Index dim5) : m_data(dataPtr), m_dimensions(dim1, dim2, dim3, dim4, dim5) {
      EIGEN_STATIC_ASSERT(5 == NumIndices || NumIndices == Dynamic, YOU_MADE_A_PROGRAMMING_MISTAKE)
    }
#endif

   EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, const array<Index, NumIndices>& dimensions)
      : m_data(dataPtr), m_dimensions(dimensions)
    { }

    template <typename Dimensions>
    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorMap(PointerArgType dataPtr, const Dimensions& dimensions)
      : m_data(dataPtr), m_dimensions(dimensions)
    { }

    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorMap(PlainObjectType& tensor)
      : m_data(tensor.data()), m_dimensions(tensor.dimensions())
    { }

    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ~TensorMap() {}

    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Index rank() const { return m_dimensions.rank(); }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Index dimension(Index n) const { return m_dimensions[n]; }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Index size() const { return m_dimensions.TotalSize(); }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE PointerType data() { return m_data; }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const PointerType data() const { return m_data; }

    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Scalar& operator()(const array<Index, NumIndices>& indices) const
    {
      //      eigen_assert(checkIndexRange(indices));
      if (PlainObjectType::Options&RowMajor) {
        const Index index = m_dimensions.IndexOfRowMajor(indices);
        return m_data[index];
      } else {
        const Index index = m_dimensions.IndexOfColMajor(indices);
        return m_data[index];
      }
    }

    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Scalar& operator()() const
    {
      EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE)
      return m_data[0];
    }

    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Scalar& operator()(Index index) const
    {
      eigen_internal_assert(index >= 0 && index < size());
      return m_data[index];
    }

#if EIGEN_HAS_VARIADIC_TEMPLATES
    template<typename... IndexTypes> EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Scalar& operator()(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) const
    {
      EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE)
      if (PlainObjectType::Options&RowMajor) {
        const Index index = m_dimensions.IndexOfRowMajor(array<Index, NumIndices>{{firstIndex, secondIndex, otherIndices...}});
        return m_data[index];
      } else {
        const Index index = m_dimensions.IndexOfColMajor(array<Index, NumIndices>{{firstIndex, secondIndex, otherIndices...}});
        return m_data[index];
      }
    }
#else
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Scalar& operator()(Index i0, Index i1) const
    {
      if (PlainObjectType::Options&RowMajor) {
        const Index index = i1 + i0 * m_dimensions[1];
        return m_data[index];
      } else {
        const Index index = i0 + i1 * m_dimensions[0];
        return m_data[index];
      }
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Scalar& operator()(Index i0, Index i1, Index i2) const
    {
      if (PlainObjectType::Options&RowMajor) {
         const Index index = i2 + m_dimensions[2] * (i1 + m_dimensions[1] * i0);
         return m_data[index];
      } else {
         const Index index = i0 + m_dimensions[0] * (i1 + m_dimensions[1] * i2);
        return m_data[index];
      }
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Scalar& operator()(Index i0, Index i1, Index i2, Index i3) const
    {
      if (PlainObjectType::Options&RowMajor) {
        const Index index = i3 + m_dimensions[3] * (i2 + m_dimensions[2] * (i1 + m_dimensions[1] * i0));
        return m_data[index];
      } else {
        const Index index = i0 + m_dimensions[0] * (i1 + m_dimensions[1] * (i2 + m_dimensions[2] * i3));
        return m_data[index];
      }
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE const Scalar& operator()(Index i0, Index i1, Index i2, Index i3, Index i4) const
    {
      if (PlainObjectType::Options&RowMajor) {
        const Index index = i4 + m_dimensions[4] * (i3 + m_dimensions[3] * (i2 + m_dimensions[2] * (i1 + m_dimensions[1] * i0)));
        return m_data[index];
      } else {
        const Index index = i0 + m_dimensions[0] * (i1 + m_dimensions[1] * (i2 + m_dimensions[2] * (i3 + m_dimensions[3] * i4)));
        return m_data[index];
      }
    }
#endif

    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Scalar& operator()(const array<Index, NumIndices>& indices)
    {
      //      eigen_assert(checkIndexRange(indices));
      if (PlainObjectType::Options&RowMajor) {
        const Index index = m_dimensions.IndexOfRowMajor(indices);
        return m_data[index];
      } else {
        const Index index = m_dimensions.IndexOfColMajor(indices);
        return m_data[index];
      }
    }

    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Scalar& operator()()
    {
      EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE)
      return m_data[0];
    }

    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Scalar& operator()(Index index)
    {
      eigen_internal_assert(index >= 0 && index < size());
      return m_data[index];
    }

#if EIGEN_HAS_VARIADIC_TEMPLATES
    template<typename... IndexTypes> EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Scalar& operator()(Index firstIndex, Index secondIndex, IndexTypes... otherIndices)
    {
      static_assert(sizeof...(otherIndices) + 2 == NumIndices || NumIndices == Dynamic, "Number of indices used to access a tensor coefficient must be equal to the rank of the tensor.");
      const std::size_t NumDims = sizeof...(otherIndices) + 2;
      if (PlainObjectType::Options&RowMajor) {
        const Index index = m_dimensions.IndexOfRowMajor(array<Index, NumDims>{{firstIndex, secondIndex, otherIndices...}});
        return m_data[index];
      } else {
        const Index index = m_dimensions.IndexOfColMajor(array<Index, NumDims>{{firstIndex, secondIndex, otherIndices...}});
        return m_data[index];
      }
    }
#else
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Scalar& operator()(Index i0, Index i1)
    {
       if (PlainObjectType::Options&RowMajor) {
         const Index index = i1 + i0 * m_dimensions[1];
        return m_data[index];
      } else {
        const Index index = i0 + i1 * m_dimensions[0];
        return m_data[index];
      }
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Scalar& operator()(Index i0, Index i1, Index i2)
    {
       if (PlainObjectType::Options&RowMajor) {
         const Index index = i2 + m_dimensions[2] * (i1 + m_dimensions[1] * i0);
        return m_data[index];
      } else {
         const Index index = i0 + m_dimensions[0] * (i1 + m_dimensions[1] * i2);
        return m_data[index];
      }
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Scalar& operator()(Index i0, Index i1, Index i2, Index i3)
    {
      if (PlainObjectType::Options&RowMajor) {
        const Index index = i3 + m_dimensions[3] * (i2 + m_dimensions[2] * (i1 + m_dimensions[1] * i0));
        return m_data[index];
      } else {
        const Index index = i0 + m_dimensions[0] * (i1 + m_dimensions[1] * (i2 + m_dimensions[2] * i3));
        return m_data[index];
      }
    }
    EIGEN_DEVICE_FUNC
    EIGEN_STRONG_INLINE Scalar& operator()(Index i0, Index i1, Index i2, Index i3, Index i4)
    {
      if (PlainObjectType::Options&RowMajor) {
        const Index index = i4 + m_dimensions[4] * (i3 + m_dimensions[3] * (i2 + m_dimensions[2] * (i1 + m_dimensions[1] * i0)));
        return m_data[index];
      } else {
        const Index index = i0 + m_dimensions[0] * (i1 + m_dimensions[1] * (i2 + m_dimensions[2] * (i3 + m_dimensions[3] * i4)));
        return m_data[index];
      }
    }
#endif

    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Self& operator=(const Self& other)
    {
      typedef TensorAssignOp<Self, const Self> Assign;
      Assign assign(*this, other);
      internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
      return *this;
    }

    template<typename OtherDerived>
    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
    Self& operator=(const OtherDerived& other)
    {
      typedef TensorAssignOp<Self, const OtherDerived> Assign;
      Assign assign(*this, other);
      internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
      return *this;
    }

  private:
    typename MakePointer_<Scalar>::Type m_data;
    Dimensions m_dimensions;
};

} // end namespace Eigen

#endif // EIGEN_CXX11_TENSOR_TENSOR_MAP_H


text:
package endpointmanager

import (
	"fmt"
	"sync"

	"github.com/cilium/cilium/pkg/endpoint"
	"github.com/cilium/cilium/pkg/lock"

	log "github.com/sirupsen/logrus"
)

var (
	// Mutex protects Endpoints and endpointsAux
	//
	// Warning: This lock may not be taken while an individual endpoint
	// lock is being held. If you require to hold both, then the global
	// endpointmanager lock must always be acquired first.
	Mutex lock.RWMutex

	// Endpoints is the global list of endpoints indexed by ID. Mutex must
	// be held to read and write.
	//
	// FIXME: This is currently exported, as more code moves from daemon
	// into pkg/endpoint, we might be able to unexport this
	Endpoints    = map[uint16]*endpoint.Endpoint{}
	endpointsAux = map[string]*endpoint.Endpoint{}
)

// LookupCiliumIDLocked looks up endpoint by endpoint ID with Mutex held
func LookupCiliumIDLocked(id uint16) *endpoint.Endpoint {
	if ep, ok := Endpoints[id]; ok {
		return ep
	}
	return nil
}

// LookupCiliumID looks up endpoint by endpoint ID
func LookupCiliumID(id uint16) *endpoint.Endpoint {
	Mutex.Lock()
	defer Mutex.Unlock()

	return LookupCiliumIDLocked(id)
}

func lookupDockerEndpointLocked(id string) *endpoint.Endpoint {
	if ep, ok := endpointsAux[endpoint.NewID(endpoint.DockerEndpointPrefix, id)]; ok {
		return ep
	}
	return nil
}

func lookupPodNameLocked(name string) *endpoint.Endpoint {
	if ep, ok := endpointsAux[endpoint.NewID(endpoint.PodNamePrefix, name)]; ok {
		return ep
	}
	return nil
}

func lookupDockerContainerNameLocked(name string) *endpoint.Endpoint {
	if ep, ok := endpointsAux[endpoint.NewID(endpoint.ContainerNamePrefix, name)]; ok {
		return ep
	}
	return nil
}

// LookupDockerID looks up endpoint by Docker ID
func LookupDockerID(id string) *endpoint.Endpoint {
	Mutex.Lock()
	defer Mutex.Unlock()

	return LookupDockerIDLocked(id)
}

func lookupIPv4Locked(ipv4 string) *endpoint.Endpoint {
	if ep, ok := endpointsAux[endpoint.NewID(endpoint.IPv4Prefix, ipv4)]; ok {
		return ep
	}
	return nil
}

// LookupIPv4 looks up endpoint by IPv4 address
func LookupIPv4(ipv4 string) *endpoint.Endpoint {
	Mutex.Lock()
	defer Mutex.Unlock()

	return lookupIPv4Locked(ipv4)
}

// LookupDockerIDLocked is identical to LookupDockerID() but with
// endpointmanager.Mutex already held
func LookupDockerIDLocked(id string) *endpoint.Endpoint {
	if ep, ok := endpointsAux[endpoint.NewID(endpoint.ContainerIdPrefix, id)]; ok {
		return ep
	}
	return nil
}

func linkContainerID(ep *endpoint.Endpoint) {
	endpointsAux[endpoint.NewID(endpoint.ContainerIdPrefix, ep.DockerID)] = ep
}

// LinkContainerID links an endpoint and makes it searchable by Docker ID.
// Mutex must be held
func LinkContainerID(ep *endpoint.Endpoint) {
	linkContainerID(ep)
}

// UpdateReferences updates the mappings of various values to their corresponding
// endpoints, such as DockerID, Docker Container Name, Pod Name, etc.
func updateReferences(ep *endpoint.Endpoint) {
	if ep.DockerID != "" {
		linkContainerID(ep)
	}

	if ep.DockerEndpointID != "" {
		endpointsAux[endpoint.NewID(endpoint.DockerEndpointPrefix, ep.DockerEndpointID)] = ep
	}

	if ep.IPv4.String() != "" {
		endpointsAux[endpoint.NewID(endpoint.IPv4Prefix, ep.IPv4.String())] = ep
	}

	if ep.ContainerName != "" {
		endpointsAux[endpoint.NewID(endpoint.ContainerNamePrefix, ep.ContainerName)] = ep
	}

	if ep.PodName != "" {
		endpointsAux[endpoint.NewID(endpoint.PodNamePrefix, ep.PodName)] = ep
	}
}

// UpdateReferences makes an endpoint available by all possible reference
// fields as available for this endpoint (containerID, IPv4 address, ...)
func UpdateReferences(ep *endpoint.Endpoint) {
	Mutex.Lock()
	defer Mutex.Unlock()

	updateReferences(ep)
}

// Insert inserts the endpoint into the global maps
func Insert(ep *endpoint.Endpoint) {
	Endpoints[ep.ID] = ep
	updateReferences(ep)
}

// RemoveLocked is identical to Remove but with endpointmanager.Mutex already held
func RemoveLocked(ep *endpoint.Endpoint) {
	delete(Endpoints, ep.ID)

	if ep.DockerID != "" {
		delete(endpointsAux, endpoint.NewID(endpoint.ContainerIdPrefix, ep.DockerID))
	}

	if ep.DockerEndpointID != "" {
		delete(endpointsAux, endpoint.NewID(endpoint.DockerEndpointPrefix, ep.DockerEndpointID))
	}

	if ep.IPv4.String() != "" {
		delete(endpointsAux, endpoint.NewID(endpoint.IPv4Prefix, ep.IPv4.String()))
	}

	if ep.ContainerName != "" {
		delete(endpointsAux, endpoint.NewID(endpoint.ContainerNamePrefix, ep.ContainerName))
	}

	if ep.PodName != "" {
		delete(endpointsAux, endpoint.NewID(endpoint.PodNamePrefix, ep.PodName))
	}
}

// Remove removes the endpoint from the global maps
func Remove(ep *endpoint.Endpoint) {
	Mutex.Lock()
	RemoveLocked(ep)
	Mutex.Unlock()
}

// Lookup looks up the endpoint by prefix id
func Lookup(id string) (*endpoint.Endpoint, error) {
	Mutex.RLock()
	defer Mutex.RUnlock()

	return LookupLocked(id)
}

// LookupLocked looks up the endpoint by prefix id with the Mutex already held
func LookupLocked(id string) (*endpoint.Endpoint, error) {
	prefix, eid, err := endpoint.ParseID(id)
	if err != nil {
		return nil, err
	}

	switch prefix {
	case endpoint.CiliumLocalIdPrefix:
		n, _ := endpoint.ParseCiliumID(id)
		return LookupCiliumIDLocked(uint16(n)), nil

	case endpoint.CiliumGlobalIdPrefix:
		return nil, fmt.Errorf("Unsupported id format for now")

	case endpoint.ContainerIdPrefix:
		return LookupDockerIDLocked(eid), nil

	case endpoint.DockerEndpointPrefix:
		return lookupDockerEndpointLocked(eid), nil

	case endpoint.ContainerNamePrefix:
		return lookupDockerContainerNameLocked(eid), nil

	case endpoint.PodNamePrefix:
		return lookupPodNameLocked(eid), nil

	case endpoint.IPv4Prefix:
		return lookupIPv4Locked(eid), nil

	default:
		return nil, fmt.Errorf("Unknown endpoint prefix %s", prefix)
	}
}

// TriggerPolicyUpdates calls TriggerPolicyUpdates for each endpoint and
// regenerates as required. During this process, the endpoint list is locked
// and cannot be modified.
// Returns a waiting group that can be used to know when all the endpoints are
// regenerated.
func TriggerPolicyUpdates(owner endpoint.Owner) *sync.WaitGroup {
	var wg sync.WaitGroup

	Mutex.RLock()

	wg.Add(len(Endpoints))

	for k := range Endpoints {
		go func(ep *endpoint.Endpoint, wg *sync.WaitGroup) {
			policyChanges, err := ep.TriggerPolicyUpdates(owner)
			if err != nil {
				log.Warningf("Error while handling policy updates for endpoint %s", err)
				ep.LogStatus(endpoint.Policy, endpoint.Failure, err.Error())
			} else {
				ep.LogStatusOK(endpoint.Policy, "Policy regenerated")
			}
			if policyChanges {
				<-ep.Regenerate(owner)
			}
			wg.Done()
		}(Endpoints[k], &wg)
	}

	Mutex.RUnlock()

	return &wg
}


text:
package cache

import (
	"time"

	expirationcache "k8s.io/client-go/tools/cache"
)

// ObjectCache is a simple wrapper of expiration cache that
// 1. use string type key
// 2. has an updater to get value directly if it is expired
// 3. then update the cache
type ObjectCache struct {
	cache   expirationcache.Store
	updater func() (interface{}, error)
}

// objectEntry is an object with string type key.
type objectEntry struct {
	key string
	obj interface{}
}

// NewObjectCache creates ObjectCache with an updater.
// updater returns an object to cache.
func NewObjectCache(f func() (interface{}, error), ttl time.Duration) *ObjectCache {
	return &ObjectCache{
		updater: f,
		cache:   expirationcache.NewTTLStore(stringKeyFunc, ttl),
	}
}

// stringKeyFunc is a string as cache key function
func stringKeyFunc(obj interface{}) (string, error) {
	key := obj.(objectEntry).key
	return key, nil
}

// Get gets cached objectEntry by using a unique string as the key.
func (c *ObjectCache) Get(key string) (interface{}, error) {
	value, ok, err := c.cache.Get(objectEntry{key: key})
	if err != nil {
		return nil, err
	}
	if !ok {
		obj, err := c.updater()
		if err != nil {
			return nil, err
		}
		err = c.cache.Add(objectEntry{
			key: key,
			obj: obj,
		})
		if err != nil {
			return nil, err
		}
		return obj, nil
	}
	return value.(objectEntry).obj, nil
}

// Add adds objectEntry by using a unique string as the key.
func (c *ObjectCache) Add(key string, obj interface{}) error {
	return c.cache.Add(objectEntry{key: key, obj: obj})
}


text:
#include <QMessageBox>
#include <QGraphicsScene>
#include <QPixmap>
#include <QEvent>
#include <QMouseEvent>
#include <QDir>
#include <QImage>
#include "mainwindow.h"
#include "ui_mainwindow.h"

// 图片高宽等常量
const int kPicWidth_s = 640;
const int kPicWeight_s = 360;
const int kPicWidth_org = 1280;
const int kPicWeight_org = 720;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_ilastCropX = 0;
    m_ilastCropY = 0;
    m_bShotContinuous = false;
    m_pLogic = new XLogic();

    initControl();
    initSignal();
    initGraphView();
    initTableView();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initGraphView()
{
    QDir dir;
    QString path = dir.currentPath() + "/logo.jpg";
    QImage orgImage;
    QImage scaledImage;
    orgImage.load(path);
    scaledImage = orgImage.scaled(kPicWidth_s, kPicWeight_s);
    qDebug() << "load image file" << path;
    ui->graphicsView->installEventFilter(this);
    m_scene.addPixmap(QPixmap::fromImage(scaledImage));
    ui->graphicsView->setScene(&m_scene);
    ui->graphicsView->show();
}

void MainWindow::initSignal()
{
    // signal
    // 连接
    connect(m_pLogic, SIGNAL(s_connected(bool)), this, SLOT(on_x_connect(bool)));
    // 断开
    connect(m_pLogic, SIGNAL(s_disconnected(bool)), this, SLOT(on_x_disconnect(bool)));
    // 得到序列号
    connect(m_pLogic, SIGNAL(s_serial_recieved(const QString &)), this, SLOT(on_x_recieved_serial(const QString &)));
    // 收到摄像头图片
    connect(m_pLogic, SIGNAL(s_camerashot_recieved(QByteArray&)), this, SLOT(on_x_recieved_camerashot(QByteArray&)));
    // 收到车牌识别结果
    connect(m_pLogic, SIGNAL(s_plate_check_result(int,QString)), this, SLOT(on_x_plate_check_result(int,QString)));
}

void MainWindow::initControl()
{
    // 控件初始化
    ui->pushButton_baseAngelRun->setEnabled(true);
    ui->pushButton_neckAngleRun->setEnabled(true);
    ui->pushButton_srvConnect->setEnabled(true);
    ui->pushButton_srvDisConnect->setEnabled(false);
}

void MainWindow::initTableView()
{
    m_tableModel.setColumnCount(7);

    m_tableModel.setHeaderData(0, Qt::Horizontal, "序号");
    m_tableModel.setHeaderData(1, Qt::Horizontal, "B角度");
    m_tableModel.setHeaderData(2, Qt::Horizontal, "N角度");

    m_tableModel.setHeaderData(3, Qt::Horizontal, "剪裁X");
    m_tableModel.setHeaderData(4, Qt::Horizontal, "剪裁Y");
    m_tableModel.setHeaderData(5, Qt::Horizontal, "剪裁宽");
    m_tableModel.setHeaderData(6, Qt::Horizontal, "剪裁高");
    ui->tableView->setModel(&m_tableModel);

    //设置列宽不可变
    for (int i = 0; i < 7; ++i)
    {
        ui->tableView->setColumnWidth(i, 80);
    }
}

// 设置断开时候的控件状态
void MainWindow::setDisConnectControlState()
{
    ui->lineEdit_srvIp->setEnabled(true);
    ui->lineEdit_srvPort->setEnabled(true);

    ui->pushButton_srvConnect->setEnabled(true);
    ui->pushButton_srvDisConnect->setEnabled(false);

    ui->pushButton_baseAngelRun->setEnabled(false);
    ui->pushButton_neckAngleRun->setEnabled(false);
}

// 设置连接时候的控件状态
void MainWindow::setConnectControlState()
{
    ui->lineEdit_srvIp->setEnabled(false);
    ui->lineEdit_srvPort->setEnabled(false);

    ui->pushButton_srvConnect->setEnabled(false);
    ui->pushButton_srvDisConnect->setEnabled(true);

    ui->pushButton_baseAngelRun->setEnabled(true);
    ui->pushButton_neckAngleRun->setEnabled(true);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/*!
 * \brief 单击连接后
 */
void MainWindow::on_pushButton_srvConnect_clicked()
{
    setConnectControlState();
    m_pLogic->setCurIp(ui->lineEdit_srvIp->text());
    m_pLogic->setCurPort(ui->lineEdit_srvPort->text().trimmed().toShort());
    m_pLogic->ConnectHost();
}

/*!
 * \brief 单击断开
 */
void MainWindow::on_pushButton_srvDisConnect_clicked()
{
    m_pLogic->DisConnectHost();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 自定义槽
/*!
 * \brief 接受到序列号
 * \param serial
 */
void MainWindow::on_x_recieved_serial(const QString &serial)
{
    ui->label_serial->setText("设备序号: " + serial);
}

/*!
 * \brief 接收到摄像头图片
 * \param data
 */
void MainWindow::on_x_recieved_camerashot(QByteArray &data)
{
    QPixmap pixmap;
    pixmap.loadFromData(data);
    QPixmap pixmap_s = pixmap.scaled(kPicWidth_s, kPicWeight_s);
    m_scene.addPixmap(pixmap_s);
    ui->graphicsView->show();

    if (m_bShotContinuous == true)
    {
        m_pLogic->screenShot();
    }
}

void MainWindow::on_x_plate_check_result(int plateCount, const QString &plateResult)
{
    // 车牌识别结果
    if (plateCount == 0)
    {
        ui->label_plateResult->setText("未识别到车牌");
    }
    else
    {
        ui->label_plateResult->setText(plateResult);
    }
}

/*!
 * \brief 断开状态
 * \param ret
 */
void MainWindow::on_x_disconnect(bool ret)
{
    ui->label_connState->setText("未连接");
    ui->label_serial->setText("设备序号: 000000000000");
    setDisConnectControlState();
}

/*!
 * \brief 连接状态
 * \param ret
 */
void MainWindow::on_x_connect(bool ret)
{
    if (ret == true)
    {
        ui->label_connState->setText("已连接");
        ui->label_serial->setText("请等待设备序号返回");
    }
    else
    {
        ui->label_connState->setText("未连接");
        QMessageBox::warning(0, "错误", "连接失败,请检查网络", 0, 0);
        setDisConnectControlState();
    }
}

/*!
 * \brief 点击base角度运行到
 */
void MainWindow::on_pushButton_baseAngelRun_clicked()
{
    on_doubleSpinBox_baseAngle_editingFinished();
    double value = ui->doubleSpinBox_baseAngle->text().toDouble();
    m_pLogic->BaseAngleRunTo(value);
}

/*!
 * \brief 点击neck角度运行到
 */
void MainWindow::on_pushButton_neckAngleRun_clicked()
{
    on_doubleSpinBox_neckAngle_editingFinished();
    double value = ui->doubleSpinBox_neckAngle->text().toDouble();
    m_pLogic->NeckAngleRunTo(value);
}

// 这个必须是0.375的倍数,若被编辑后,应修改为最接近0.375的倍数值
void MainWindow::on_doubleSpinBox_baseAngle_editingFinished()
{
    double value = ui->doubleSpinBox_baseAngle->text().toDouble();
    double step = ui->doubleSpinBox_baseAngle->singleStep();
    double v = m_pLogic->adjustAngleValue(value, step);
    ui->doubleSpinBox_baseAngle->setValue(v);
}

// 这个必须是0.9的倍数,若被编辑后,应修改为最接近0.9的倍数值
void MainWindow::on_doubleSpinBox_neckAngle_editingFinished()
{
    double value = ui->doubleSpinBox_neckAngle->text().toDouble();
    double step = ui->doubleSpinBox_neckAngle->singleStep();
    double v = m_pLogic->adjustAngleValue(value, step);
    ui->doubleSpinBox_neckAngle->setValue(v);
}

// 点击单次截屏
void MainWindow::on_pushButton_singleScreenShot_clicked()
{
    if (m_bShotContinuous == true)
    {
        return;
    }
    m_pLogic->screenShot();
}

// 单击连续截屏
void MainWindow::on_pushButton_continuousScreenShot_clicked()
{
    // 连续截屏的方式为, 上一次截图完成, 显示完图片后, 则立刻开始下一次截屏
    if (m_bShotContinuous == true)
    {
        m_bShotContinuous = false;
        ui->pushButton_continuousScreenShot->setText("连续截图");
    }
    else
    {
        m_bShotContinuous = true;
        ui->pushButton_continuousScreenShot->setText("停止截图");
        m_pLogic->screenShot();
    }
}

// 单击车牌识别
void MainWindow::on_pushButton_plateCheck_clicked()
{
    int cropX = ui->lineEdit_cropX->text().toInt();
    int cropY = ui->lineEdit_cropY->text().toInt();
    int cropWidth = ui->lineEdit_cropWidth->text().toInt();
    int cropHeight = ui->lineEdit_cropHeight->text().toInt();
    if (cropWidth == 0 || cropHeight == 0)
    {
        QMessageBox::warning(0, "错误", "截图区域不正确", 0, 0);
        return;
    }
    m_pLogic->plateCheck(cropX, cropY, cropWidth, cropHeight);
}

// 单击写入当前设备某角度值
void MainWindow::on_pushButton_saveCurAngle_clicked()
{
    // 得到两个角度值
    double baseAngle = ui->doubleSpinBox_baseAngle->text().toDouble();
    double neckAngle = ui->doubleSpinBox_neckAngle->text().toDouble();

    // 得到截屏数据
    int cropX = ui->lineEdit_cropX->text().toInt();
    int cropY = ui->lineEdit_cropY->text().toInt();
    int cropWidth = ui->lineEdit_cropWidth->text().toInt();
    int cropWeight = ui->lineEdit_cropHeight->text().toInt();

    AngleItem item(baseAngle, neckAngle, cropX, cropY, cropWidth, cropWeight);

    if (m_angelData.contains(m_pLogic->m_curSerial))
    {
        m_angelData[m_pLogic->m_curSerial].append(item);
        showAngleTable(m_angelData[m_pLogic->m_curSerial]);
    }
    else
    {
        QList<AngleItem> ls;
        ls.append(item);
        m_angelData.insert(m_pLogic->m_curSerial, ls);
        showAngleTable(ls);
    }

// 单击写入当前设备值到文件
}
void MainWindow::on_pushButton_saveCurDevice_clicked()
{

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 主要用于监视图片空间是鼠标移动等事件
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    // 图片控件
    if (obj == ui->graphicsView)
    {
        // qDebug() << event->type();
        if (event->type() == QEvent::MouseMove)
        {
            QMouseEvent* e = (QMouseEvent*)event;
            QString xstr;
            QString ystr;
            xstr = QString("%1").arg(e->x());
            ystr = QString("%1").arg(e->y());
            // qDebug() << xstr << ystr;
            ui->lineEdit_mouseX->setText(xstr);
            ui->lineEdit_mouseY->setText(ystr);
        }
        else if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent* e = (QMouseEvent*)event;
            int curX = e->x();
            int curY = e->y();
            onClickPic(curX, curY);
        }
    }
    return QWidget::eventFilter(obj, event);
}

// 在图片上点击了, 用来处理屏幕截取的区域等等
void MainWindow::onClickPic(int curX, int curY)
{
    if (curX < m_ilastCropX || curY < m_ilastCropY)
    {
        ui->lineEdit_cropX->setText(QString("%1").arg(curX * 2));
        ui->lineEdit_cropY->setText(QString("%1").arg(curY * 2));
        ui->lineEdit_cropXEnd->setText("0");
        ui->lineEdit_cropYEnd->setText("0");
        ui->lineEdit_cropWidth->setText("0");
        ui->lineEdit_cropHeight->setText("0");
    }
    else if (curX >= m_ilastCropX && curY >= m_ilastCropY)
    {
        int width = curX - m_ilastCropX;
        int height = curY - m_ilastCropY;
        ui->lineEdit_cropWidth->setText(QString("%1").arg(width * 2));
        ui->lineEdit_cropHeight->setText(QString("%1").arg(height * 2));

        ui->lineEdit_cropX->setText(QString("%1").arg(m_ilastCropX * 2));
        ui->lineEdit_cropY->setText(QString("%1").arg(m_ilastCropY * 2));
        ui->lineEdit_cropXEnd->setText(QString("%1").arg(curX * 2));
        ui->lineEdit_cropYEnd->setText(QString("%1").arg(curY * 2));
    }

    m_ilastCropX = curX;
    m_ilastCropY = curY;
}

// 在表中显示角度值
void MainWindow::showAngleTable(QList<AngleItem> &data)
{
    // "序号"
    // "B角度"
    // "N角度"
    // "剪裁X"
    // "剪裁Y"
    // "剪裁宽"
    // "剪裁高"
    m_tableModel.removeRows(0, m_tableModel.rowCount());
    // 清空表中内容
    for (int i = 0; i < data.size(); ++i)
    {
        const AngleItem &item = data.at(i);
        m_tableModel.setItem(i, 0, new QStandardItem(QString("%1").arg(i+1)));
        m_tableModel.setItem(i, 1, new QStandardItem(QString("%1").arg(item.baseAngle)));
        m_tableModel.setItem(i, 2, new QStandardItem(QString("%1").arg(item.neckAngle)));
        m_tableModel.setItem(i, 3, new QStandardItem(QString("%1").arg(item.cropX)));
        m_tableModel.setItem(i, 4, new QStandardItem(QString("%1").arg(item.cropY)));
        m_tableModel.setItem(i, 5, new QStandardItem(QString("%1").arg(item.cropWidth)));
        m_tableModel.setItem(i, 6, new QStandardItem(QString("%1").arg(item.cropHeight)));
    }
}


text:
.footer {
	font-size: xx-small;
}
.profile-img-32 {
    width: 32px;
    height: 32px;
    vertical-align: inherit;
}
.pretty-dd {
    margin-bottom: 0;
}
.pretty-dd input[type="checkbox"] {
    display: none;
}
.pretty-dd input[type="checkbox"] + .btn-group > label span {
    width: 20px;
}
.pretty-dd input[type="checkbox"] + .btn-group > label span:first-child {
    display: none;
}
.pretty-dd input[type="checkbox"] + .btn-group > label span:last-child {
    display: inline-block;
}
.pretty-dd input[type="checkbox"]:checked + .btn-group > label span:first-child {
    display: inline-block;
}
.pretty-dd input[type="checkbox"]:checked + .btn-group > label span:last-child {
    display: none;
}


text:
package armsynapse

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// IntegrationRuntimeConnectionInfosClient contains the methods for the IntegrationRuntimeConnectionInfos group.
// Don't use this type directly, use NewIntegrationRuntimeConnectionInfosClient() instead.
type IntegrationRuntimeConnectionInfosClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewIntegrationRuntimeConnectionInfosClient creates a new instance of IntegrationRuntimeConnectionInfosClient with the specified values.
// subscriptionID - The ID of the target subscription.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewIntegrationRuntimeConnectionInfosClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*IntegrationRuntimeConnectionInfosClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &IntegrationRuntimeConnectionInfosClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// Get - Get connection info for an integration runtime
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-06-01-preview
// resourceGroupName - The name of the resource group. The name is case insensitive.
// workspaceName - The name of the workspace.
// integrationRuntimeName - Integration runtime name
// options - IntegrationRuntimeConnectionInfosClientGetOptions contains the optional parameters for the IntegrationRuntimeConnectionInfosClient.Get
// method.
func (client *IntegrationRuntimeConnectionInfosClient) Get(ctx context.Context, resourceGroupName string, workspaceName string, integrationRuntimeName string, options *IntegrationRuntimeConnectionInfosClientGetOptions) (IntegrationRuntimeConnectionInfosClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, workspaceName, integrationRuntimeName, options)
	if err != nil {
		return IntegrationRuntimeConnectionInfosClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return IntegrationRuntimeConnectionInfosClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return IntegrationRuntimeConnectionInfosClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *IntegrationRuntimeConnectionInfosClient) getCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, integrationRuntimeName string, options *IntegrationRuntimeConnectionInfosClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/integrationRuntimes/{integrationRuntimeName}/getConnectionInfo"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if workspaceName == "" {
		return nil, errors.New("parameter workspaceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName))
	if integrationRuntimeName == "" {
		return nil, errors.New("parameter integrationRuntimeName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{integrationRuntimeName}", url.PathEscape(integrationRuntimeName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-06-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *IntegrationRuntimeConnectionInfosClient) getHandleResponse(resp *http.Response) (IntegrationRuntimeConnectionInfosClientGetResponse, error) {
	result := IntegrationRuntimeConnectionInfosClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.IntegrationRuntimeConnectionInfo); err != nil {
		return IntegrationRuntimeConnectionInfosClientGetResponse{}, err
	}
	return result, nil
}


text:
<?php

namespace Main\MainBundle\Form;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\FormBuilderInterface;

class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        //ici nous allons faire notre formulaire en PHP
        $builder
//            ->add('firstname', 'text', array('label' => 'Prenom',
//                                          'attr' => array('class' => 'input-medium search-query form-control',
//                                          'placeholder' => 'Prenom',)))

            ->add('lastname', 'text', array('label' => 'Nom',
                                          'attr' => array('class' => 'input-medium search-query form-control',
                                          'placeholder' => 'Nom',)))

            ->add('email', EmailType::class, array('label' => 'Email',
                                          'attr' => array('class' => 'input-medium search-query form-control',
                                          'placeholder' => 'Adresse Email',)))

            ->add('phone', 'text', array('label' => 'Telephone',
                                          'attr' => array('class' => 'input-medium search-query form-control',
                                          'placeholder' => 'Telephone',)))

            ->add('message', 'textarea', array('label' => 'Message',
                                          'attr' => array('class' => 'input-medium search-query form-control',
                                          'placeholder' => 'Votre message',)))
            ->add('Send', 'submit', array('label' => 'Envoyer',
                                          'attr' => array('class' => 'btn btn-danger raised',
                                          'placeholder' => 'Envoyer',)));

    }

    public function getName()
    {
        return 'main_mainbundle_contact';
    }
}


text:
package com.arjuna.ats.internal.jta.tools.osb.mbean.jts;

import com.arjuna.ats.arjuna.coordinator.AbstractRecord;
import com.arjuna.ats.arjuna.tools.osb.mbean.*;
import com.arjuna.ats.internal.jta.resources.jts.orbspecific.XAResourceRecord;
import com.arjuna.ats.internal.jta.tools.osb.mbean.jta.JTAActionBean;
import com.arjuna.ats.internal.jta.tools.osb.mbean.jta.XARecoveryResourceMBean;
import com.arjuna.ats.internal.jts.resources.ExtendedResourceRecord;

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

/**
 *
 * @author Mike Musgrove
 */
/**
 * @deprecated as of 5.0.5.Final In a subsequent release we will change packages names in order to
 * provide a better separation between public and internal classes.
 */
@Deprecated // in order to provide a better separation between public and internal classes.
public class JTSActionBean extends JTAActionBean {
    // ExtendedResourceRecord does not statically expose its type
    private static String ERRT = "StateManager/AbstractRecord/ExtendedResourceRecord";
    private static List<XARecoveryResourceMBean> xaRecoveryResourceMBeans = null;

    public JTSActionBean(UidWrapper w) {
        super(w);
    }

    @Override
    protected LogRecordWrapper createParticipant(AbstractRecord rec, ParticipantStatus listType) {
        if (rec instanceof ExtendedResourceRecord)
            return new XAResourceRecordBean(this, rec, listType);

        return super.createParticipant(rec, listType);
    }

    static synchronized void getXARecoveryResourceMBeans(UidWrapper uidWrapper) {
        if (xaRecoveryResourceMBeans == null) {
            xaRecoveryResourceMBeans = new ArrayList<XARecoveryResourceMBean>();

            List<UidWrapper> wrappers = uidWrapper.probe(XAResourceRecord.typeName());

            if (wrappers != null) {
                for (UidWrapper w : wrappers) {
                    OSEntryBean bean = w.getMBean();

                    if (bean != null && bean instanceof XARecoveryResourceMBean)
                        xaRecoveryResourceMBeans.add((XARecoveryResourceMBean) bean);
                }
            }
        }
    }

    private XARecoveryResourceMBean findJTSXAResourceRecordWrapper(XAResourceRecordBean xarrb) {
        getXARecoveryResourceMBeans(_uidWrapper);

        for (XARecoveryResourceMBean bean : xaRecoveryResourceMBeans) {
            if (xarrb.xares.xidImple.equals(((JTSXAResourceRecordWrapper) bean).xidImple))
                return bean;
        }

        return null;
    }

    @Override
    public void register() {
        super.register();

        // for each ExtendedResourceRecord see if there is a corresponding XARecoveryResource entry in the local store
        for (LogRecordWrapper participant : getParticipants()) {
            if (participant instanceof XAResourceRecordBean) {
                // this is an ExtendedResourceRecord
                XAResourceRecordBean xarrb = (XAResourceRecordBean) participant;

                // see if there is a corresponding JTSXAResourceRecordWrapper for this participant
                XARecoveryResourceMBean jtsxaResourceRecordWrapper = findJTSXAResourceRecordWrapper(xarrb);

                if (jtsxaResourceRecordWrapper != null && jtsxaResourceRecordWrapper instanceof JTSXAResourceRecordWrapper)
                    xarrb.setJtsXAResourceRecord((JTSXAResourceRecordWrapper) jtsxaResourceRecordWrapper);
            }
        }
    }
}


text:
<?php

namespace Drupal\KernelTests\Core\File;

use Drupal\Core\Site\Settings;
use Drupal\Core\File\FileSystem;

/**
 * Tests the unmanaged file copy function.
 *
 * @group File
 */
class UnmanagedCopyTest extends FileTestBase {
  /**
   * Copy a normal file.
   */
  public function testNormal() {
    // Create a file for testing
    $uri = $this->createUri();

    // Copying to a new name.
    $desired_filepath = 'public://' . $this->randomMachineName();
    $new_filepath = file_unmanaged_copy($uri, $desired_filepath, FILE_EXISTS_ERROR);
    $this->assertTrue($new_filepath, 'Copy was successful.');
    $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
    $this->assertTrue(file_exists($uri), 'Original file remains.');
    $this->assertTrue(file_exists($new_filepath), 'New file exists.');
    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));

    // Copying with rename.
    $desired_filepath = 'public://' . $this->randomMachineName();
    $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
    $newer_filepath = file_unmanaged_copy($uri, $desired_filepath, FILE_EXISTS_RENAME);
    $this->assertTrue($newer_filepath, 'Copy was successful.');
    $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
    $this->assertTrue(file_exists($uri), 'Original file remains.');
    $this->assertTrue(file_exists($newer_filepath), 'New file exists.');
    $this->assertFilePermissions($newer_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));

    // TODO: test copying to a directory (rather than full directory/file path)
    // TODO: test copying normal files using normal paths (rather than only streams)
  }

  /**
   * Copy a non-existent file.
   */
  public function testNonExistent() {
    // Copy non-existent file
    $desired_filepath = $this->randomMachineName();
    $this->assertFalse(file_exists($desired_filepath), "Randomly named file doesn't exists.");
    $new_filepath = file_unmanaged_copy($desired_filepath, $this->randomMachineName());
    $this->assertFalse($new_filepath, 'Copying a missing file fails.');
  }

  /**
   * Copy a file onto itself.
   */
  public function testOverwriteSelf() {
    // Create a file for testing
    $uri = $this->createUri();

    // Copy the file onto itself with renaming works.
    $new_filepath = file_unmanaged_copy($uri, $uri, FILE_EXISTS_RENAME);
    $this->assertTrue($new_filepath, 'Copying onto itself with renaming works.');
    $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
    $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
    $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));

    // Copy the file onto itself without renaming fails.
    $new_filepath = file_unmanaged_copy($uri, $uri, FILE_EXISTS_ERROR);
    $this->assertFalse($new_filepath, 'Copying onto itself without renaming fails.');
    $this->assertTrue(file_exists($uri), 'File exists after copying onto itself.');

    // Copy the file into same directory without renaming fails.
    $new_filepath = file_unmanaged_copy($uri, drupal_dirname($uri), FILE_EXISTS_ERROR);
    $this->assertFalse($new_filepath, 'Copying onto itself fails.');
    $this->assertTrue(file_exists($uri), 'File exists after copying onto itself.');

    // Copy the file into same directory with renaming works.
    $new_filepath = file_unmanaged_copy($uri, drupal_dirname($uri), FILE_EXISTS_RENAME);
    $this->assertTrue($new_filepath, 'Copying into same directory works.');
    $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
    $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
    $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));
  }

}


text:
  Saint-Agnan-en-Vercors est
       un village
       localisé dans le département de Drôme en Rhône-Alpes. Elle totalisait 386 habitants en 2008.

À proximité de Saint-Agnan-en-Vercors sont positionnées géographiquement les communes de
Gresse-en-Vercors située à 11 km, 365 habitants,
Saint-Julien-en-Vercors située à 12 km, 220 habitants,
Saint-Guillaume située à 12 km, 252 habitants,
Saint-Martin-en-Vercors située à 9 km, 357 habitants,
Bouvante localisée à 12 km, 237 habitants,
Corrençon-en-Vercors à 12 km, 367 habitants,
 entre autres. De plus, Saint-Agnan-en-Vercors est située à seulement 29 km de Le Pont-de-Claix.

Si vous envisagez de demenager à Saint-Agnan-en-Vercors, vous pourrez facilement trouver une maison à vendre.

Le parc de logements, à Saint-Agnan-en-Vercors, était réparti en 2011 en 195 appartements et 307 maisons soit
 un marché plutôt équilibré.

La commune offre de multiples  équipements, elle dispose, entre autres, de deux terrains de tennis, un domaine skiable et une boucle de randonnée.