text
stringlengths 2
100k
| meta
dict |
---|---|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <NewsUI2/NSObject-Protocol.h>
@class NSString, UIActivityViewController, UIImage;
@protocol UIActivityItemSource <NSObject>
- (id)activityViewController:(UIActivityViewController *)arg1 itemForActivityType:(NSString *)arg2;
- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)arg1;
@optional
- (UIImage *)activityViewController:(UIActivityViewController *)arg1 thumbnailImageForActivityType:(NSString *)arg2 suggestedSize:(struct CGSize)arg3;
- (NSString *)activityViewController:(UIActivityViewController *)arg1 dataTypeIdentifierForActivityType:(NSString *)arg2;
- (NSString *)activityViewController:(UIActivityViewController *)arg1 subjectForActivityType:(NSString *)arg2;
@end
| {
"pile_set_name": "Github"
} |
Range [0x7f51eda65000, 0x7f51eda8b000) uses 0x26000 bytes.
Region use: used by module
This is for module /lib/x86_64-linux-gnu/ld-2.23.so.
Range [0x7fffe22fd000, 0x7fffe22ff000) uses 0x2000 bytes.
Region use: unknown
Range [0xffffffffff600000, 0xffffffffff601000) uses 0x1000 bytes.
Region use: unknown
3 rx-only ranges use 0x29000 (167,936) bytes.
| {
"pile_set_name": "Github"
} |
package msgpack
import (
"math"
"reflect"
"github.com/vmihailenco/msgpack/codes"
)
// EncodeUint8 encodes an uint8 in 2 bytes preserving type of the number.
func (e *Encoder) EncodeUint8(n uint8) error {
return e.write1(codes.Uint8, n)
}
func (e *Encoder) encodeUint8Cond(n uint8) error {
if e.useCompact {
return e.EncodeUint(uint64(n))
}
return e.EncodeUint8(n)
}
// EncodeUint16 encodes an uint16 in 3 bytes preserving type of the number.
func (e *Encoder) EncodeUint16(n uint16) error {
return e.write2(codes.Uint16, n)
}
func (e *Encoder) encodeUint16Cond(n uint16) error {
if e.useCompact {
return e.EncodeUint(uint64(n))
}
return e.EncodeUint16(n)
}
// EncodeUint32 encodes an uint16 in 5 bytes preserving type of the number.
func (e *Encoder) EncodeUint32(n uint32) error {
return e.write4(codes.Uint32, n)
}
func (e *Encoder) encodeUint32Cond(n uint32) error {
if e.useCompact {
return e.EncodeUint(uint64(n))
}
return e.EncodeUint32(n)
}
// EncodeUint64 encodes an uint16 in 9 bytes preserving type of the number.
func (e *Encoder) EncodeUint64(n uint64) error {
return e.write8(codes.Uint64, n)
}
func (e *Encoder) encodeUint64Cond(n uint64) error {
if e.useCompact {
return e.EncodeUint(n)
}
return e.EncodeUint64(n)
}
// EncodeInt8 encodes an int8 in 2 bytes preserving type of the number.
func (e *Encoder) EncodeInt8(n int8) error {
return e.write1(codes.Int8, uint8(n))
}
func (e *Encoder) encodeInt8Cond(n int8) error {
if e.useCompact {
return e.EncodeInt(int64(n))
}
return e.EncodeInt8(n)
}
// EncodeInt16 encodes an int16 in 3 bytes preserving type of the number.
func (e *Encoder) EncodeInt16(n int16) error {
return e.write2(codes.Int16, uint16(n))
}
func (e *Encoder) encodeInt16Cond(n int16) error {
if e.useCompact {
return e.EncodeInt(int64(n))
}
return e.EncodeInt16(n)
}
// EncodeInt32 encodes an int32 in 5 bytes preserving type of the number.
func (e *Encoder) EncodeInt32(n int32) error {
return e.write4(codes.Int32, uint32(n))
}
func (e *Encoder) encodeInt32Cond(n int32) error {
if e.useCompact {
return e.EncodeInt(int64(n))
}
return e.EncodeInt32(n)
}
// EncodeInt64 encodes an int64 in 9 bytes preserving type of the number.
func (e *Encoder) EncodeInt64(n int64) error {
return e.write8(codes.Int64, uint64(n))
}
func (e *Encoder) encodeInt64Cond(n int64) error {
if e.useCompact {
return e.EncodeInt(n)
}
return e.EncodeInt64(n)
}
// EncodeUnsignedNumber encodes an uint64 in 1, 2, 3, 5, or 9 bytes.
// Type of the number is lost during encoding.
func (e *Encoder) EncodeUint(n uint64) error {
if n <= math.MaxInt8 {
return e.w.WriteByte(byte(n))
}
if n <= math.MaxUint8 {
return e.EncodeUint8(uint8(n))
}
if n <= math.MaxUint16 {
return e.EncodeUint16(uint16(n))
}
if n <= math.MaxUint32 {
return e.EncodeUint32(uint32(n))
}
return e.EncodeUint64(uint64(n))
}
// EncodeNumber encodes an int64 in 1, 2, 3, 5, or 9 bytes.
// Type of number is lost during encoding.
func (e *Encoder) EncodeInt(n int64) error {
if n >= 0 {
return e.EncodeUint(uint64(n))
}
if n >= int64(int8(codes.NegFixedNumLow)) {
return e.w.WriteByte(byte(n))
}
if n >= math.MinInt8 {
return e.EncodeInt8(int8(n))
}
if n >= math.MinInt16 {
return e.EncodeInt16(int16(n))
}
if n >= math.MinInt32 {
return e.EncodeInt32(int32(n))
}
return e.EncodeInt64(int64(n))
}
func (e *Encoder) EncodeFloat32(n float32) error {
return e.write4(codes.Float, math.Float32bits(n))
}
func (e *Encoder) EncodeFloat64(n float64) error {
return e.write8(codes.Double, math.Float64bits(n))
}
func (e *Encoder) write1(code codes.Code, n uint8) error {
e.buf = e.buf[:2]
e.buf[0] = byte(code)
e.buf[1] = byte(n)
return e.write(e.buf)
}
func (e *Encoder) write2(code codes.Code, n uint16) error {
e.buf = e.buf[:3]
e.buf[0] = byte(code)
e.buf[1] = byte(n >> 8)
e.buf[2] = byte(n)
return e.write(e.buf)
}
func (e *Encoder) write4(code codes.Code, n uint32) error {
e.buf = e.buf[:5]
e.buf[0] = byte(code)
e.buf[1] = byte(n >> 24)
e.buf[2] = byte(n >> 16)
e.buf[3] = byte(n >> 8)
e.buf[4] = byte(n)
return e.write(e.buf)
}
func (e *Encoder) write8(code codes.Code, n uint64) error {
e.buf = e.buf[:9]
e.buf[0] = byte(code)
e.buf[1] = byte(n >> 56)
e.buf[2] = byte(n >> 48)
e.buf[3] = byte(n >> 40)
e.buf[4] = byte(n >> 32)
e.buf[5] = byte(n >> 24)
e.buf[6] = byte(n >> 16)
e.buf[7] = byte(n >> 8)
e.buf[8] = byte(n)
return e.write(e.buf)
}
func encodeUint8CondValue(e *Encoder, v reflect.Value) error {
return e.encodeUint8Cond(uint8(v.Uint()))
}
func encodeUint16CondValue(e *Encoder, v reflect.Value) error {
return e.encodeUint16Cond(uint16(v.Uint()))
}
func encodeUint32CondValue(e *Encoder, v reflect.Value) error {
return e.encodeUint32Cond(uint32(v.Uint()))
}
func encodeUint64CondValue(e *Encoder, v reflect.Value) error {
return e.encodeUint64Cond(v.Uint())
}
func encodeInt8CondValue(e *Encoder, v reflect.Value) error {
return e.encodeInt8Cond(int8(v.Int()))
}
func encodeInt16CondValue(e *Encoder, v reflect.Value) error {
return e.encodeInt16Cond(int16(v.Int()))
}
func encodeInt32CondValue(e *Encoder, v reflect.Value) error {
return e.encodeInt32Cond(int32(v.Int()))
}
func encodeInt64CondValue(e *Encoder, v reflect.Value) error {
return e.encodeInt64Cond(v.Int())
}
func encodeFloat32Value(e *Encoder, v reflect.Value) error {
return e.EncodeFloat32(float32(v.Float()))
}
func encodeFloat64Value(e *Encoder, v reflect.Value) error {
return e.EncodeFloat64(v.Float())
}
| {
"pile_set_name": "Github"
} |
import { AppPage } from './app.po';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('Welcome to ngxsmoothdnd!');
});
});
| {
"pile_set_name": "Github"
} |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
/*
*
* (C) Copyright IBM Corp. 1998-2010 - All Rights Reserved
*
*/
#ifndef __HANGULAYOUTENGINE_H
#define __HANGULAYOUTENGINE_H
#include "LETypes.h"
#include "LEFontInstance.h"
#include "LEGlyphFilter.h"
#include "LayoutEngine.h"
#include "OpenTypeLayoutEngine.h"
#include "GlyphSubstitutionTables.h"
#include "GlyphDefinitionTables.h"
#include "GlyphPositioningTables.h"
U_NAMESPACE_BEGIN
class MPreFixups;
class LEGlyphStorage;
/**
* This class implements OpenType layout for Old Hangul OpenType fonts, as
* specified by Microsoft in "Creating and Supporting OpenType Fonts for
* The Korean Hangul Script" (http://www.microsoft.com/typography/otfntdev/hangulot/default.htm)
*
* This class overrides the characterProcessing method to do Hangul character processing.
* (See the MS spec. for more details)
*
* @internal
*/
class HangulOpenTypeLayoutEngine : public OpenTypeLayoutEngine
{
public:
/**
* This is the main constructor. It constructs an instance of HangulOpenTypeLayoutEngine for
* a particular font, script and language. It takes the GSUB table as a parameter since
* LayoutEngine::layoutEngineFactory has to read the GSUB table to know that it has an
* Hangul OpenType font.
*
* @param fontInstance - the font
* @param scriptCode - the script
* @param langaugeCode - the language
* @param gsubTable - the GSUB table
* @param success - set to an error code if the operation fails
*
* @see LayoutEngine::layoutEngineFactory
* @see OpenTypeLayoutEngine
* @see ScriptAndLangaugeTags.h for script and language codes
*
* @internal
*/
HangulOpenTypeLayoutEngine(const LEFontInstance *fontInstance, le_int32 scriptCode, le_int32 languageCode,
le_int32 typoFlags, const LEReferenceTo<GlyphSubstitutionTableHeader> &gsubTable, LEErrorCode &success);
/**
* This constructor is used when the font requires a "canned" GSUB table which can't be known
* until after this constructor has been invoked.
*
* @param fontInstance - the font
* @param scriptCode - the script
* @param langaugeCode - the language
* @param success - set to an error code if the operation fails
*
* @see OpenTypeLayoutEngine
* @see ScriptAndLangaugeTags.h for script and language codes
*
* @internal
*/
HangulOpenTypeLayoutEngine(const LEFontInstance *fontInstance, le_int32 scriptCode, le_int32 languageCode,
le_int32 typoFlags, LEErrorCode &success);
/**
* The destructor, virtual for correct polymorphic invocation.
*
* @internal
*/
virtual ~HangulOpenTypeLayoutEngine();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.8
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.8
*/
static UClassID getStaticClassID();
protected:
/**
* This method does Hangul OpenType character processing. It assigns the OpenType feature
* tags to the characters, and may compose a character sequence into a modern Hangul syllable,
* or decompose a modern Hangul syllable if it forms part of an old Hangul syllable.
*
* Input parameters:
* @param chars - the input character context
* @param offset - the index of the first character to process
* @param count - the number of characters to process
* @param max - the number of characters in the input context
* @param rightToLeft - <code>TRUE</code> if the characters are in a right to left directional run
* @param glyphStorage - the glyph storage object. The glyph and character index arrays will be set.
* the auxillary data array will be set to the feature tags.
*
* Output parameters:
* @param success - set to an error code if the operation fails
*
* @return the output character count
*
* @internal
*/
virtual le_int32 characterProcessing(const LEUnicode chars[], le_int32 offset, le_int32 count, le_int32 max, le_bool rightToLeft,
LEUnicode *&outChars, LEGlyphStorage &glyphStorage, LEErrorCode &success);
};
U_NAMESPACE_END
#endif
| {
"pile_set_name": "Github"
} |
#
# Server-side
<reply>
<data nocheck=1>
HTTP/1.1 407 Needs proxy authentication
Server: test-server/fake swsclose yesyes
Proxy-Authenticate: Basic "oh please"
Connection: close
bing
</data>
</reply>
#
# Client-side
<client>
<server>
http
</server>
<features>
SSL
</features>
<name>
HTTPS GET with failed proxy auth
</name>
<command>
https://test.anything.really.com:94 -x %HOSTIP:%HOSTPORT
</command>
</client>
#
# Verify data after the test has been "shot"
<verify>
<errorcode>
56
</errorcode>
<strip>
^User-Agent:.*
</strip>
<protocol>
CONNECT test.anything.really.com:94 HTTP/1.0
User-Agent: curl/7.11.0-CVS (i686-pc-linux-gnu) libcurl/7.11.0-CVS OpenSSL/0.9.6b ipv6 zlib/1.1.4
</protocol>
</verify>
| {
"pile_set_name": "Github"
} |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.qa.performance.engine.junit;
import static org.camunda.bpm.engine.authorization.Authorization.ANY;
import static org.camunda.bpm.engine.authorization.Authorization.AUTH_TYPE_GRANT;
import java.util.List;
import org.camunda.bpm.engine.AuthorizationService;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.authorization.Authorization;
import org.camunda.bpm.engine.authorization.Permission;
import org.camunda.bpm.engine.authorization.Resource;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.qa.performance.engine.framework.PerfTestBuilder;
import org.camunda.bpm.qa.performance.engine.framework.PerfTestConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.RuleChain;
/**
* @author Daniel Meyer
*
*/
public abstract class AuthorizationPerformanceTestCase {
public PerfTestConfigurationRule testConfigurationRule = new PerfTestConfigurationRule();
public PerfTestResultRecorderRule resultRecorderRule = new PerfTestResultRecorderRule();
@Rule
public RuleChain ruleChain = RuleChain
.outerRule(testConfigurationRule)
.around(resultRecorderRule);
protected ProcessEngine engine;
protected TaskService taskService;
protected HistoryService historyService;
protected RuntimeService runtimeService;
protected RepositoryService repositoryService;
@Before
public void setup() {
engine = PerfTestProcessEngine.getInstance();
taskService = engine.getTaskService();
historyService = engine.getHistoryService();
runtimeService = engine.getRuntimeService();
repositoryService = engine.getRepositoryService();
}
public PerfTestBuilder performanceTest() {
PerfTestConfiguration configuration = testConfigurationRule.getPerformanceTestConfiguration();
configuration.setPlatform("camunda BPM");
return new PerfTestBuilder(configuration, resultRecorderRule);
}
protected void grouptGrant(String groupId, Resource resource, Permission... perms) {
AuthorizationService authorizationService = engine.getAuthorizationService();
Authorization groupGrant = authorizationService.createNewAuthorization(AUTH_TYPE_GRANT);
groupGrant.setResource(resource);
groupGrant.setResourceId(ANY);
for (Permission permission : perms) {
groupGrant.addPermission(permission);
}
groupGrant.setGroupId(groupId);
authorizationService.saveAuthorization(groupGrant);
}
protected void userGrant(String userId, Resource resource, Permission... perms) {
AuthorizationService authorizationService = engine.getAuthorizationService();
Authorization groupGrant = authorizationService.createNewAuthorization(AUTH_TYPE_GRANT);
groupGrant.setResource(resource);
groupGrant.setResourceId(ANY);
for (Permission permission : perms) {
groupGrant.addPermission(permission);
}
groupGrant.setUserId(userId);
authorizationService.saveAuthorization(groupGrant);
}
}
| {
"pile_set_name": "Github"
} |
---------------------------------------------------------------------
winPenPack Project § X-Software collection
Copyright © 2005-2013 Danilo Leggieri and winPenPack Development Team
---------------------------------------------------------------------
http://www.winpenpack.com
[email protected]
winPenPack License Agreement:
http://www.winpenpack.com/main/page.php?5
=======================================================
Crediti e Ringraziamenti (ultima revisione: 10.04.2011)
=======================================================
NOTA: se qualcuno ritiene di dover essere incluso in questo
elenco, invii una mail a [email protected]
------
Indice
------
1. Hosting
2. Mirror e distribuzione
3. Vecchi componenti del Team e collaboratori
4. Suggerimenti e idee
5. Testing
6. Autori programmi
7. Sito Web
8. Icone e immagini
9. Tools e linguaggi di programmazione
1. Hosting
----------
Il progetto winPenPack è ospitato anche su SourceForge
(http://sourceforge.net/projects/winpenpack/)
2. Mirror e distribuzione
-------------------------
SourceForge (http://sourceforge.net/projects/winpenpack/)
Marvho.com (http://www.marvho.com)
Uncle Dan’s Corner (http://www.uncledan.it/)
3. Vecchi componenti del Team e collaboratori
---------------------------------------------
Roberto Angius (Roan)
Gaspare Grana (grangas)
Michele R. (Moticanus)
Gabriele Tittonel (tittoproject)
Massimo D'Angelo (icemax)
Umberto Mascia (PortableUmbo)
Luca Zoboli (_zulu)
Matteo Salvi (El Salvador)
Ciro Iorio (Alchimista)
Simone Grassini (Simongr)
4. Suggerimenti e idee
----------------------
Un grande ringraziamento a tutti gli utenti di winPenPack,
a chi collabora e ha collaborato in passato allo sviluppo
del progetto.
5. Testing
----------
Un grande ringraziamento a tutti gli utenti per l'attività
di testing.
6. Autori programmi
-------------------
Un grande ringraziamento a tutti gli autori dei programmi
inclusi in winPenPack.
7. Sito Web
-----------
e107 website system (e107.org, http://www.e107.org)
e107Italia (traduzione di e107, http://www.e107italia.org)
8. Icone e immagini
-------------------
Lamberto Tedaldi (Usbix, la mascotte di winPenPack,
http://www.officinepixel.com)
Alexandre Moore (icona della pendrive di winPenPack
e altre immagini utilizzate per la grafica del sito,
http://sa-ki.deviantart.com)
David Vignoni (tema "Nuvola", http://www.icon-king.com)
Gli autori delle immagini pubblicate sotto licenza open source
(GPL/LGPL, etc..) su Iconlet (http://iconlet.com/), Wikipedia
(http://wikipedia.org/), Open Clip Art Library
(http://openclipart.org/) ed altri siti simili, utilizzate per
la grafica del sito e gli splash screen degli X-Software.
Per maggiori dettagli leggere le note supplementari su marchi e
copyright (http://www.winpenpack.com/main/page.php?5#infringement).
9. Tools e linguaggi di programmazione
--------------------------------------
Autoit3 (linguaggio utilizzato per i launchers,
http://www.autoitscript.com)
Jordan Russell (setup di winPenPack creato con Innosetup,
http://www.jrsoftware.org) | {
"pile_set_name": "Github"
} |
#
# _____ _ _____
# / ____| (_) | __ \
# | | __ ___ _ __ _ ___ _ _ ___| |__) | __ ___
# | | |_ |/ _ \ '_ \| / __| | | / __| ___/ '__/ _ \
# | |__| | __/ | | | \__ \ |_| \__ \ | | | | (_) |
# \_____|\___|_| |_|_|___/\__, |___/_| |_| \___/
# __/ |
# |___/
#
#
#
#Genisys高级配置文件
#配置文件版本
config:
version: 28
level:
#设置是否变换天气
weather: true
#随机天气持续时长最小值,最大值
weather-random-duration-min: 6000
weather-random-duration-max: 12000
#随机闪电间隔,默认10秒,0 = 禁用
lightning-time: 200
#是否启用闪电击中着火
lightning-fire: false
#是否启用火焰蔓延
fire-spread: false
player:
#是否打开饥饿
hunger: true
#是否打开经验系统
experience: true
#是否开启死亡不掉落
keep-inventory: false
#是否开启切换模式自动清除背包
auto-clear-inventory: true
#是否开启死亡经验不掉落
keep-experience: false
#如果玩家进入游戏时崩溃, 请设置低于10的值. 禁用 = -1
chunk-radius: -1
developer:
#是否允许服务器加载文件夹插件(源码)
#建议关闭
folder-plugin-loader: true
#是否允许服务器加载不兼容的API插件
#建议关闭
load-incompatible-api: true
nether:
#是否允许地狱,打开此选项会自动生成地狱地图
allow-nether: true
#地狱地图名
level-name: "nether"
ender:
#是否允许末地,打开此选项会自动生成下界地图
allow-ender: true
#末地地图名
level-name: "ender"
server:
#是否允许生成铁傀儡
allow-iron-golem: false
#是否允许生成雪傀儡
allow-snow-golem: false
#是否禁用server.log
disable-log: false
#是否启用反飞行作弊
anti-fly: true
#是否启用异步方式发送区块
async-chunk-request: true
#玩家进出服务器消息提醒方式。0为Message,1为Tip,2为Popup
player-msg-type: 0
login-msg: "§3@player 加入了游戏"
logout-msg: "§3@player 退出了游戏"
#是否限制创造某些功能(禁止丢物品, 禁止操作箱子等等)
limited-creative: false
#是否开启方块破坏粒子
destroy-block-particle: true
#是否允许喷溅型药水
allow-splash-potion: true
#是否启用高级指令选择器
advanced-command-selector: false
#是否加载ResourcePackManager
enable-resource: false
#是否开启海绵的吸水功能
absorb-water: false
enchantment:
#是否允许使用铁砧
enable-anvil: true
#是否允许使用附魔台
enable-enchanting-table: true
#是否启用计算附魔等级(计算书架数量),可能造成服务器延迟
#如果不启用本项, 附魔等级将在0-15间随机选取
count-bookshelf: false
redstone:
##############################
#######是否开启红石系统#######
##############################
#如果不改为true将无法使用红石#
##############################
enable: false
#是否允许频率脉冲
frequency-pulse: false
#设置脉冲频率, 默认: 1s
pulse-frequency: 1
dserver:
#多服统统一人数
enable: false
#Query自动更新
query-auto-update: false
#Query周期更新
query-tick-update: true
#Motd最大人数,0为默认
motd-max-players: 0
#Query最大人数,0为默认
query-max-players: 0
#Motd显示总人数
motd-all-players: false
#Query显示总人数
query-all-players: false
#Motd显示人数
motd-players: false
#Query显示人数
query-players: false
#更新频率,20 = 1秒
time: 40
#获取失败自动重试次数
retry-times: 3
#服务器列表,用;隔开,例如 1.example.com:19132;2.example.com:19133
server-list: ""
inventory:
#如果无法使用铁砧或附魔台,请启用本项. 将会对背包交易进行验证.
allow-cheats: false | {
"pile_set_name": "Github"
} |
#include<cstdio>
using namespace std;
char M[1000][1000];
int n,m;
bool count(int r, int c){
if(M[r][c]!='B') return false;
if(r==0 || r==n-1 || c==0 || c==m-1) return false;
if(M[r-1][c]!='B') return false;
if(M[r][c-1]!='B') return false;
if(M[r+1][c]!='B') return false;
if(M[r][c+1]!='B') return false;
return true;
}
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++) scanf("%s",M[i]);
int cont=0;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(count(i,j)) cont++;
printf("%d\n",cont);
return 0;
}
| {
"pile_set_name": "Github"
} |
<template> </template>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{0A039E0A-10A8-4980-9989-539AE529B01E}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Gimela.Rukbat.BST.DataAccess</RootNamespace>
<AssemblyName>Gimela.Rukbat.BST.DataAccess</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\..\..\..\bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
| {
"pile_set_name": "Github"
} |
/*
***************************************************************************************
* Copyright (C) 2006 EsperTech, Inc. All rights reserved. *
* http://www.espertech.com/esper *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
***************************************************************************************
*/
package com.espertech.esper.common.internal.supportunit.bean;
public interface ISupportRevisionFull {
public String getK0();
public String getP0();
public String getP1();
}
| {
"pile_set_name": "Github"
} |
//
// Modals
// --------------------------------------------------
// .modal-open - body class for killing the scroll
// .modal - container to scroll within
// .modal-dialog - positioning shell for the actual modal
// .modal-content - actual modal w/ bg and corners and shit
// Kill the scroll on the body
.modal-open {
overflow: hidden;
}
// Container that the modal scrolls within
.modal {
display: none;
overflow: hidden;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: @zindex-modal;
-webkit-overflow-scrolling: touch;
// Prevent Chrome on Windows from adding a focus outline. For details, see
// https://github.com/twbs/bootstrap/pull/10951.
outline: 0;
// When fading in the modal, animate it to slide down
&.fade .modal-dialog {
.translate(0, -25%);
.transition-transform(~"0.3s ease-out");
}
&.in .modal-dialog { .translate(0, 0) }
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
// Shell div to position the modal with bottom padding
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
// Actual modal
.modal-content {
position: relative;
background-color: @modal-content-bg;
border: 1px solid @modal-content-fallback-border-color; //old browsers fallback (ie8 etc)
border: 1px solid @modal-content-border-color;
border-radius: @border-radius-large;
.box-shadow(0 3px 9px rgba(0,0,0,.5));
background-clip: padding-box;
// Remove focus outline from opened modal
outline: 0;
}
// Modal background
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: @zindex-modal-background;
background-color: @modal-backdrop-bg;
// Fade for backdrop
&.fade { .opacity(0); }
&.in { .opacity(@modal-backdrop-opacity); }
}
// Modal header
// Top section of the modal w/ title and dismiss
.modal-header {
padding: @modal-title-padding;
border-bottom: 1px solid @modal-header-border-color;
&:extend(.clearfix all);
}
// Close icon
.modal-header .close {
margin-top: -2px;
}
// Title text within header
.modal-title {
margin: 0;
line-height: @modal-title-line-height;
}
// Modal body
// Where all modal content resides (sibling of .modal-header and .modal-footer)
.modal-body {
position: relative;
padding: @modal-inner-padding;
}
// Footer (for actions)
.modal-footer {
padding: @modal-inner-padding;
text-align: right; // right align buttons
border-top: 1px solid @modal-footer-border-color;
&:extend(.clearfix all); // clear it in case folks use .pull-* classes on buttons
// Properly space out buttons
.btn + .btn {
margin-left: 5px;
margin-bottom: 0; // account for input[type="submit"] which gets the bottom margin like all other inputs
}
// but override that for button groups
.btn-group .btn + .btn {
margin-left: -1px;
}
// and override it for block buttons as well
.btn-block + .btn-block {
margin-left: 0;
}
}
// Measure scrollbar width for padding body during modal show/hide
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
// Scale up the modal
@media (min-width: @screen-sm-min) {
// Automatically set modal's width for larger viewports
.modal-dialog {
width: @modal-md;
margin: 30px auto;
}
.modal-content {
.box-shadow(0 5px 15px rgba(0,0,0,.5));
}
// Modal sizes
.modal-sm { width: @modal-sm; }
}
@media (min-width: @screen-md-min) {
.modal-lg { width: @modal-lg; }
}
| {
"pile_set_name": "Github"
} |
# Autogenerated by fastlane
#
# Ensure this file is checked in to source control!
gem 'fastlane-plugin-versioning'
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
This is an auto-generated file. Do not edit!
==============================================================================*/
namespace boost { namespace fusion { namespace detail
{
template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29>
struct list_to_cons
{
typedef T0 head_type;
typedef list_to_cons<
T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29, void_>
tail_list_to_cons;
typedef typename tail_list_to_cons::type tail_type;
typedef cons<head_type, tail_type> type;
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0)
{
return type(arg0
);
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1)
{
return type(arg0
, tail_list_to_cons::call(arg1));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21 , typename detail::call_param<T22 >::type arg22)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21 , arg22));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21 , typename detail::call_param<T22 >::type arg22 , typename detail::call_param<T23 >::type arg23)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21 , arg22 , arg23));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21 , typename detail::call_param<T22 >::type arg22 , typename detail::call_param<T23 >::type arg23 , typename detail::call_param<T24 >::type arg24)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21 , arg22 , arg23 , arg24));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21 , typename detail::call_param<T22 >::type arg22 , typename detail::call_param<T23 >::type arg23 , typename detail::call_param<T24 >::type arg24 , typename detail::call_param<T25 >::type arg25)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21 , arg22 , arg23 , arg24 , arg25));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21 , typename detail::call_param<T22 >::type arg22 , typename detail::call_param<T23 >::type arg23 , typename detail::call_param<T24 >::type arg24 , typename detail::call_param<T25 >::type arg25 , typename detail::call_param<T26 >::type arg26)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21 , arg22 , arg23 , arg24 , arg25 , arg26));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21 , typename detail::call_param<T22 >::type arg22 , typename detail::call_param<T23 >::type arg23 , typename detail::call_param<T24 >::type arg24 , typename detail::call_param<T25 >::type arg25 , typename detail::call_param<T26 >::type arg26 , typename detail::call_param<T27 >::type arg27)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21 , arg22 , arg23 , arg24 , arg25 , arg26 , arg27));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21 , typename detail::call_param<T22 >::type arg22 , typename detail::call_param<T23 >::type arg23 , typename detail::call_param<T24 >::type arg24 , typename detail::call_param<T25 >::type arg25 , typename detail::call_param<T26 >::type arg26 , typename detail::call_param<T27 >::type arg27 , typename detail::call_param<T28 >::type arg28)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21 , arg22 , arg23 , arg24 , arg25 , arg26 , arg27 , arg28));
}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(typename detail::call_param<T0 >::type arg0 , typename detail::call_param<T1 >::type arg1 , typename detail::call_param<T2 >::type arg2 , typename detail::call_param<T3 >::type arg3 , typename detail::call_param<T4 >::type arg4 , typename detail::call_param<T5 >::type arg5 , typename detail::call_param<T6 >::type arg6 , typename detail::call_param<T7 >::type arg7 , typename detail::call_param<T8 >::type arg8 , typename detail::call_param<T9 >::type arg9 , typename detail::call_param<T10 >::type arg10 , typename detail::call_param<T11 >::type arg11 , typename detail::call_param<T12 >::type arg12 , typename detail::call_param<T13 >::type arg13 , typename detail::call_param<T14 >::type arg14 , typename detail::call_param<T15 >::type arg15 , typename detail::call_param<T16 >::type arg16 , typename detail::call_param<T17 >::type arg17 , typename detail::call_param<T18 >::type arg18 , typename detail::call_param<T19 >::type arg19 , typename detail::call_param<T20 >::type arg20 , typename detail::call_param<T21 >::type arg21 , typename detail::call_param<T22 >::type arg22 , typename detail::call_param<T23 >::type arg23 , typename detail::call_param<T24 >::type arg24 , typename detail::call_param<T25 >::type arg25 , typename detail::call_param<T26 >::type arg26 , typename detail::call_param<T27 >::type arg27 , typename detail::call_param<T28 >::type arg28 , typename detail::call_param<T29 >::type arg29)
{
return type(arg0
, tail_list_to_cons::call(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9 , arg10 , arg11 , arg12 , arg13 , arg14 , arg15 , arg16 , arg17 , arg18 , arg19 , arg20 , arg21 , arg22 , arg23 , arg24 , arg25 , arg26 , arg27 , arg28 , arg29));
}
};
template <>
struct list_to_cons<void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_>
{
typedef nil_ type;
};
}}}
| {
"pile_set_name": "Github"
} |
{
"dashboards": [
{
"_id": { "$oid": "5c7fc3f9f38ed741ac154697" },
"creator_user_id": "admin",
"description": "Hey!",
"created_at": { "$date": "2019-03-06T12:58:33.610Z" },
"positions": {
"da111daa-0d0a-47b9-98ed-8b8aa8a4f575": {
"width": 2,
"col": 5,
"row": 5,
"height": 2
},
"40c9cf4e-0956-4dc1-9ccd-83868fa83277": {
"width": 6,
"col": 7,
"row": 4,
"height": 3
},
"a8eadf94-6494-4271-8c0e-3c8d08e65623": {
"width": 6,
"col": 7,
"row": 7,
"height": 5
},
"6f2cc355-bcbb-4b3f-be01-bfba299aa51a": {
"width": 3,
"col": 1,
"row": 7,
"height": 5
},
"9b55d975-a5d4-4df6-8b2e-6fc7b48d52c3": {
"width": 4,
"col": 1,
"row": 14,
"height": 2
},
"5020d62d-24a0-4b0c-8819-78e668cc2428": {
"width": 4,
"col": 1,
"row": 1,
"height": 2
},
"91b37752-e3a8-4274-910f-3d66d19f1028": {
"width": 4,
"col": 1,
"row": 12,
"height": 2
},
"05b03c7b-fe23-4789-a1c8-a38a583d3ba6": {
"width": 2,
"col": 5,
"row": 1,
"height": 2
},
"76b7f7e1-76ac-486b-894b-bc31bf4808f1": {
"width": 3,
"col": 4,
"row": 7,
"height": 5
},
"10c1b3f9-6b34-4b34-9457-892d12b84151": {
"width": 2,
"col": 5,
"row": 3,
"height": 2
},
"4a192616-51d3-474e-9e18-a680f2577769": {
"width": 4,
"col": 1,
"row": 5,
"height": 2
},
"e9efdfaf-f7be-47ca-97fe-871c05a24d3c": {
"width": 4,
"col": 1,
"row": 3,
"height": 2
},
"2afb1838-24ee-489f-929f-ef7d47485021": {
"width": 6,
"col": 7,
"row": 1,
"height": 3
},
"f2e76256-0379-483e-8622-8efd661ca939": {
"width": 23,
"col": 8,
"row": 8,
"height": 42
}
},
"title": "Sample Dashboard",
"widgets": [
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "KPI",
"id": "a8eadf94-6494-4271-8c0e-3c8d08e65623",
"type": "FIELD_CHART",
"config": {
"valuetype": "total",
"renderer": "line",
"interpolation": "linear",
"timerange": {
"type": "relative",
"range": 300
},
"rangeType": "relative",
"field": "nf_bytes",
"query": "",
"interval": "minute",
"relative": 300
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Field graph",
"id": "40c9cf4e-0956-4dc1-9ccd-83868fa83277",
"type": "FIELD_CHART",
"config": {
"valuetype": "total",
"renderer": "line",
"interpolation": "linear",
"timerange": {
"type": "relative",
"range": 300
},
"rangeType": "relative",
"field": "nf_bytes",
"query": "",
"interval": "minute",
"relative": 300
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Search result graph",
"id": "e9efdfaf-f7be-47ca-97fe-871c05a24d3c",
"type": "SEARCH_RESULT_CHART",
"config": {
"interval": "minute",
"timerange": {
"type": "relative",
"range": 28800
},
"query": ""
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Important!",
"id": "5020d62d-24a0-4b0c-8819-78e668cc2428",
"type": "FIELD_CHART",
"config": {
"valuetype": "total",
"renderer": "line",
"interpolation": "linear",
"timerange": {
"type": "relative",
"range": 28800
},
"rangeType": "relative",
"field": "nf_bytes",
"query": "",
"interval": "minute",
"relative": 28800
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Search result count",
"id": "05b03c7b-fe23-4789-a1c8-a38a583d3ba6",
"type": "SEARCH_RESULT_COUNT",
"config": {
"timerange": {
"type": "relative",
"range": 300
},
"lower_is_better": true,
"trend": true,
"query": ""
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Quick values",
"id": "6f2cc355-bcbb-4b3f-be01-bfba299aa51a",
"type": "QUICKVALUES",
"config": {
"timerange": {
"type": "relative",
"range": 300
},
"field": "facility",
"query": "",
"show_data_table": true,
"limit": 5,
"show_pie_chart": true,
"sort_order": "desc",
"stacked_fields": "",
"data_table_limit": 50
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Statistical value",
"id": "10c1b3f9-6b34-4b34-9457-892d12b84151",
"type": "STATS_COUNT",
"config": {
"timerange": {
"type": "relative",
"range": 300
},
"field": "nf_src_address_geolocation",
"trend": false,
"query": "",
"stats_function": "cardinality",
"lower_is_better": false
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Search result graph",
"id": "2afb1838-24ee-489f-929f-ef7d47485021",
"type": "SEARCH_RESULT_CHART",
"config": {
"interval": "minute",
"timerange": {
"type": "relative",
"range": 300
},
"query": ""
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "World Map Example",
"id": "76b7f7e1-76ac-486b-894b-bc31bf4808f1",
"type": "org.graylog.plugins.map.widget.strategy.MapWidgetStrategy",
"config": {
"timerange": {
"type": "relative",
"range": 300
},
"field": "nf_dst_address_geolocation",
"stream_id": "5c2e07eeba33a9681ad6070a",
"query": ""
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Some Statistical values",
"id": "da111daa-0d0a-47b9-98ed-8b8aa8a4f575",
"type": "STATS_COUNT",
"config": {
"timerange": {
"type": "relative",
"range": 300
},
"field": "nf_proto",
"stream_id": "5c2e07eeba33a9681ad6070a",
"trend": true,
"query": "",
"stats_function": "cardinality",
"lower_is_better": true
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Field Chart with absolute time range",
"id": "9b55d975-a5d4-4df6-8b2e-6fc7b48d52c3",
"type": "FIELD_CHART",
"config": {
"valuetype": "count",
"renderer": "bar",
"interpolation": "linear",
"timerange": {
"from": { "$date": "2019-11-25T00:00:00.000Z" },
"to": { "$date": "2019-11-26T00:00:00.000Z" },
"type": "absolute"
},
"rangeType": "absolute",
"field": "nf_bytes",
"query": "",
"interval": "minute",
"from": "2019-11-25T00:00:00.000Z",
"to": "2019-11-26T00:00:00.000Z"
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Field chart with keyword time range",
"id": "91b37752-e3a8-4274-910f-3d66d19f1028",
"type": "FIELD_CHART",
"config": {
"valuetype": "count",
"renderer": "bar",
"interpolation": "linear",
"timerange": {
"type": "keyword",
"keyword": "yesterday"
},
"rangeType": "keyword",
"field": "nf_bytes",
"query": "",
"interval": "minute",
"keyword": "yesterday"
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Quick values Histogram",
"id": "4a192616-51d3-474e-9e18-a680f2577769",
"type": "QUICKVALUES_HISTOGRAM",
"config": {
"timerange": {
"type": "relative",
"range": 300
},
"field": "facility",
"query": "",
"limit": 5,
"interval": "hour",
"sort_order": "desc",
"stacked_fields": ""
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Stacked Field graph",
"id": "f6e9d960-9cc8-4d16-b3c8-770501b2709f",
"type": "STACKED_CHART",
"config": {
"interval": "minute",
"timerange": {
"type": "relative",
"range": 300
},
"renderer": "bar",
"interpolation": "linear",
"series": [
{
"query": "",
"field": "dns_client",
"statistical_function": "count"
},
{
"query": "",
"field": "nf_bytes",
"statistical_function": "count"
}
]
}
},
{
"creator_user_id": "admin",
"cache_time": 10,
"description": "Stacked graph with custom timerange & query",
"id": "d9be20a1-82d7-427b-8a2d-c7ea9cd114de",
"type": "STACKED_CHART",
"config": {
"interval": "minute",
"timerange": {
"type": "relative",
"range": 7200
},
"renderer": "bar",
"interpolation": "linear",
"series": [
{
"query": "",
"field": "dns_client",
"statistical_function": "count"
},
{
"query": "",
"field": "nf_bytes",
"statistical_function": "count"
}
]
}
}
]
}
]
}
| {
"pile_set_name": "Github"
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ProjectsComponent } from './projects.component';
describe('ProjectsComponent', () => {
let component: ProjectsComponent;
let fixture: ComponentFixture<ProjectsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ProjectsComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProjectsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| {
"pile_set_name": "Github"
} |
[/============================================================================
Boost.odeint
Copyright 2009-2012 Karsten Ahnert
Copyright 2011-2013 Mario Mulansky
Copyright 2012 Sylwester Arabas
Copyright 2013 Pascal Germroth
Use, modification and distribution is subject to the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
=============================================================================/]
[library Boost.Numeric.Odeint
[quickbook 1.5]
[id odeint]
[dirname odeint]
[authors [Ahnert, Karsten], [Mulansky, Mario]]
[copyright 2009-2015 Karsten Ahnert and Mario Mulansky]
[category math]
[purpose
Numerical integration of ordinary differential equations.
]
[license
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy
at [@http://www.boost.org/LICENSE_1_0.txt])
]
]
[include auto_index_helpers.qbk]
[def __boost_lambda
[@http://www.boost.org/doc/libs/release/libs/lambda/ Boost.Lambda]]
[def __boost_phoenix
[@http://www.boost.org/doc/libs/release/libs/phoenix/ Boost.Phoenix]]
[def __boost_operators
[@http://www.boost.org/doc/libs/release/libs/utility/operators.htm Boost.Operators]]
[def __boost_ref
[@http://www.boost.org/doc/libs/release/libs/bind/ref.html Boost.Ref]]
[def __boost_range
[@http://www.boost.org/doc/libs/release/libs/range/ Boost.Range]]
[def __boost_units
[@http://www.boost.org/doc/libs/release/libs/units/ Boost.Units]]
[def __boost_fusion
[@http://www.boost.org/doc/libs/release/libs/fusion/ Boost.Fusion]]
[def __boost_graph
[@http://www.boost.org/doc/libs/release/libs/graph/ Boost.Graph]]
[def __boost_multiprecision
[@http://www.boost.org/doc/libs/release/libs/multiprecision/ Boost.Multiprecision]]
[def __boost_mpi
[@http://www.boost.org/doc/libs/release/libs/mpi/ Boost.MPI]]
[def __thrust
[@http://code.google.com/p/thrust/ Thrust]]
[def __ublas
[@http://www.boost.org/doc/libs/release/libs/numeric/ublas/index.html Boost.uBLAS]]
[def __intel_mkl
[@http://software.intel.com/en-us/articles/intel-mkl/ Intel Math Kernel Library]]
[def __gsl
[@http://www.gsl.org GSL]]
[def __vexcl
[@https://github.com/ddemidov/vexcl VexCL]]
[def __concepts
[link boost_numeric_odeint.concepts Concepts]]
[def __system
[link boost_numeric_odeint.concepts.system System]]
[def __symplectic_system
[link boost_numeric_odeint.concepts.symplectic_system Symplectic System]]
[def __simple_symplectic_system
[link boost_numeric_odeint.concepts.simple_symplectic_system Simple Symplectic System]]
[def __implicit_system
[link boost_numeric_odeint.concepts.implicit_system Implicit System]]
[def __second_order_system
[link boost_numeric_odeint.concepts.second_order_system Second Order System]]
[def __stepper
[link boost_numeric_odeint.concepts.stepper Stepper]]
[def __error_stepper
[link boost_numeric_odeint.concepts.error_stepper Error Stepper]]
[def __controlled_stepper
[link boost_numeric_odeint.concepts.controlled_stepper Controlled Stepper]]
[def __dense_output_stepper
[link boost_numeric_odeint.concepts.dense_output_stepper Dense Output Stepper]]
[def __integrate_functions
[link boost_numeric_odeint.odeint_in_detail.integrate_functions integrate functions]]
[def __tutorial
[link boost_numeric_odeint.tutorial Tutorial]]
[def __tut_solar_system
[link boost_numeric_odeint.tutorial.solar_system Solar System]]
[def __tut_chaotic_system
[link boost_numeric_odeint.tutorial.chaotic_systems_and_lyapunov_exponents Chaotic System]]
[def __tut_harmonic_oscillator
[link boost_numeric_odeint.tutorial.harmonic_oscillator Harmonic Oscillator]]
[def __using_steppers
[link boost_numeric_odeint.odeint_in_detail.steppers.using_steppers Using steppers]]
[def __generation_functions
[link boost_numeric_odeint.odeint_in_detail.generation_functions Generation functions]]
[def __adapt_state_types
[link boost_numeric_odeint.odeint_in_detail.state_types__algebras_and_operations Adapt your own state types]]
[def __resizing_lattice_example
[link boost_numeric_odeint.tutorial.self_expanding_lattices Self expanding lattices]]
[def __odeint_stepper_table
[link boost_numeric_odeint.odeint_in_detail.steppers.stepper_overview Stepper overview]]
[def __nr_ref [link numerical_recipies \[1\] ]]
[def __hairer_1_ref [link hairer_solving_odes_1 \[2\] ]]
[def __hairer_2_ref [link hairer_solving_odes_2 \[3\] ]]
[def __hairer_geom_ref [link hairer_geometrical_numeric_integration \[4\] ]]
[def __leimkuhler_reich_ref [link leimkuhler_reich_simulating_hamiltonian_dynamics \[5\] ]]
[def __symplectic_integrator_1_ref [link symplectic_yoshida_symplectic_integrators \[6\] ]]
[def __symplectic_integrator_2_ref [link symplectic_mylachlan_symmetric_composition_mehtods \[7\] ]]
[def __fpu_scholarpedia_ref [link fpu_scholarpedia \[8\] ]]
[def __synchronization_pikovsky_ref [link synchronization_pikovsky_rosenblum \[9\] ]]
[def __alpha '''α''']
[def __Alpha '''Α''']
[def __beta '''β''']
[def __Beta '''Β''']
[def __gamma '''γ''']
[def __Gamma '''Γ''']
[def __delta '''δ''']
[def __Delta '''Δ''']
[def __epsilon '''ε''']
[def __Epsilon '''Ε''']
[def __zeta '''ζ''']
[def __Zeta '''Ζ''']
[def __eta '''η''']
[def __Eta '''Η''']
[def __theta '''θ''']
[def __Theta '''Θ''']
[def __iota '''ι''']
[def __Iota '''Ι''']
[def __kappa '''κ''']
[def __Kappa '''Κ''']
[def __lambda '''λ'''][/lower case]
[def __Lambda '''Λ'''][/upper case]
[def __mu '''μ''']
[def __Mu '''Μ''']
[def __nu '''ν''']
[def __Nu '''Ν''']
[def __xi '''ξ''']
[def __Xi '''Ξ''']
[def __omicron '''ο''']
[def __Omicron '''Ο''']
[def __pi '''π''']
[def __Pi '''Π''']
[def __rho '''ρ''']
[def __Rho '''Ρ''']
[def __sigma '''σ''']
[def __Sigma '''Σ''']
[def __tau '''τ''']
[def __Tau '''Τ''']
[def __upsilon '''υ''']
[def __Upsilon '''Υ''']
[def __phi '''φ''']
[def __Phi '''Φ''']
[def __chi '''χ''']
[def __Chi '''Χ''']
[def __psi '''ψ''']
[def __Psi '''Ψ''']
[def __Omega '''Ω''']
[def __omega '''ω''']
[def __space '''​''']
[template super[x]'''<superscript>'''[x]'''</superscript>''']
[template supl[x]'''<superscript>'''__space[x]'''</superscript>''']
[template sub[x]'''<subscript>'''[x]'''</subscript>''']
[template subl[x]'''<subscript>'''__space[x]'''</subscript>''']
[template github_link[url text]'''<ulink url="https://github.com/headmyshoulder/odeint-v2/blob/master/'''[url]'''" target="_blank">'''[text]'''</ulink>''']
[/ [template github_link[url text]'''<ulink url="../../../../../'''[url]'''" target="_blank">'''[text]'''</ulink>''']]
[include getting_started.qbk]
[include tutorial.qbk]
[include details.qbk]
[include concepts.qbk]
[include literature.qbk]
[include acknowledgements.qbk]
[xinclude reference.xml]
[section:indexes Indexes]
[named_index class_name Class Index]
[named_index function_name Function Index]
[/
[named_index typedef_name Typedef Index]
[named_index macro_name Macro Index]
]
[index]
[endsect]
[/
# Α Α Α U+0391 Greek capital letter alpha
# Β Β Β U+0392 Greek capital letter beta
# Γ Γ Γ U+0393 Greek capital letter gamma ISOgrk3
# Δ Δ Δ U+0394 Greek capital letter delta ISOgrk3
# Ε Ε Ε U+0395 Greek capital letter epsilon
# Ζ Ζ Ζ U+0396 Greek capital letter zeta
# Η Η Η U+0397 Greek capital letter eta
# Θ Θ Θ U+0398 Greek capital letter theta ISOgrk3
# Ι Ι Ι U+0399 Greek capital letter iota
# Κ Κ Κ U+039A Greek capital letter kappa
# Λ Λ Λ U+039B Greek capital letter lambda ISOgrk3
# Μ Μ Μ U+039C Greek capital letter mu
# Ν Ν Ν U+039D Greek capital letter nu
# Ξ Ξ Ξ U+039E Greek capital letter xi ISOgrk3
# Ο Ο Ο U+039F Greek capital letter omicron
# Π Π Π U+03A0 Greek capital letter pi ISOgrk3
# Ρ Ρ Ρ U+03A1 Greek capital letter rho
# Σ Σ Σ U+03A3 Greek capital letter sigma ISOgrk3
# Τ Τ Τ U+03A4 Greek capital letter tau
# Υ Υ Υ U+03A5 Greek capital letter upsilon ISOgrk3
# Φ Φ Φ U+03A6 Greek capital letter phi ISOgrk3
# Χ Χ Χ U+03A7 Greek capital letter chi
# Ψ Ψ Ψ U+03A8 Greek capital letter psi ISOgrk3
# Ω Ω Ω U+03A9 Greek capital letter omega ISOgrk3
# α α α U+03B1 Greek small letter alpha ISOgrk3
# β β β U+03B2 Greek small letter beta ISOgrk3
# γ γ γ U+03B3 Greek small letter gamma ISOgrk3
# δ δ δ U+03B4 Greek small letter delta ISOgrk3
# ε ε ε U+03B5 Greek small letter epsilon ISOgrk3
# ζ ζ ζ U+03B6 Greek small letter zeta ISOgrk3
# η η η U+03B7 Greek small letter eta ISOgrk3
# θ θ θ U+03B8 Greek small letter theta ISOgrk3
# ι ι ι U+03B9 Greek small letter iota ISOgrk3
# κ κ κ U+03BA Greek small letter kappa ISOgrk3
# λ λ λ U+03BB Greek small letter lambda ISOgrk3
# μ μ μ U+03BC Greek small letter mu ISOgrk3
# ν ν ν U+03BD Greek small letter nu ISOgrk3
# ξ ξ ξ U+03BE Greek small letter xi ISOgrk3
# ο ο ο U+03BF Greek small letter omicron New
# π π π U+03C0 Greek small letter pi ISOgrk3
# ρ ρ ρ U+03C1 Greek small letter rho ISOgrk3
# ς ς ς U+03C2 Greek small letter final sigma ISOgrk3
# σ σ σ U+03C3 Greek small letter sigma ISOgrk3
# τ τ τ U+03C4 Greek small letter tau ISOgrk3
# υ υ υ U+03C5 Greek small letter upsilon ISOgrk3
# φ φ φ U+03C6 Greek small letter phi ISOgrk3
# χ χ χ U+03C7 Greek small letter chi ISOgrk3
# ψ ψ ψ U+03C8 Greek small letter psi ISOgrk3
# ω ω ω U+03C9 Greek small letter omega ISOgrk3
# ϑ ϑ ϑ U+03D1 Greek small letter theta symbol New
# ϒ ϒ ϒ U+03D2 Greek upsilon with hook symbol New
# ϖ ϖ ϖ U+03D6 Greek pi symbol ISOgrk3
/]
| {
"pile_set_name": "Github"
} |
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "../src/sys/MixinParams.sol";
contract TestMixinParams is
MixinParams
{
bool public shouldFailAssertValidStorageParams;
/// @dev Set `shouldFailAssertValidStorageParams`
function setShouldFailAssertValidStorageParams(bool shouldFail)
external
{
shouldFailAssertValidStorageParams = shouldFail;
}
/// @dev `IStakingProxy.assertValidStorageParams()` that reverts if
/// `shouldFailAssertValidStorageParams` is true.
function assertValidStorageParams()
public
view
{
if (shouldFailAssertValidStorageParams) {
revert("ASSERT_VALID_STORAGE_PARAMS_FAILED");
}
}
}
| {
"pile_set_name": "Github"
} |
/***************************************************************************
* Copyright (C) 2009 Zachary T Welch <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef OPENOCD_HELLO_H
#define OPENOCD_HELLO_H
struct command_registration;
/**
* Export the registration for the hello command group, so it can be
* embedded in example drivers.
*/
extern const struct command_registration hello_command_handlers[];
#endif /* OPENOCD_HELLO_H */
| {
"pile_set_name": "Github"
} |
<%@ Page Language="C#" MasterPageFile="Layout.master" AutoEventWireup="true" CodeBehind="TagContainer.aspx.cs" Inherits="N2.Addons.Tagging.UI.TagContainer" %>
<%@ Import Namespace="N2.Addons.Tagging.UI"%>
<asp:Content ID="cpc" ContentPlaceHolderID="Content" runat="server">
<h1><%= CurrentPage.Title %></h1>
<ul><% foreach(N2.Addons.Tagging.Items.Tag item in CurrentPage.GetChildren()) { %>
<li><%= N2.Web.Link.To(item) %> (<%= item.ReferenceCount %>)</li>
<% } %></ul>
</asp:Content>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_name" msgid="8095131950334945205">"ಕ್ಯಾಲ್ಕುಲೇಟರ್"</string>
<string name="error_nan" msgid="4071578355972369426">"ಸಂಖ್ಯೆಯಲ್ಲ"</string>
<string name="error_syntax" msgid="6940043994468390738">"ದೋಷ"</string>
<string name="fun_cos" msgid="7312559527731358211">"cos"</string>
<string name="fun_ln" msgid="6282013842946532944">"ಇನ್"</string>
<string name="fun_log" msgid="6856905045055937519">"ಲಾ."</string>
<string name="fun_sin" msgid="7136698561875496766">"ಸೈನ್"</string>
<string name="fun_tan" msgid="9116158377794370341">"ಟ್ಯಾ"</string>
<string name="clr" msgid="3126239559646368205">"ತೆರ"</string>
<string name="del" msgid="6700172918709138470">"ಅಳಿ"</string>
<string name="desc_const_e" msgid="7752508267661034194">"ಯೂಲರ್ನ ಸಂಖ್ಯೆ"</string>
<string name="desc_const_pi" msgid="5843835548313660468">"ಪೈ"</string>
<string name="desc_dec_point" msgid="6211527612960070934">"ಬಿಂದು"</string>
<string name="desc_lparen" msgid="3319203240269597504">"ಎಡ ಆವರಣದ ವಾಕ್ಯ"</string>
<string name="desc_rparen" msgid="7629704943022422763">"ಬಲ ಆವರಣದ ವಾಕ್ಯ"</string>
<string name="desc_fun_cos" msgid="3197307754450718348">"ಕೊಸೈನ್"</string>
<string name="desc_fun_ln" msgid="4943842219071979148">"ಸ್ವಾಭಾವಿಕ ಲಾಗರಿದಮ್"</string>
<string name="desc_fun_log" msgid="6163178034661345125">"ಲಾಗರಿದಮ್"</string>
<string name="desc_fun_sin" msgid="4010564022860883142">"ಸೈನ್"</string>
<string name="desc_fun_tan" msgid="8547330421304946587">"ಸ್ಪರ್ಶರೇಖೆ"</string>
<string name="desc_op_add" msgid="1174812755738083078">"ಸಂಕಲನ"</string>
<string name="desc_op_div" msgid="8320455802423478031">"ವಿಭಾಗಿಸು"</string>
<string name="desc_op_fact" msgid="5004950609277631750">"ಅಪವರ್ತನೀಯ"</string>
<string name="desc_op_mul" msgid="978652245185868311">"ಬಾರಿ"</string>
<string name="desc_op_pow" msgid="2620877401884059447">"ಪವರ್"</string>
<string name="desc_op_sqrt" msgid="4405610392216554239">"ವರ್ಗಮೂಲ"</string>
<string name="desc_op_sub" msgid="2563060630032563021">"ವ್ಯವಕಲನ"</string>
<string name="desc_clr" msgid="8357371663749541924">"ತೆರವುಗೊಳಿಸು"</string>
<string name="desc_del" msgid="1866733601083210032">"ಅಳಿಸು"</string>
<string name="desc_eq" msgid="8068773095462472408">"ಸಮ ಚಿಹ್ನೆ"</string>
</resources>
| {
"pile_set_name": "Github"
} |
/*
* linux/sound/oss/dmasound/dmasound_paula.c
*
* Amiga `Paula' DMA Sound Driver
*
* See linux/sound/oss/dmasound/dmasound_core.c for copyright and credits
* prior to 28/01/2001
*
* 28/01/2001 [0.1] Iain Sandoe
* - added versioning
* - put in and populated the hardware_afmts field.
* [0.2] - put in SNDCTL_DSP_GETCAPS value.
* [0.3] - put in constraint on state buffer usage.
* [0.4] - put in default hard/soft settings
*/
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/soundcard.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <asm/uaccess.h>
#include <asm/setup.h>
#include <asm/amigahw.h>
#include <asm/amigaints.h>
#include <asm/machdep.h>
#include "dmasound.h"
#define DMASOUND_PAULA_REVISION 0
#define DMASOUND_PAULA_EDITION 4
#define custom amiga_custom
/*
* The minimum period for audio depends on htotal (for OCS/ECS/AGA)
* (Imported from arch/m68k/amiga/amisound.c)
*/
extern volatile u_short amiga_audio_min_period;
/*
* amiga_mksound() should be able to restore the period after beeping
* (Imported from arch/m68k/amiga/amisound.c)
*/
extern u_short amiga_audio_period;
/*
* Audio DMA masks
*/
#define AMI_AUDIO_OFF (DMAF_AUD0 | DMAF_AUD1 | DMAF_AUD2 | DMAF_AUD3)
#define AMI_AUDIO_8 (DMAF_SETCLR | DMAF_MASTER | DMAF_AUD0 | DMAF_AUD1)
#define AMI_AUDIO_14 (AMI_AUDIO_8 | DMAF_AUD2 | DMAF_AUD3)
/*
* Helper pointers for 16(14)-bit sound
*/
static int write_sq_block_size_half, write_sq_block_size_quarter;
/*** Low level stuff *********************************************************/
static void *AmiAlloc(unsigned int size, gfp_t flags);
static void AmiFree(void *obj, unsigned int size);
static int AmiIrqInit(void);
#ifdef MODULE
static void AmiIrqCleanUp(void);
#endif
static void AmiSilence(void);
static void AmiInit(void);
static int AmiSetFormat(int format);
static int AmiSetVolume(int volume);
static int AmiSetTreble(int treble);
static void AmiPlayNextFrame(int index);
static void AmiPlay(void);
static irqreturn_t AmiInterrupt(int irq, void *dummy);
#ifdef CONFIG_HEARTBEAT
/*
* Heartbeat interferes with sound since the 7 kHz low-pass filter and the
* power LED are controlled by the same line.
*/
static void (*saved_heartbeat)(int) = NULL;
static inline void disable_heartbeat(void)
{
if (mach_heartbeat) {
saved_heartbeat = mach_heartbeat;
mach_heartbeat = NULL;
}
AmiSetTreble(dmasound.treble);
}
static inline void enable_heartbeat(void)
{
if (saved_heartbeat)
mach_heartbeat = saved_heartbeat;
}
#else /* !CONFIG_HEARTBEAT */
#define disable_heartbeat() do { } while (0)
#define enable_heartbeat() do { } while (0)
#endif /* !CONFIG_HEARTBEAT */
/*** Mid level stuff *********************************************************/
static void AmiMixerInit(void);
static int AmiMixerIoctl(u_int cmd, u_long arg);
static int AmiWriteSqSetup(void);
static int AmiStateInfo(char *buffer, size_t space);
/*** Translations ************************************************************/
/* ++TeSche: radically changed for new expanding purposes...
*
* These two routines now deal with copying/expanding/translating the samples
* from user space into our buffer at the right frequency. They take care about
* how much data there's actually to read, how much buffer space there is and
* to convert samples into the right frequency/encoding. They will only work on
* complete samples so it may happen they leave some bytes in the input stream
* if the user didn't write a multiple of the current sample size. They both
* return the number of bytes they've used from both streams so you may detect
* such a situation. Luckily all programs should be able to cope with that.
*
* I think I've optimized anything as far as one can do in plain C, all
* variables should fit in registers and the loops are really short. There's
* one loop for every possible situation. Writing a more generalized and thus
* parameterized loop would only produce slower code. Feel free to optimize
* this in assembler if you like. :)
*
* I think these routines belong here because they're not yet really hardware
* independent, especially the fact that the Falcon can play 16bit samples
* only in stereo is hardcoded in both of them!
*
* ++geert: split in even more functions (one per format)
*/
/*
* Native format
*/
static ssize_t ami_ct_s8(const u_char __user *userPtr, size_t userCount,
u_char frame[], ssize_t *frameUsed, ssize_t frameLeft)
{
ssize_t count, used;
if (!dmasound.soft.stereo) {
void *p = &frame[*frameUsed];
count = min_t(unsigned long, userCount, frameLeft) & ~1;
used = count;
if (copy_from_user(p, userPtr, count))
return -EFAULT;
} else {
u_char *left = &frame[*frameUsed>>1];
u_char *right = left+write_sq_block_size_half;
count = min_t(unsigned long, userCount, frameLeft)>>1 & ~1;
used = count*2;
while (count > 0) {
if (get_user(*left++, userPtr++)
|| get_user(*right++, userPtr++))
return -EFAULT;
count--;
}
}
*frameUsed += used;
return used;
}
/*
* Copy and convert 8 bit data
*/
#define GENERATE_AMI_CT8(funcname, convsample) \
static ssize_t funcname(const u_char __user *userPtr, size_t userCount, \
u_char frame[], ssize_t *frameUsed, \
ssize_t frameLeft) \
{ \
ssize_t count, used; \
\
if (!dmasound.soft.stereo) { \
u_char *p = &frame[*frameUsed]; \
count = min_t(size_t, userCount, frameLeft) & ~1; \
used = count; \
while (count > 0) { \
u_char data; \
if (get_user(data, userPtr++)) \
return -EFAULT; \
*p++ = convsample(data); \
count--; \
} \
} else { \
u_char *left = &frame[*frameUsed>>1]; \
u_char *right = left+write_sq_block_size_half; \
count = min_t(size_t, userCount, frameLeft)>>1 & ~1; \
used = count*2; \
while (count > 0) { \
u_char data; \
if (get_user(data, userPtr++)) \
return -EFAULT; \
*left++ = convsample(data); \
if (get_user(data, userPtr++)) \
return -EFAULT; \
*right++ = convsample(data); \
count--; \
} \
} \
*frameUsed += used; \
return used; \
}
#define AMI_CT_ULAW(x) (dmasound_ulaw2dma8[(x)])
#define AMI_CT_ALAW(x) (dmasound_alaw2dma8[(x)])
#define AMI_CT_U8(x) ((x) ^ 0x80)
GENERATE_AMI_CT8(ami_ct_ulaw, AMI_CT_ULAW)
GENERATE_AMI_CT8(ami_ct_alaw, AMI_CT_ALAW)
GENERATE_AMI_CT8(ami_ct_u8, AMI_CT_U8)
/*
* Copy and convert 16 bit data
*/
#define GENERATE_AMI_CT_16(funcname, convsample) \
static ssize_t funcname(const u_char __user *userPtr, size_t userCount, \
u_char frame[], ssize_t *frameUsed, \
ssize_t frameLeft) \
{ \
const u_short __user *ptr = (const u_short __user *)userPtr; \
ssize_t count, used; \
u_short data; \
\
if (!dmasound.soft.stereo) { \
u_char *high = &frame[*frameUsed>>1]; \
u_char *low = high+write_sq_block_size_half; \
count = min_t(size_t, userCount, frameLeft)>>1 & ~1; \
used = count*2; \
while (count > 0) { \
if (get_user(data, ptr++)) \
return -EFAULT; \
data = convsample(data); \
*high++ = data>>8; \
*low++ = (data>>2) & 0x3f; \
count--; \
} \
} else { \
u_char *lefth = &frame[*frameUsed>>2]; \
u_char *leftl = lefth+write_sq_block_size_quarter; \
u_char *righth = lefth+write_sq_block_size_half; \
u_char *rightl = righth+write_sq_block_size_quarter; \
count = min_t(size_t, userCount, frameLeft)>>2 & ~1; \
used = count*4; \
while (count > 0) { \
if (get_user(data, ptr++)) \
return -EFAULT; \
data = convsample(data); \
*lefth++ = data>>8; \
*leftl++ = (data>>2) & 0x3f; \
if (get_user(data, ptr++)) \
return -EFAULT; \
data = convsample(data); \
*righth++ = data>>8; \
*rightl++ = (data>>2) & 0x3f; \
count--; \
} \
} \
*frameUsed += used; \
return used; \
}
#define AMI_CT_S16BE(x) (x)
#define AMI_CT_U16BE(x) ((x) ^ 0x8000)
#define AMI_CT_S16LE(x) (le2be16((x)))
#define AMI_CT_U16LE(x) (le2be16((x)) ^ 0x8000)
GENERATE_AMI_CT_16(ami_ct_s16be, AMI_CT_S16BE)
GENERATE_AMI_CT_16(ami_ct_u16be, AMI_CT_U16BE)
GENERATE_AMI_CT_16(ami_ct_s16le, AMI_CT_S16LE)
GENERATE_AMI_CT_16(ami_ct_u16le, AMI_CT_U16LE)
static TRANS transAmiga = {
.ct_ulaw = ami_ct_ulaw,
.ct_alaw = ami_ct_alaw,
.ct_s8 = ami_ct_s8,
.ct_u8 = ami_ct_u8,
.ct_s16be = ami_ct_s16be,
.ct_u16be = ami_ct_u16be,
.ct_s16le = ami_ct_s16le,
.ct_u16le = ami_ct_u16le,
};
/*** Low level stuff *********************************************************/
static inline void StopDMA(void)
{
custom.aud[0].audvol = custom.aud[1].audvol = 0;
custom.aud[2].audvol = custom.aud[3].audvol = 0;
custom.dmacon = AMI_AUDIO_OFF;
enable_heartbeat();
}
static void *AmiAlloc(unsigned int size, gfp_t flags)
{
return amiga_chip_alloc((long)size, "dmasound [Paula]");
}
static void AmiFree(void *obj, unsigned int size)
{
amiga_chip_free (obj);
}
static int __init AmiIrqInit(void)
{
/* turn off DMA for audio channels */
StopDMA();
/* Register interrupt handler. */
if (request_irq(IRQ_AMIGA_AUD0, AmiInterrupt, 0, "DMA sound",
AmiInterrupt))
return 0;
return 1;
}
#ifdef MODULE
static void AmiIrqCleanUp(void)
{
/* turn off DMA for audio channels */
StopDMA();
/* release the interrupt */
free_irq(IRQ_AMIGA_AUD0, AmiInterrupt);
}
#endif /* MODULE */
static void AmiSilence(void)
{
/* turn off DMA for audio channels */
StopDMA();
}
static void AmiInit(void)
{
int period, i;
AmiSilence();
if (dmasound.soft.speed)
period = amiga_colorclock/dmasound.soft.speed-1;
else
period = amiga_audio_min_period;
dmasound.hard = dmasound.soft;
dmasound.trans_write = &transAmiga;
if (period < amiga_audio_min_period) {
/* we would need to squeeze the sound, but we won't do that */
period = amiga_audio_min_period;
} else if (period > 65535) {
period = 65535;
}
dmasound.hard.speed = amiga_colorclock/(period+1);
for (i = 0; i < 4; i++)
custom.aud[i].audper = period;
amiga_audio_period = period;
}
static int AmiSetFormat(int format)
{
int size;
/* Amiga sound DMA supports 8bit and 16bit (pseudo 14 bit) modes */
switch (format) {
case AFMT_QUERY:
return dmasound.soft.format;
case AFMT_MU_LAW:
case AFMT_A_LAW:
case AFMT_U8:
case AFMT_S8:
size = 8;
break;
case AFMT_S16_BE:
case AFMT_U16_BE:
case AFMT_S16_LE:
case AFMT_U16_LE:
size = 16;
break;
default: /* :-) */
size = 8;
format = AFMT_S8;
}
dmasound.soft.format = format;
dmasound.soft.size = size;
if (dmasound.minDev == SND_DEV_DSP) {
dmasound.dsp.format = format;
dmasound.dsp.size = dmasound.soft.size;
}
AmiInit();
return format;
}
#define VOLUME_VOXWARE_TO_AMI(v) \
(((v) < 0) ? 0 : ((v) > 100) ? 64 : ((v) * 64)/100)
#define VOLUME_AMI_TO_VOXWARE(v) ((v)*100/64)
static int AmiSetVolume(int volume)
{
dmasound.volume_left = VOLUME_VOXWARE_TO_AMI(volume & 0xff);
custom.aud[0].audvol = dmasound.volume_left;
dmasound.volume_right = VOLUME_VOXWARE_TO_AMI((volume & 0xff00) >> 8);
custom.aud[1].audvol = dmasound.volume_right;
if (dmasound.hard.size == 16) {
if (dmasound.volume_left == 64 && dmasound.volume_right == 64) {
custom.aud[2].audvol = 1;
custom.aud[3].audvol = 1;
} else {
custom.aud[2].audvol = 0;
custom.aud[3].audvol = 0;
}
}
return VOLUME_AMI_TO_VOXWARE(dmasound.volume_left) |
(VOLUME_AMI_TO_VOXWARE(dmasound.volume_right) << 8);
}
static int AmiSetTreble(int treble)
{
dmasound.treble = treble;
if (treble < 50)
ciaa.pra &= ~0x02;
else
ciaa.pra |= 0x02;
return treble;
}
#define AMI_PLAY_LOADED 1
#define AMI_PLAY_PLAYING 2
#define AMI_PLAY_MASK 3
static void AmiPlayNextFrame(int index)
{
u_char *start, *ch0, *ch1, *ch2, *ch3;
u_long size;
/* used by AmiPlay() if all doubts whether there really is something
* to be played are already wiped out.
*/
start = write_sq.buffers[write_sq.front];
size = (write_sq.count == index ? write_sq.rear_size
: write_sq.block_size)>>1;
if (dmasound.hard.stereo) {
ch0 = start;
ch1 = start+write_sq_block_size_half;
size >>= 1;
} else {
ch0 = start;
ch1 = start;
}
disable_heartbeat();
custom.aud[0].audvol = dmasound.volume_left;
custom.aud[1].audvol = dmasound.volume_right;
if (dmasound.hard.size == 8) {
custom.aud[0].audlc = (u_short *)ZTWO_PADDR(ch0);
custom.aud[0].audlen = size;
custom.aud[1].audlc = (u_short *)ZTWO_PADDR(ch1);
custom.aud[1].audlen = size;
custom.dmacon = AMI_AUDIO_8;
} else {
size >>= 1;
custom.aud[0].audlc = (u_short *)ZTWO_PADDR(ch0);
custom.aud[0].audlen = size;
custom.aud[1].audlc = (u_short *)ZTWO_PADDR(ch1);
custom.aud[1].audlen = size;
if (dmasound.volume_left == 64 && dmasound.volume_right == 64) {
/* We can play pseudo 14-bit only with the maximum volume */
ch3 = ch0+write_sq_block_size_quarter;
ch2 = ch1+write_sq_block_size_quarter;
custom.aud[2].audvol = 1; /* we are being affected by the beeps */
custom.aud[3].audvol = 1; /* restoring volume here helps a bit */
custom.aud[2].audlc = (u_short *)ZTWO_PADDR(ch2);
custom.aud[2].audlen = size;
custom.aud[3].audlc = (u_short *)ZTWO_PADDR(ch3);
custom.aud[3].audlen = size;
custom.dmacon = AMI_AUDIO_14;
} else {
custom.aud[2].audvol = 0;
custom.aud[3].audvol = 0;
custom.dmacon = AMI_AUDIO_8;
}
}
write_sq.front = (write_sq.front+1) % write_sq.max_count;
write_sq.active |= AMI_PLAY_LOADED;
}
static void AmiPlay(void)
{
int minframes = 1;
custom.intena = IF_AUD0;
if (write_sq.active & AMI_PLAY_LOADED) {
/* There's already a frame loaded */
custom.intena = IF_SETCLR | IF_AUD0;
return;
}
if (write_sq.active & AMI_PLAY_PLAYING)
/* Increase threshold: frame 1 is already being played */
minframes = 2;
if (write_sq.count < minframes) {
/* Nothing to do */
custom.intena = IF_SETCLR | IF_AUD0;
return;
}
if (write_sq.count <= minframes &&
write_sq.rear_size < write_sq.block_size && !write_sq.syncing) {
/* hmmm, the only existing frame is not
* yet filled and we're not syncing?
*/
custom.intena = IF_SETCLR | IF_AUD0;
return;
}
AmiPlayNextFrame(minframes);
custom.intena = IF_SETCLR | IF_AUD0;
}
static irqreturn_t AmiInterrupt(int irq, void *dummy)
{
int minframes = 1;
custom.intena = IF_AUD0;
if (!write_sq.active) {
/* Playing was interrupted and sq_reset() has already cleared
* the sq variables, so better don't do anything here.
*/
WAKE_UP(write_sq.sync_queue);
return IRQ_HANDLED;
}
if (write_sq.active & AMI_PLAY_PLAYING) {
/* We've just finished a frame */
write_sq.count--;
WAKE_UP(write_sq.action_queue);
}
if (write_sq.active & AMI_PLAY_LOADED)
/* Increase threshold: frame 1 is already being played */
minframes = 2;
/* Shift the flags */
write_sq.active = (write_sq.active<<1) & AMI_PLAY_MASK;
if (!write_sq.active)
/* No frame is playing, disable audio DMA */
StopDMA();
custom.intena = IF_SETCLR | IF_AUD0;
if (write_sq.count >= minframes)
/* Try to play the next frame */
AmiPlay();
if (!write_sq.active)
/* Nothing to play anymore.
Wake up a process waiting for audio output to drain. */
WAKE_UP(write_sq.sync_queue);
return IRQ_HANDLED;
}
/*** Mid level stuff *********************************************************/
/*
* /dev/mixer abstraction
*/
static void __init AmiMixerInit(void)
{
dmasound.volume_left = 64;
dmasound.volume_right = 64;
custom.aud[0].audvol = dmasound.volume_left;
custom.aud[3].audvol = 1; /* For pseudo 14bit */
custom.aud[1].audvol = dmasound.volume_right;
custom.aud[2].audvol = 1; /* For pseudo 14bit */
dmasound.treble = 50;
}
static int AmiMixerIoctl(u_int cmd, u_long arg)
{
int data;
switch (cmd) {
case SOUND_MIXER_READ_DEVMASK:
return IOCTL_OUT(arg, SOUND_MASK_VOLUME | SOUND_MASK_TREBLE);
case SOUND_MIXER_READ_RECMASK:
return IOCTL_OUT(arg, 0);
case SOUND_MIXER_READ_STEREODEVS:
return IOCTL_OUT(arg, SOUND_MASK_VOLUME);
case SOUND_MIXER_READ_VOLUME:
return IOCTL_OUT(arg,
VOLUME_AMI_TO_VOXWARE(dmasound.volume_left) |
VOLUME_AMI_TO_VOXWARE(dmasound.volume_right) << 8);
case SOUND_MIXER_WRITE_VOLUME:
IOCTL_IN(arg, data);
return IOCTL_OUT(arg, dmasound_set_volume(data));
case SOUND_MIXER_READ_TREBLE:
return IOCTL_OUT(arg, dmasound.treble);
case SOUND_MIXER_WRITE_TREBLE:
IOCTL_IN(arg, data);
return IOCTL_OUT(arg, dmasound_set_treble(data));
}
return -EINVAL;
}
static int AmiWriteSqSetup(void)
{
write_sq_block_size_half = write_sq.block_size>>1;
write_sq_block_size_quarter = write_sq_block_size_half>>1;
return 0;
}
static int AmiStateInfo(char *buffer, size_t space)
{
int len = 0;
len += sprintf(buffer+len, "\tsound.volume_left = %d [0...64]\n",
dmasound.volume_left);
len += sprintf(buffer+len, "\tsound.volume_right = %d [0...64]\n",
dmasound.volume_right);
if (len >= space) {
printk(KERN_ERR "dmasound_paula: overflowed state buffer alloc.\n") ;
len = space ;
}
return len;
}
/*** Machine definitions *****************************************************/
static SETTINGS def_hard = {
.format = AFMT_S8,
.stereo = 0,
.size = 8,
.speed = 8000
} ;
static SETTINGS def_soft = {
.format = AFMT_U8,
.stereo = 0,
.size = 8,
.speed = 8000
} ;
static MACHINE machAmiga = {
.name = "Amiga",
.name2 = "AMIGA",
.owner = THIS_MODULE,
.dma_alloc = AmiAlloc,
.dma_free = AmiFree,
.irqinit = AmiIrqInit,
#ifdef MODULE
.irqcleanup = AmiIrqCleanUp,
#endif /* MODULE */
.init = AmiInit,
.silence = AmiSilence,
.setFormat = AmiSetFormat,
.setVolume = AmiSetVolume,
.setTreble = AmiSetTreble,
.play = AmiPlay,
.mixer_init = AmiMixerInit,
.mixer_ioctl = AmiMixerIoctl,
.write_sq_setup = AmiWriteSqSetup,
.state_info = AmiStateInfo,
.min_dsp_speed = 8000,
.version = ((DMASOUND_PAULA_REVISION<<8) | DMASOUND_PAULA_EDITION),
.hardware_afmts = (AFMT_S8 | AFMT_S16_BE), /* h'ware-supported formats *only* here */
.capabilities = DSP_CAP_BATCH /* As per SNDCTL_DSP_GETCAPS */
};
/*** Config & Setup **********************************************************/
static int __init amiga_audio_probe(struct platform_device *pdev)
{
dmasound.mach = machAmiga;
dmasound.mach.default_hard = def_hard ;
dmasound.mach.default_soft = def_soft ;
return dmasound_init();
}
static int __exit amiga_audio_remove(struct platform_device *pdev)
{
dmasound_deinit();
return 0;
}
static struct platform_driver amiga_audio_driver = {
.remove = __exit_p(amiga_audio_remove),
.driver = {
.name = "amiga-audio",
},
};
module_platform_driver_probe(amiga_audio_driver, amiga_audio_probe);
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:amiga-audio");
| {
"pile_set_name": "Github"
} |
// Copyright (C) Explorer++ Project
// SPDX-License-Identifier: GPL-3.0-only
// See LICENSE in the top level directory
#pragma once
#define EMPTY_STRING _T("")
#define UNUSED(x) ((void)(x))
/* TODO: Switch to this once the compiler
provides support for constexpr.
See:
http://www.reddit.com/r/programming/comments/i0gz4/chromiums_code_is_perhaps_the_most_quality_code/
http://stackoverflow.com/questions/4748083/when-should-you-use-constexpr-capability-in-c0x
*/
//template <typename T,size_t N>
//constexpr size_t SIZEOF_ARRAY(T (&)[N])
//{
// return N;
//}
template <typename T,size_t N>
char (&ArraySizeHelper(T (&array)[N]))[N];
#define SIZEOF_ARRAY(array) (sizeof(ArraySizeHelper(array)))
/* A macro to disallow the copy constructor and operator= functions
This should be used in the private: declarations for a class.
See http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml. */
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&) | {
"pile_set_name": "Github"
} |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createTypeAnnotationBasedOnTypeof;
var _generated = require("../generated");
function createTypeAnnotationBasedOnTypeof(type) {
if (type === "string") {
return (0, _generated.stringTypeAnnotation)();
} else if (type === "number") {
return (0, _generated.numberTypeAnnotation)();
} else if (type === "undefined") {
return (0, _generated.voidTypeAnnotation)();
} else if (type === "boolean") {
return (0, _generated.booleanTypeAnnotation)();
} else if (type === "function") {
return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Function"));
} else if (type === "object") {
return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Object"));
} else if (type === "symbol") {
return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Symbol"));
} else {
throw new Error("Invalid typeof value");
}
} | {
"pile_set_name": "Github"
} |
var before = require('./before');
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/
function once(func) {
return before(2, func);
}
module.exports = once;
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
GremlinConsole {
com.sun.security.auth.module.Krb5LoginModule required
doNotPrompt=true
useTicketCache=true
ticketCache="target/kdc/test-tkt.cc";
};
UserNotLoggedIn {
com.sun.security.auth.module.Krb5LoginModule required
doNotPrompt=true
principal="[email protected]"
useTicketCache=true;
};
GremlinConsole2 {
com.sun.security.auth.module.Krb5LoginModule required
doNotPrompt=true
useTicketCache=true
ticketCache="target/kdc/test-tkt2.cc";
};
| {
"pile_set_name": "Github"
} |
/*
* WPA Supplicant - Glue code to setup EAPOL and RSN modules
* Copyright (c) 2003-2008, Jouni Malinen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See README and COPYING for more details.
*/
#ifndef WPAS_GLUE_H
#define WPAS_GLUE_H
int wpa_supplicant_init_eapol(struct wpa_supplicant *wpa_s);
int wpa_supplicant_init_wpa(struct wpa_supplicant *wpa_s);
void wpa_supplicant_rsn_supp_set_config(struct wpa_supplicant *wpa_s,
struct wpa_ssid *ssid);
#endif /* WPAS_GLUE_H */
| {
"pile_set_name": "Github"
} |
/*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.messenger;
import android.util.SparseArray;
import android.util.SparseIntArray;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.io.File;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipException;
public class FileLoadOperation {
protected static class RequestInfo {
private int requestToken;
private int offset;
private TLRPC.TL_upload_file response;
private TLRPC.TL_upload_webFile responseWeb;
private TLRPC.TL_upload_cdnFile responseCdn;
}
public static class Range {
private int start;
private int end;
private Range(int s, int e) {
start = s;
end = e;
}
}
private static class PreloadRange {
private int fileOffset;
private int length;
private PreloadRange(int o, int l) {
fileOffset = o;
length = l;
}
}
private ArrayList<FileLoadOperationStream> streamListeners;
private final static int stateIdle = 0;
private final static int stateDownloading = 1;
private final static int stateFailed = 2;
private final static int stateFinished = 3;
private final static int downloadChunkSize = 1024 * 32;
private final static int downloadChunkSizeBig = 1024 * 128;
private final static int cdnChunkCheckSize = 1024 * 128;
private final static int maxDownloadRequests = 4;
private final static int maxDownloadRequestsBig = 4;
private final static int bigFileSizeFrom = 1024 * 1024;
private final static int maxCdnParts = (int) (FileLoader.MAX_FILE_SIZE / downloadChunkSizeBig);
private final static int preloadMaxBytes = 2 * 1024 * 1024;
private String fileName;
private int currentQueueType;
private SparseArray<PreloadRange> preloadedBytesRanges;
private SparseIntArray requestedPreloadedBytesRanges;
private RandomAccessFile preloadStream;
private int preloadStreamFileOffset;
private int totalPreloadedBytes;
private boolean isPreloadVideoOperation;
private boolean preloadFinished;
private File cacheFilePreload;
private boolean supportsPreloading;
private int nextPreloadDownloadOffset;
private int nextAtomOffset;
private int foundMoovSize;
private int preloadNotRequestedBytesCount;
private int moovFound;
private byte[] preloadTempBuffer = new byte[16];
private int preloadTempBufferCount;
private boolean nextPartWasPreloaded;
private ArrayList<Range> notLoadedBytesRanges;
private volatile ArrayList<Range> notLoadedBytesRangesCopy;
private ArrayList<Range> notRequestedBytesRanges;
private ArrayList<Range> notCheckedCdnRanges;
private int requestedBytesCount;
private int currentAccount;
private boolean started;
private int datacenterId;
private int initialDatacenterId;
protected TLRPC.InputFileLocation location;
private TLRPC.InputWebFileLocation webLocation;
private WebFile webFile;
private volatile int state = stateIdle;
private volatile boolean paused;
private int downloadedBytes;
private int totalBytesCount;
private int bytesCountPadding;
private int streamStartOffset;
private int streamPriorityStartOffset;
private RequestInfo priorityRequestInfo;
private FileLoadOperationDelegate delegate;
private byte[] key;
private byte[] iv;
private int currentDownloadChunkSize;
private int currentMaxDownloadRequests;
private int requestsCount;
private int renameRetryCount;
private boolean encryptFile;
private boolean allowDisordererFileSave;
private Object parentObject;
private SparseArray<TLRPC.TL_fileHash> cdnHashes;
private boolean forceBig;
private byte[] encryptKey;
private byte[] encryptIv;
private boolean isCdn;
private byte[] cdnIv;
private byte[] cdnKey;
private byte[] cdnToken;
private int cdnDatacenterId;
private boolean reuploadingCdn;
protected boolean requestingReference;
private RandomAccessFile fileReadStream;
private byte[] cdnCheckBytes;
private boolean requestingCdnOffsets;
private ArrayList<RequestInfo> requestInfos;
private ArrayList<RequestInfo> delayedRequestInfos;
private File cacheFileTemp;
private File cacheFileGzipTemp;
private File cacheFileFinal;
private File cacheIvTemp;
private File cacheFileParts;
private String ext;
private RandomAccessFile fileOutputStream;
private RandomAccessFile fiv;
private RandomAccessFile filePartsStream;
private File storePath;
private File tempPath;
private boolean isForceRequest;
private int priority;
private boolean ungzip;
private int currentType;
public interface FileLoadOperationDelegate {
void didFinishLoadingFile(FileLoadOperation operation, File finalFile);
void didFailedLoadingFile(FileLoadOperation operation, int state);
void didChangedLoadProgress(FileLoadOperation operation, long uploadedSize, long totalSize);
}
public FileLoadOperation(ImageLocation imageLocation, Object parent, String extension, int size) {
parentObject = parent;
forceBig = imageLocation.imageType == FileLoader.IMAGE_TYPE_ANIMATION;
if (imageLocation.isEncrypted()) {
location = new TLRPC.TL_inputEncryptedFileLocation();
location.id = imageLocation.location.volume_id;
location.volume_id = imageLocation.location.volume_id;
location.local_id = imageLocation.location.local_id;
location.access_hash = imageLocation.access_hash;
iv = new byte[32];
System.arraycopy(imageLocation.iv, 0, iv, 0, iv.length);
key = imageLocation.key;
} else if (imageLocation.photoPeer != null) {
location = new TLRPC.TL_inputPeerPhotoFileLocation();
location.id = imageLocation.location.volume_id;
location.volume_id = imageLocation.location.volume_id;
location.local_id = imageLocation.location.local_id;
location.big = imageLocation.photoPeerBig;
location.peer = imageLocation.photoPeer;
} else if (imageLocation.stickerSet != null) {
location = new TLRPC.TL_inputStickerSetThumb();
location.id = imageLocation.location.volume_id;
location.volume_id = imageLocation.location.volume_id;
location.local_id = imageLocation.location.local_id;
location.stickerset = imageLocation.stickerSet;
} else if (imageLocation.thumbSize != null) {
if (imageLocation.photoId != 0) {
location = new TLRPC.TL_inputPhotoFileLocation();
location.id = imageLocation.photoId;
location.volume_id = imageLocation.location.volume_id;
location.local_id = imageLocation.location.local_id;
location.access_hash = imageLocation.access_hash;
location.file_reference = imageLocation.file_reference;
location.thumb_size = imageLocation.thumbSize;
if (imageLocation.imageType == FileLoader.IMAGE_TYPE_ANIMATION) {
allowDisordererFileSave = true;
}
} else {
location = new TLRPC.TL_inputDocumentFileLocation();
location.id = imageLocation.documentId;
location.volume_id = imageLocation.location.volume_id;
location.local_id = imageLocation.location.local_id;
location.access_hash = imageLocation.access_hash;
location.file_reference = imageLocation.file_reference;
location.thumb_size = imageLocation.thumbSize;
}
if (location.file_reference == null) {
location.file_reference = new byte[0];
}
} else {
location = new TLRPC.TL_inputFileLocation();
location.volume_id = imageLocation.location.volume_id;
location.local_id = imageLocation.location.local_id;
location.secret = imageLocation.access_hash;
location.file_reference = imageLocation.file_reference;
if (location.file_reference == null) {
location.file_reference = new byte[0];
}
allowDisordererFileSave = true;
}
ungzip = imageLocation.imageType == FileLoader.IMAGE_TYPE_LOTTIE || imageLocation.imageType == FileLoader.IMAGE_TYPE_SVG;
initialDatacenterId = datacenterId = imageLocation.dc_id;
currentType = ConnectionsManager.FileTypePhoto;
totalBytesCount = size;
ext = extension != null ? extension : "jpg";
}
public FileLoadOperation(SecureDocument secureDocument) {
location = new TLRPC.TL_inputSecureFileLocation();
location.id = secureDocument.secureFile.id;
location.access_hash = secureDocument.secureFile.access_hash;
datacenterId = secureDocument.secureFile.dc_id;
totalBytesCount = secureDocument.secureFile.size;
allowDisordererFileSave = true;
currentType = ConnectionsManager.FileTypeFile;
ext = ".jpg";
}
public FileLoadOperation(int instance, WebFile webDocument) {
currentAccount = instance;
webFile = webDocument;
webLocation = webDocument.location;
totalBytesCount = webDocument.size;
initialDatacenterId = datacenterId = MessagesController.getInstance(currentAccount).webFileDatacenterId;
String defaultExt = FileLoader.getMimeTypePart(webDocument.mime_type);
if (webDocument.mime_type.startsWith("image/")) {
currentType = ConnectionsManager.FileTypePhoto;
} else if (webDocument.mime_type.equals("audio/ogg")) {
currentType = ConnectionsManager.FileTypeAudio;
} else if (webDocument.mime_type.startsWith("video/")) {
currentType = ConnectionsManager.FileTypeVideo;
} else {
currentType = ConnectionsManager.FileTypeFile;
}
allowDisordererFileSave = true;
ext = ImageLoader.getHttpUrlExtension(webDocument.url, defaultExt);
}
public FileLoadOperation(TLRPC.Document documentLocation, Object parent) {
try {
parentObject = parent;
if (documentLocation instanceof TLRPC.TL_documentEncrypted) {
location = new TLRPC.TL_inputEncryptedFileLocation();
location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash;
initialDatacenterId = datacenterId = documentLocation.dc_id;
iv = new byte[32];
System.arraycopy(documentLocation.iv, 0, iv, 0, iv.length);
key = documentLocation.key;
} else if (documentLocation instanceof TLRPC.TL_document) {
location = new TLRPC.TL_inputDocumentFileLocation();
location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash;
location.file_reference = documentLocation.file_reference;
location.thumb_size = "";
if (location.file_reference == null) {
location.file_reference = new byte[0];
}
initialDatacenterId = datacenterId = documentLocation.dc_id;
allowDisordererFileSave = true;
for (int a = 0, N = documentLocation.attributes.size(); a < N; a++) {
if (documentLocation.attributes.get(a) instanceof TLRPC.TL_documentAttributeVideo) {
supportsPreloading = true;
break;
}
}
}
ungzip = "application/x-tgsticker".equals(documentLocation.mime_type) || "application/x-tgwallpattern".equals(documentLocation.mime_type);
totalBytesCount = documentLocation.size;
if (key != null) {
int toAdd = 0;
if (totalBytesCount % 16 != 0) {
bytesCountPadding = 16 - totalBytesCount % 16;
totalBytesCount += bytesCountPadding;
}
}
ext = FileLoader.getDocumentFileName(documentLocation);
int idx;
if (ext == null || (idx = ext.lastIndexOf('.')) == -1) {
ext = "";
} else {
ext = ext.substring(idx);
}
if ("audio/ogg".equals(documentLocation.mime_type)) {
currentType = ConnectionsManager.FileTypeAudio;
} else if (FileLoader.isVideoMimeType(documentLocation.mime_type)) {
currentType = ConnectionsManager.FileTypeVideo;
} else {
currentType = ConnectionsManager.FileTypeFile;
}
if (ext.length() <= 1) {
ext = FileLoader.getExtensionByMimeType(documentLocation.mime_type);
}
} catch (Exception e) {
FileLog.e(e);
onFail(true, 0);
}
}
public void setEncryptFile(boolean value) {
encryptFile = value;
if (encryptFile) {
allowDisordererFileSave = false;
}
}
public int getDatacenterId() {
return initialDatacenterId;
}
public void setForceRequest(boolean forceRequest) {
isForceRequest = forceRequest;
}
public boolean isForceRequest() {
return isForceRequest;
}
public void setPriority(int value) {
priority = value;
}
public int getPriority() {
return priority;
}
public void setPaths(int instance, String name, int queueType, File store, File temp) {
storePath = store;
tempPath = temp;
currentAccount = instance;
fileName = name;
currentQueueType = queueType;
}
public int getQueueType() {
return currentQueueType;
}
public boolean wasStarted() {
return started && !paused;
}
public int getCurrentType() {
return currentType;
}
private void removePart(ArrayList<Range> ranges, int start, int end) {
if (ranges == null || end < start) {
return;
}
int count = ranges.size();
Range range;
boolean modified = false;
for (int a = 0; a < count; a++) {
range = ranges.get(a);
if (start == range.end) {
range.end = end;
modified = true;
break;
} else if (end == range.start) {
range.start = start;
modified = true;
break;
}
}
Collections.sort(ranges, (o1, o2) -> {
if (o1.start > o2.start) {
return 1;
} else if (o1.start < o2.start) {
return -1;
}
return 0;
});
for (int a = 0; a < ranges.size() - 1; a++) {
Range r1 = ranges.get(a);
Range r2 = ranges.get(a + 1);
if (r1.end == r2.start) {
r1.end = r2.end;
ranges.remove(a + 1);
a--;
}
}
if (!modified) {
ranges.add(new Range(start, end));
}
}
private void addPart(ArrayList<Range> ranges, int start, int end, boolean save) {
if (ranges == null || end < start) {
return;
}
boolean modified = false;
int count = ranges.size();
Range range;
for (int a = 0; a < count; a++) {
range = ranges.get(a);
if (start <= range.start) {
if (end >= range.end) {
ranges.remove(a);
modified = true;
break;
} else if (end > range.start) {
range.start = end;
modified = true;
break;
}
} else {
if (end < range.end) {
Range newRange = new Range(range.start, start);
ranges.add(0, newRange);
modified = true;
range.start = end;
break;
} else if (start < range.end) {
range.end = start;
modified = true;
break;
}
}
}
if (save) {
if (modified) {
try {
filePartsStream.seek(0);
count = ranges.size();
filePartsStream.writeInt(count);
for (int a = 0; a < count; a++) {
range = ranges.get(a);
filePartsStream.writeInt(range.start);
filePartsStream.writeInt(range.end);
}
} catch (Exception e) {
FileLog.e(e);
}
if (streamListeners != null) {
count = streamListeners.size();
for (int a = 0; a < count; a++) {
streamListeners.get(a).newDataAvailable();
}
}
} else {
if (BuildVars.LOGS_ENABLED) {
FileLog.e(cacheFileFinal + " downloaded duplicate file part " + start + " - " + end);
}
}
}
}
protected File getCacheFileFinal() {
return cacheFileFinal;
}
protected File getCurrentFile() {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final File[] result = new File[1];
Utilities.stageQueue.postRunnable(() -> {
if (state == stateFinished) {
result[0] = cacheFileFinal;
} else {
result[0] = cacheFileTemp;
}
countDownLatch.countDown();
});
try {
countDownLatch.await();
} catch (Exception e) {
FileLog.e(e);
}
return result[0];
}
private int getDownloadedLengthFromOffsetInternal(ArrayList<Range> ranges, final int offset, final int length) {
if (ranges == null || state == stateFinished || ranges.isEmpty()) {
if (downloadedBytes == 0) {
return length;
} else {
return Math.min(length, Math.max(downloadedBytes - offset, 0));
}
} else {
int count = ranges.size();
Range range;
Range minRange = null;
int availableLength = length;
for (int a = 0; a < count; a++) {
range = ranges.get(a);
if (offset <= range.start && (minRange == null || range.start < minRange.start)) {
minRange = range;
}
if (range.start <= offset && range.end > offset) {
availableLength = 0;
break;
}
}
if (availableLength == 0) {
return 0;
} else if (minRange != null) {
return Math.min(length, minRange.start - offset);
} else {
return Math.min(length, Math.max(totalBytesCount - offset, 0));
}
}
}
protected float getDownloadedLengthFromOffset(final float progress) {
ArrayList<Range> ranges = notLoadedBytesRangesCopy;
if (totalBytesCount == 0 || ranges == null) {
return 0;
}
return progress + getDownloadedLengthFromOffsetInternal(ranges, (int) (totalBytesCount * progress), totalBytesCount) / (float) totalBytesCount;
}
protected int[] getDownloadedLengthFromOffset(final int offset, final int length) {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final int[] result = new int[2];
Utilities.stageQueue.postRunnable(() -> {
result[0] = getDownloadedLengthFromOffsetInternal(notLoadedBytesRanges, offset, length);
if (state == stateFinished) {
result[1] = 1;
}
countDownLatch.countDown();
});
try {
countDownLatch.await();
} catch (Exception ignore) {
}
return result;
}
public String getFileName() {
return fileName;
}
protected void removeStreamListener(final FileLoadOperationStream operation) {
Utilities.stageQueue.postRunnable(() -> {
if (streamListeners == null) {
return;
}
streamListeners.remove(operation);
});
}
private void copyNotLoadedRanges() {
if (notLoadedBytesRanges == null) {
return;
}
notLoadedBytesRangesCopy = new ArrayList<>(notLoadedBytesRanges);
}
public void pause() {
if (state != stateDownloading) {
return;
}
paused = true;
}
public boolean start() {
return start(null, 0, false);
}
public boolean start(final FileLoadOperationStream stream, final int streamOffset, final boolean steamPriority) {
if (currentDownloadChunkSize == 0) {
currentDownloadChunkSize = totalBytesCount >= bigFileSizeFrom || forceBig ? downloadChunkSizeBig : downloadChunkSize;
currentMaxDownloadRequests = totalBytesCount >= bigFileSizeFrom || forceBig ? maxDownloadRequestsBig : maxDownloadRequests;
}
final boolean alreadyStarted = state != stateIdle;
final boolean wasPaused = paused;
paused = false;
if (stream != null) {
Utilities.stageQueue.postRunnable(() -> {
if (streamListeners == null) {
streamListeners = new ArrayList<>();
}
if (steamPriority) {
int offset = streamOffset / currentDownloadChunkSize * currentDownloadChunkSize;
if (priorityRequestInfo != null && priorityRequestInfo.offset != offset) {
requestInfos.remove(priorityRequestInfo);
requestedBytesCount -= currentDownloadChunkSize;
removePart(notRequestedBytesRanges, priorityRequestInfo.offset, priorityRequestInfo.offset + currentDownloadChunkSize);
if (priorityRequestInfo.requestToken != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(priorityRequestInfo.requestToken, true);
requestsCount--;
}
if (BuildVars.DEBUG_VERSION) {
FileLog.d("frame get cancel request at offset " + priorityRequestInfo.offset);
}
priorityRequestInfo = null;
}
if (priorityRequestInfo == null) {
streamPriorityStartOffset = offset;
}
} else {
streamStartOffset = streamOffset / currentDownloadChunkSize * currentDownloadChunkSize;
}
streamListeners.add(stream);
if (alreadyStarted) {
if (preloadedBytesRanges != null && getDownloadedLengthFromOffsetInternal(notLoadedBytesRanges, streamStartOffset, 1) == 0) {
if (preloadedBytesRanges.get(streamStartOffset) != null) {
nextPartWasPreloaded = true;
}
}
startDownloadRequest();
nextPartWasPreloaded = false;
}
});
} else if (wasPaused && alreadyStarted) {
Utilities.stageQueue.postRunnable(this::startDownloadRequest);
}
if (alreadyStarted) {
return wasPaused;
}
if (location == null && webLocation == null) {
onFail(true, 0);
return false;
}
streamStartOffset = streamOffset / currentDownloadChunkSize * currentDownloadChunkSize;
if (allowDisordererFileSave && totalBytesCount > 0 && totalBytesCount > currentDownloadChunkSize) {
notLoadedBytesRanges = new ArrayList<>();
notRequestedBytesRanges = new ArrayList<>();
}
String fileNameFinal;
String fileNameTemp;
String fileNameParts = null;
String fileNamePreload = null;
String fileNameIv = null;
if (webLocation != null) {
String md5 = Utilities.MD5(webFile.url);
if (encryptFile) {
fileNameTemp = md5 + ".temp.enc";
fileNameFinal = md5 + "." + ext + ".enc";
if (key != null) {
fileNameIv = md5 + ".iv.enc";
}
} else {
fileNameTemp = md5 + ".temp";
fileNameFinal = md5 + "." + ext;
if (key != null) {
fileNameIv = md5 + ".iv";
}
}
} else {
if (location.volume_id != 0 && location.local_id != 0) {
if (datacenterId == Integer.MIN_VALUE || location.volume_id == Integer.MIN_VALUE || datacenterId == 0) {
onFail(true, 0);
return false;
}
if (encryptFile) {
fileNameTemp = location.volume_id + "_" + location.local_id + ".temp.enc";
fileNameFinal = location.volume_id + "_" + location.local_id + "." + ext + ".enc";
if (key != null) {
fileNameIv = location.volume_id + "_" + location.local_id + ".iv.enc";
}
} else {
fileNameTemp = location.volume_id + "_" + location.local_id + ".temp";
fileNameFinal = location.volume_id + "_" + location.local_id + "." + ext;
if (key != null) {
fileNameIv = location.volume_id + "_" + location.local_id + ".iv";
}
if (notLoadedBytesRanges != null) {
fileNameParts = location.volume_id + "_" + location.local_id + ".pt";
}
fileNamePreload = location.volume_id + "_" + location.local_id + ".preload";
}
} else {
if (datacenterId == 0 || location.id == 0) {
onFail(true, 0);
return false;
}
if (encryptFile) {
fileNameTemp = datacenterId + "_" + location.id + ".temp.enc";
fileNameFinal = datacenterId + "_" + location.id + ext + ".enc";
if (key != null) {
fileNameIv = datacenterId + "_" + location.id + ".iv.enc";
}
} else {
fileNameTemp = datacenterId + "_" + location.id + ".temp";
fileNameFinal = datacenterId + "_" + location.id + ext;
if (key != null) {
fileNameIv = datacenterId + "_" + location.id + ".iv";
}
if (notLoadedBytesRanges != null) {
fileNameParts = datacenterId + "_" + location.id + ".pt";
}
fileNamePreload = datacenterId + "_" + location.id + ".preload";
}
}
}
requestInfos = new ArrayList<>(currentMaxDownloadRequests);
delayedRequestInfos = new ArrayList<>(currentMaxDownloadRequests - 1);
state = stateDownloading;
if (parentObject instanceof TLRPC.TL_theme) {
TLRPC.TL_theme theme = (TLRPC.TL_theme) parentObject;
cacheFileFinal = new File(ApplicationLoader.getFilesDirFixed(), "remote" + theme.id + ".attheme");
} else {
cacheFileFinal = new File(storePath, fileNameFinal);
}
boolean finalFileExist = cacheFileFinal.exists();
if (finalFileExist && (parentObject instanceof TLRPC.TL_theme || totalBytesCount != 0 && totalBytesCount != cacheFileFinal.length())) {
cacheFileFinal.delete();
finalFileExist = false;
}
if (!finalFileExist) {
cacheFileTemp = new File(tempPath, fileNameTemp);
if (ungzip) {
cacheFileGzipTemp = new File(tempPath, fileNameTemp + ".gz");
}
boolean newKeyGenerated = false;
if (encryptFile) {
File keyFile = new File(FileLoader.getInternalCacheDir(), fileNameFinal + ".key");
try {
RandomAccessFile file = new RandomAccessFile(keyFile, "rws");
long len = keyFile.length();
encryptKey = new byte[32];
encryptIv = new byte[16];
if (len > 0 && len % 48 == 0) {
file.read(encryptKey, 0, 32);
file.read(encryptIv, 0, 16);
} else {
Utilities.random.nextBytes(encryptKey);
Utilities.random.nextBytes(encryptIv);
file.write(encryptKey);
file.write(encryptIv);
newKeyGenerated = true;
}
try {
file.getChannel().close();
} catch (Exception e) {
FileLog.e(e);
}
file.close();
} catch (Exception e) {
FileLog.e(e);
}
}
boolean[] preloaded = new boolean[]{false};
if (supportsPreloading && fileNamePreload != null) {
cacheFilePreload = new File(tempPath, fileNamePreload);
boolean closeStream = false;
try {
preloadStream = new RandomAccessFile(cacheFilePreload, "rws");
long len = preloadStream.length();
int readOffset = 0;
preloadStreamFileOffset = 1;
if (len - readOffset > 1) {
preloaded[0] = preloadStream.readByte() != 0;
readOffset += 1;
while (readOffset < len) {
if (len - readOffset < 4) {
break;
}
int offset = preloadStream.readInt();
readOffset += 4;
if (len - readOffset < 4 || offset < 0 || offset > totalBytesCount) {
break;
}
int size = preloadStream.readInt();
readOffset += 4;
if (len - readOffset < size || size > currentDownloadChunkSize) {
break;
}
PreloadRange range = new PreloadRange(readOffset, size);
readOffset += size;
preloadStream.seek(readOffset);
if (len - readOffset < 12) {
break;
}
foundMoovSize = preloadStream.readInt();
if (foundMoovSize != 0) {
moovFound = nextPreloadDownloadOffset > totalBytesCount / 2 ? 2 : 1;
preloadNotRequestedBytesCount = foundMoovSize;
}
nextPreloadDownloadOffset = preloadStream.readInt();
nextAtomOffset = preloadStream.readInt();
readOffset += 12;
if (preloadedBytesRanges == null) {
preloadedBytesRanges = new SparseArray<>();
}
if (requestedPreloadedBytesRanges == null) {
requestedPreloadedBytesRanges = new SparseIntArray();
}
preloadedBytesRanges.put(offset, range);
requestedPreloadedBytesRanges.put(offset, 1);
totalPreloadedBytes += size;
preloadStreamFileOffset += 20 + size;
}
}
preloadStream.seek(preloadStreamFileOffset);
} catch (Exception e) {
FileLog.e(e);
}
if (!isPreloadVideoOperation && preloadedBytesRanges == null) {
cacheFilePreload = null;
try {
if (preloadStream != null) {
try {
preloadStream.getChannel().close();
} catch (Exception e) {
FileLog.e(e);
}
preloadStream.close();
preloadStream = null;
}
} catch (Exception e) {
FileLog.e(e);
}
}
}
if (fileNameParts != null) {
cacheFileParts = new File(tempPath, fileNameParts);
try {
filePartsStream = new RandomAccessFile(cacheFileParts, "rws");
long len = filePartsStream.length();
if (len % 8 == 4) {
len -= 4;
int count = filePartsStream.readInt();
if (count <= len / 2) {
for (int a = 0; a < count; a++) {
int start = filePartsStream.readInt();
int end = filePartsStream.readInt();
notLoadedBytesRanges.add(new Range(start, end));
notRequestedBytesRanges.add(new Range(start, end));
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
if (cacheFileTemp.exists()) {
if (newKeyGenerated) {
cacheFileTemp.delete();
} else {
long totalDownloadedLen = cacheFileTemp.length();
if (fileNameIv != null && (totalDownloadedLen % currentDownloadChunkSize) != 0) {
requestedBytesCount = downloadedBytes = 0;
} else {
requestedBytesCount = downloadedBytes = ((int) cacheFileTemp.length()) / currentDownloadChunkSize * currentDownloadChunkSize;
}
if (notLoadedBytesRanges != null && notLoadedBytesRanges.isEmpty()) {
notLoadedBytesRanges.add(new Range(downloadedBytes, totalBytesCount));
notRequestedBytesRanges.add(new Range(downloadedBytes, totalBytesCount));
}
}
} else if (notLoadedBytesRanges != null && notLoadedBytesRanges.isEmpty()) {
notLoadedBytesRanges.add(new Range(0, totalBytesCount));
notRequestedBytesRanges.add(new Range(0, totalBytesCount));
}
if (notLoadedBytesRanges != null) {
downloadedBytes = totalBytesCount;
int size = notLoadedBytesRanges.size();
Range range;
for (int a = 0; a < size; a++) {
range = notLoadedBytesRanges.get(a);
downloadedBytes -= (range.end - range.start);
}
requestedBytesCount = downloadedBytes;
}
if (BuildVars.LOGS_ENABLED) {
if (isPreloadVideoOperation) {
FileLog.d("start preloading file to temp = " + cacheFileTemp);
} else {
FileLog.d("start loading file to temp = " + cacheFileTemp + " final = " + cacheFileFinal);
}
}
if (fileNameIv != null) {
cacheIvTemp = new File(tempPath, fileNameIv);
try {
fiv = new RandomAccessFile(cacheIvTemp, "rws");
if (downloadedBytes != 0 && !newKeyGenerated) {
long len = cacheIvTemp.length();
if (len > 0 && len % 32 == 0) {
fiv.read(iv, 0, 32);
} else {
requestedBytesCount = downloadedBytes = 0;
}
}
} catch (Exception e) {
FileLog.e(e);
requestedBytesCount = downloadedBytes = 0;
}
}
if (!isPreloadVideoOperation && downloadedBytes != 0 && totalBytesCount > 0) {
copyNotLoadedRanges();
}
updateProgress();
try {
fileOutputStream = new RandomAccessFile(cacheFileTemp, "rws");
if (downloadedBytes != 0) {
fileOutputStream.seek(downloadedBytes);
}
} catch (Exception e) {
FileLog.e(e);
}
if (fileOutputStream == null) {
onFail(true, 0);
return false;
}
started = true;
Utilities.stageQueue.postRunnable(() -> {
if (totalBytesCount != 0 && (isPreloadVideoOperation && preloaded[0] || downloadedBytes == totalBytesCount)) {
try {
onFinishLoadingFile(false);
} catch (Exception e) {
onFail(true, 0);
}
} else {
startDownloadRequest();
}
});
} else {
started = true;
try {
onFinishLoadingFile(false);
} catch (Exception e) {
onFail(true, 0);
}
}
return true;
}
public void updateProgress() {
if (delegate != null && downloadedBytes != totalBytesCount && totalBytesCount > 0) {
delegate.didChangedLoadProgress(FileLoadOperation.this, downloadedBytes, totalBytesCount);
}
}
public boolean isPaused() {
return paused;
}
public void setIsPreloadVideoOperation(boolean value) {
if (isPreloadVideoOperation == value || value && totalBytesCount <= preloadMaxBytes) {
return;
}
if (!value && isPreloadVideoOperation) {
if (state == stateFinished) {
isPreloadVideoOperation = value;
state = stateIdle;
preloadFinished = false;
start();
} else if (state == stateDownloading) {
Utilities.stageQueue.postRunnable(() -> {
requestedBytesCount = 0;
clearOperaion(null, true);
isPreloadVideoOperation = value;
startDownloadRequest();
});
} else {
isPreloadVideoOperation = value;
}
} else {
isPreloadVideoOperation = value;
}
}
public boolean isPreloadVideoOperation() {
return isPreloadVideoOperation;
}
public boolean isPreloadFinished() {
return preloadFinished;
}
public void cancel() {
Utilities.stageQueue.postRunnable(() -> {
if (state == stateFinished || state == stateFailed) {
return;
}
if (requestInfos != null) {
for (int a = 0; a < requestInfos.size(); a++) {
RequestInfo requestInfo = requestInfos.get(a);
if (requestInfo.requestToken != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(requestInfo.requestToken, true);
}
}
}
onFail(false, 1);
});
}
private void cleanup() {
try {
if (fileOutputStream != null) {
try {
fileOutputStream.getChannel().close();
} catch (Exception e) {
FileLog.e(e);
}
fileOutputStream.close();
fileOutputStream = null;
}
} catch (Exception e) {
FileLog.e(e);
}
try {
if (preloadStream != null) {
try {
preloadStream.getChannel().close();
} catch (Exception e) {
FileLog.e(e);
}
preloadStream.close();
preloadStream = null;
}
} catch (Exception e) {
FileLog.e(e);
}
try {
if (fileReadStream != null) {
try {
fileReadStream.getChannel().close();
} catch (Exception e) {
FileLog.e(e);
}
fileReadStream.close();
fileReadStream = null;
}
} catch (Exception e) {
FileLog.e(e);
}
try {
if (filePartsStream != null) {
try {
filePartsStream.getChannel().close();
} catch (Exception e) {
FileLog.e(e);
}
filePartsStream.close();
filePartsStream = null;
}
} catch (Exception e) {
FileLog.e(e);
}
try {
if (fiv != null) {
fiv.close();
fiv = null;
}
} catch (Exception e) {
FileLog.e(e);
}
if (delayedRequestInfos != null) {
for (int a = 0; a < delayedRequestInfos.size(); a++) {
RequestInfo requestInfo = delayedRequestInfos.get(a);
if (requestInfo.response != null) {
requestInfo.response.disableFree = false;
requestInfo.response.freeResources();
} else if (requestInfo.responseWeb != null) {
requestInfo.responseWeb.disableFree = false;
requestInfo.responseWeb.freeResources();
} else if (requestInfo.responseCdn != null) {
requestInfo.responseCdn.disableFree = false;
requestInfo.responseCdn.freeResources();
}
}
delayedRequestInfos.clear();
}
}
private void onFinishLoadingFile(final boolean increment) {
if (state != stateDownloading) {
return;
}
state = stateFinished;
cleanup();
if (isPreloadVideoOperation) {
preloadFinished = true;
if (BuildVars.DEBUG_VERSION) {
FileLog.d("finished preloading file to " + cacheFileTemp + " loaded " + totalPreloadedBytes + " of " + totalBytesCount);
}
} else {
if (cacheIvTemp != null) {
cacheIvTemp.delete();
cacheIvTemp = null;
}
if (cacheFileParts != null) {
cacheFileParts.delete();
cacheFileParts = null;
}
if (cacheFilePreload != null) {
cacheFilePreload.delete();
cacheFilePreload = null;
}
if (cacheFileTemp != null) {
if (ungzip) {
try {
GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(cacheFileTemp));
FileLoader.copyFile(gzipInputStream, cacheFileGzipTemp, 1024 * 1024 * 2);
gzipInputStream.close();
cacheFileTemp.delete();
cacheFileTemp = cacheFileGzipTemp;
ungzip = false;
} catch (ZipException zipException) {
ungzip = false;
} catch (Throwable e) {
FileLog.e(e);
if (BuildVars.LOGS_ENABLED) {
FileLog.e("unable to ungzip temp = " + cacheFileTemp + " to final = " + cacheFileFinal);
}
}
}
if (!ungzip) {
boolean renameResult;
if (parentObject instanceof TLRPC.TL_theme) {
try {
renameResult = AndroidUtilities.copyFile(cacheFileTemp, cacheFileFinal);
} catch (Exception e) {
renameResult = false;
FileLog.e(e);
}
} else {
renameResult = cacheFileTemp.renameTo(cacheFileFinal);
}
if (!renameResult) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("unable to rename temp = " + cacheFileTemp + " to final = " + cacheFileFinal + " retry = " + renameRetryCount);
}
renameRetryCount++;
if (renameRetryCount < 3) {
state = stateDownloading;
Utilities.stageQueue.postRunnable(() -> {
try {
onFinishLoadingFile(increment);
} catch (Exception e) {
onFail(false, 0);
}
}, 200);
return;
}
cacheFileFinal = cacheFileTemp;
}
} else {
onFail(false, 0);
return;
}
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("finished downloading file to " + cacheFileFinal);
}
if (increment) {
if (currentType == ConnectionsManager.FileTypeAudio) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_AUDIOS, 1);
} else if (currentType == ConnectionsManager.FileTypeVideo) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_VIDEOS, 1);
} else if (currentType == ConnectionsManager.FileTypePhoto) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_PHOTOS, 1);
} else if (currentType == ConnectionsManager.FileTypeFile) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_FILES, 1);
}
}
}
delegate.didFinishLoadingFile(FileLoadOperation.this, cacheFileFinal);
}
private void delayRequestInfo(RequestInfo requestInfo) {
delayedRequestInfos.add(requestInfo);
if (requestInfo.response != null) {
requestInfo.response.disableFree = true;
} else if (requestInfo.responseWeb != null) {
requestInfo.responseWeb.disableFree = true;
} else if (requestInfo.responseCdn != null) {
requestInfo.responseCdn.disableFree = true;
}
}
private int findNextPreloadDownloadOffset(int atomOffset, int partOffset, NativeByteBuffer partBuffer) {
int partSize = partBuffer.limit();
while (true) {
if (atomOffset < partOffset - (preloadTempBuffer != null ? 16 : 0) || atomOffset >= partOffset + partSize) {
return 0;
}
if (atomOffset >= partOffset + partSize - 16) {
preloadTempBufferCount = partOffset + partSize - atomOffset;
partBuffer.position(partBuffer.limit() - preloadTempBufferCount);
partBuffer.readBytes(preloadTempBuffer, 0, preloadTempBufferCount, false);
return partOffset + partSize;
}
if (preloadTempBufferCount != 0) {
partBuffer.position(0);
partBuffer.readBytes(preloadTempBuffer, preloadTempBufferCount, 16 - preloadTempBufferCount, false);
preloadTempBufferCount = 0;
} else {
partBuffer.position(atomOffset - partOffset);
partBuffer.readBytes(preloadTempBuffer, 0, 16, false);
}
int atomSize = (((int) preloadTempBuffer[0] & 0xFF) << 24) + (((int) preloadTempBuffer[1] & 0xFF) << 16) + (((int) preloadTempBuffer[2] & 0xFF) << 8) + ((int) preloadTempBuffer[3] & 0xFF);
if (atomSize == 0) {
return 0;
} else if (atomSize == 1) {
atomSize = (((int) preloadTempBuffer[12] & 0xFF) << 24) + (((int) preloadTempBuffer[13] & 0xFF) << 16) + (((int) preloadTempBuffer[14] & 0xFF) << 8) + ((int) preloadTempBuffer[15] & 0xFF);
}
if (preloadTempBuffer[4] == 'm' && preloadTempBuffer[5] == 'o' && preloadTempBuffer[6] == 'o' && preloadTempBuffer[7] == 'v') {
return -atomSize;
}
if (atomSize + atomOffset >= partOffset + partSize) {
return atomSize + atomOffset;
}
atomOffset += atomSize;
}
}
private void requestFileOffsets(int offset) {
if (requestingCdnOffsets) {
return;
}
requestingCdnOffsets = true;
TLRPC.TL_upload_getCdnFileHashes req = new TLRPC.TL_upload_getCdnFileHashes();
req.file_token = cdnToken;
req.offset = offset;
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
if (error != null) {
onFail(false, 0);
} else {
requestingCdnOffsets = false;
TLRPC.Vector vector = (TLRPC.Vector) response;
if (!vector.objects.isEmpty()) {
if (cdnHashes == null) {
cdnHashes = new SparseArray<>();
}
for (int a = 0; a < vector.objects.size(); a++) {
TLRPC.TL_fileHash hash = (TLRPC.TL_fileHash) vector.objects.get(a);
cdnHashes.put(hash.offset, hash);
}
}
for (int a = 0; a < delayedRequestInfos.size(); a++) {
RequestInfo delayedRequestInfo = delayedRequestInfos.get(a);
if (notLoadedBytesRanges != null || downloadedBytes == delayedRequestInfo.offset) {
delayedRequestInfos.remove(a);
if (!processRequestResult(delayedRequestInfo, null)) {
if (delayedRequestInfo.response != null) {
delayedRequestInfo.response.disableFree = false;
delayedRequestInfo.response.freeResources();
} else if (delayedRequestInfo.responseWeb != null) {
delayedRequestInfo.responseWeb.disableFree = false;
delayedRequestInfo.responseWeb.freeResources();
} else if (delayedRequestInfo.responseCdn != null) {
delayedRequestInfo.responseCdn.disableFree = false;
delayedRequestInfo.responseCdn.freeResources();
}
}
break;
}
}
}
}, null, null, 0, datacenterId, ConnectionsManager.ConnectionTypeGeneric, true);
}
protected boolean processRequestResult(RequestInfo requestInfo, TLRPC.TL_error error) {
if (state != stateDownloading) {
if (BuildVars.DEBUG_VERSION) {
FileLog.d("trying to write to finished file " + cacheFileFinal + " offset " + requestInfo.offset);
}
return false;
}
requestInfos.remove(requestInfo);
if (error == null) {
try {
if (notLoadedBytesRanges == null && downloadedBytes != requestInfo.offset) {
delayRequestInfo(requestInfo);
return false;
}
NativeByteBuffer bytes;
if (requestInfo.response != null) {
bytes = requestInfo.response.bytes;
} else if (requestInfo.responseWeb != null) {
bytes = requestInfo.responseWeb.bytes;
} else if (requestInfo.responseCdn != null) {
bytes = requestInfo.responseCdn.bytes;
} else {
bytes = null;
}
if (bytes == null || bytes.limit() == 0) {
onFinishLoadingFile(true);
return false;
}
int currentBytesSize = bytes.limit();
if (isCdn) {
int cdnCheckPart = requestInfo.offset / cdnChunkCheckSize;
int fileOffset = cdnCheckPart * cdnChunkCheckSize;
TLRPC.TL_fileHash hash = cdnHashes != null ? cdnHashes.get(fileOffset) : null;
if (hash == null) {
delayRequestInfo(requestInfo);
requestFileOffsets(fileOffset);
return true;
}
}
if (requestInfo.responseCdn != null) {
int offset = requestInfo.offset / 16;
cdnIv[15] = (byte) (offset & 0xff);
cdnIv[14] = (byte) ((offset >> 8) & 0xff);
cdnIv[13] = (byte) ((offset >> 16) & 0xff);
cdnIv[12] = (byte) ((offset >> 24) & 0xff);
Utilities.aesCtrDecryption(bytes.buffer, cdnKey, cdnIv, 0, bytes.limit());
}
boolean finishedDownloading;
if (isPreloadVideoOperation) {
preloadStream.writeInt(requestInfo.offset);
preloadStream.writeInt(currentBytesSize);
preloadStreamFileOffset += 8;
FileChannel channel = preloadStream.getChannel();
channel.write(bytes.buffer);
if (BuildVars.DEBUG_VERSION) {
FileLog.d("save preload file part " + cacheFilePreload + " offset " + requestInfo.offset + " size " + currentBytesSize);
}
if (preloadedBytesRanges == null) {
preloadedBytesRanges = new SparseArray<>();
}
preloadedBytesRanges.put(requestInfo.offset, new PreloadRange(preloadStreamFileOffset, currentBytesSize));
totalPreloadedBytes += currentBytesSize;
preloadStreamFileOffset += currentBytesSize;
if (moovFound == 0) {
int offset = findNextPreloadDownloadOffset(nextAtomOffset, requestInfo.offset, bytes);
if (offset < 0) {
offset *= -1;
nextPreloadDownloadOffset += currentDownloadChunkSize;
if (nextPreloadDownloadOffset < totalBytesCount / 2) {
preloadNotRequestedBytesCount = foundMoovSize = preloadMaxBytes / 2 + offset;
moovFound = 1;
} else {
preloadNotRequestedBytesCount = foundMoovSize = preloadMaxBytes;
moovFound = 2;
}
nextPreloadDownloadOffset = -1;
} else {
nextPreloadDownloadOffset = offset / currentDownloadChunkSize * currentDownloadChunkSize;
}
nextAtomOffset = offset;
}
preloadStream.writeInt(foundMoovSize);
preloadStream.writeInt(nextPreloadDownloadOffset);
preloadStream.writeInt(nextAtomOffset);
preloadStreamFileOffset += 12;
finishedDownloading = nextPreloadDownloadOffset == 0 || moovFound != 0 && foundMoovSize < 0 || totalPreloadedBytes > preloadMaxBytes || nextPreloadDownloadOffset >= totalBytesCount;
if (finishedDownloading) {
preloadStream.seek(0);
preloadStream.write((byte) 1);
} else if (moovFound != 0) {
foundMoovSize -= currentDownloadChunkSize;
}
} else {
downloadedBytes += currentBytesSize;
if (totalBytesCount > 0) {
finishedDownloading = downloadedBytes >= totalBytesCount;
} else {
finishedDownloading = currentBytesSize != currentDownloadChunkSize || (totalBytesCount == downloadedBytes || downloadedBytes % currentDownloadChunkSize != 0) && (totalBytesCount <= 0 || totalBytesCount <= downloadedBytes);
}
if (key != null) {
Utilities.aesIgeEncryption(bytes.buffer, key, iv, false, true, 0, bytes.limit());
if (finishedDownloading && bytesCountPadding != 0) {
bytes.limit(bytes.limit() - bytesCountPadding);
}
}
if (encryptFile) {
int offset = requestInfo.offset / 16;
encryptIv[15] = (byte) (offset & 0xff);
encryptIv[14] = (byte) ((offset >> 8) & 0xff);
encryptIv[13] = (byte) ((offset >> 16) & 0xff);
encryptIv[12] = (byte) ((offset >> 24) & 0xff);
Utilities.aesCtrDecryption(bytes.buffer, encryptKey, encryptIv, 0, bytes.limit());
}
if (notLoadedBytesRanges != null) {
fileOutputStream.seek(requestInfo.offset);
if (BuildVars.DEBUG_VERSION) {
FileLog.d("save file part " + cacheFileFinal + " offset " + requestInfo.offset);
}
}
FileChannel channel = fileOutputStream.getChannel();
channel.write(bytes.buffer);
addPart(notLoadedBytesRanges, requestInfo.offset, requestInfo.offset + currentBytesSize, true);
if (isCdn) {
int cdnCheckPart = requestInfo.offset / cdnChunkCheckSize;
int size = notCheckedCdnRanges.size();
Range range;
boolean checked = true;
for (int a = 0; a < size; a++) {
range = notCheckedCdnRanges.get(a);
if (range.start <= cdnCheckPart && cdnCheckPart <= range.end) {
checked = false;
break;
}
}
if (!checked) {
int fileOffset = cdnCheckPart * cdnChunkCheckSize;
int availableSize = getDownloadedLengthFromOffsetInternal(notLoadedBytesRanges, fileOffset, cdnChunkCheckSize);
if (availableSize != 0 && (availableSize == cdnChunkCheckSize || totalBytesCount > 0 && availableSize == totalBytesCount - fileOffset || totalBytesCount <= 0 && finishedDownloading)) {
TLRPC.TL_fileHash hash = cdnHashes.get(fileOffset);
if (fileReadStream == null) {
cdnCheckBytes = new byte[cdnChunkCheckSize];
fileReadStream = new RandomAccessFile(cacheFileTemp, "r");
}
fileReadStream.seek(fileOffset);
fileReadStream.readFully(cdnCheckBytes, 0, availableSize);
byte[] sha256 = Utilities.computeSHA256(cdnCheckBytes, 0, availableSize);
if (!Arrays.equals(sha256, hash.hash)) {
if (BuildVars.LOGS_ENABLED) {
if (location != null) {
FileLog.e("invalid cdn hash " + location + " id = " + location.id + " local_id = " + location.local_id + " access_hash = " + location.access_hash + " volume_id = " + location.volume_id + " secret = " + location.secret);
} else if (webLocation != null) {
FileLog.e("invalid cdn hash " + webLocation + " id = " + fileName);
}
}
onFail(false, 0);
cacheFileTemp.delete();
return false;
}
cdnHashes.remove(fileOffset);
addPart(notCheckedCdnRanges, cdnCheckPart, cdnCheckPart + 1, false);
}
}
}
if (fiv != null) {
fiv.seek(0);
fiv.write(iv);
}
if (totalBytesCount > 0 && state == stateDownloading) {
copyNotLoadedRanges();
delegate.didChangedLoadProgress(FileLoadOperation.this, downloadedBytes, totalBytesCount);
}
}
for (int a = 0; a < delayedRequestInfos.size(); a++) {
RequestInfo delayedRequestInfo = delayedRequestInfos.get(a);
if (notLoadedBytesRanges != null || downloadedBytes == delayedRequestInfo.offset) {
delayedRequestInfos.remove(a);
if (!processRequestResult(delayedRequestInfo, null)) {
if (delayedRequestInfo.response != null) {
delayedRequestInfo.response.disableFree = false;
delayedRequestInfo.response.freeResources();
} else if (delayedRequestInfo.responseWeb != null) {
delayedRequestInfo.responseWeb.disableFree = false;
delayedRequestInfo.responseWeb.freeResources();
} else if (delayedRequestInfo.responseCdn != null) {
delayedRequestInfo.responseCdn.disableFree = false;
delayedRequestInfo.responseCdn.freeResources();
}
}
break;
}
}
if (finishedDownloading) {
onFinishLoadingFile(true);
} else {
startDownloadRequest();
}
} catch (Exception e) {
onFail(false, 0);
FileLog.e(e);
}
} else {
if (error.text.contains("FILE_MIGRATE_")) {
String errorMsg = error.text.replace("FILE_MIGRATE_", "");
Scanner scanner = new Scanner(errorMsg);
scanner.useDelimiter("");
Integer val;
try {
val = scanner.nextInt();
} catch (Exception e) {
val = null;
}
if (val == null) {
onFail(false, 0);
} else {
datacenterId = val;
requestedBytesCount = downloadedBytes = 0;
startDownloadRequest();
}
} else if (error.text.contains("OFFSET_INVALID")) {
if (downloadedBytes % currentDownloadChunkSize == 0) {
try {
onFinishLoadingFile(true);
} catch (Exception e) {
FileLog.e(e);
onFail(false, 0);
}
} else {
onFail(false, 0);
}
} else if (error.text.contains("RETRY_LIMIT")) {
onFail(false, 2);
} else {
if (BuildVars.LOGS_ENABLED) {
if (location != null) {
FileLog.e(error.text + " " + location + " id = " + location.id + " local_id = " + location.local_id + " access_hash = " + location.access_hash + " volume_id = " + location.volume_id + " secret = " + location.secret);
} else if (webLocation != null) {
FileLog.e(error.text + " " + webLocation + " id = " + fileName);
}
}
onFail(false, 0);
}
}
return false;
}
protected void onFail(boolean thread, final int reason) {
cleanup();
state = stateFailed;
if (thread) {
Utilities.stageQueue.postRunnable(() -> delegate.didFailedLoadingFile(FileLoadOperation.this, reason));
} else {
delegate.didFailedLoadingFile(FileLoadOperation.this, reason);
}
}
private void clearOperaion(RequestInfo currentInfo, boolean preloadChanged) {
int minOffset = Integer.MAX_VALUE;
for (int a = 0; a < requestInfos.size(); a++) {
RequestInfo info = requestInfos.get(a);
minOffset = Math.min(info.offset, minOffset);
if (isPreloadVideoOperation) {
requestedPreloadedBytesRanges.delete(info.offset);
} else {
removePart(notRequestedBytesRanges, info.offset, info.offset + currentDownloadChunkSize);
}
if (currentInfo == info) {
continue;
}
if (info.requestToken != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(info.requestToken, true);
}
}
requestInfos.clear();
for (int a = 0; a < delayedRequestInfos.size(); a++) {
RequestInfo info = delayedRequestInfos.get(a);
if (isPreloadVideoOperation) {
requestedPreloadedBytesRanges.delete(info.offset);
} else {
removePart(notRequestedBytesRanges, info.offset, info.offset + currentDownloadChunkSize);
}
if (info.response != null) {
info.response.disableFree = false;
info.response.freeResources();
} else if (info.responseWeb != null) {
info.responseWeb.disableFree = false;
info.responseWeb.freeResources();
} else if (info.responseCdn != null) {
info.responseCdn.disableFree = false;
info.responseCdn.freeResources();
}
minOffset = Math.min(info.offset, minOffset);
}
delayedRequestInfos.clear();
requestsCount = 0;
if (!preloadChanged && isPreloadVideoOperation) {
requestedBytesCount = totalPreloadedBytes;
} else if (notLoadedBytesRanges == null) {
requestedBytesCount = downloadedBytes = minOffset;
}
}
private void requestReference(RequestInfo requestInfo) {
if (requestingReference) {
return;
}
clearOperaion(requestInfo, false);
requestingReference = true;
if (parentObject instanceof MessageObject) {
MessageObject messageObject = (MessageObject) parentObject;
if (messageObject.getId() < 0 && messageObject.messageOwner.media.webpage != null) {
parentObject = messageObject.messageOwner.media.webpage;
}
}
FileRefController.getInstance(currentAccount).requestReference(parentObject, location, this, requestInfo);
}
protected void startDownloadRequest() {
if (paused || reuploadingCdn ||
state != stateDownloading ||
streamPriorityStartOffset == 0 && (
!nextPartWasPreloaded && (requestInfos.size() + delayedRequestInfos.size() >= currentMaxDownloadRequests) ||
isPreloadVideoOperation && (requestedBytesCount > preloadMaxBytes || moovFound != 0 && requestInfos.size() > 0))) {
return;
}
int count = 1;
if (streamPriorityStartOffset == 0 && !nextPartWasPreloaded && (!isPreloadVideoOperation || moovFound != 0) && totalBytesCount > 0) {
count = Math.max(0, currentMaxDownloadRequests - requestInfos.size());
}
for (int a = 0; a < count; a++) {
int downloadOffset;
if (isPreloadVideoOperation) {
if (moovFound != 0 && preloadNotRequestedBytesCount <= 0) {
return;
}
if (nextPreloadDownloadOffset == -1) {
downloadOffset = 0;
boolean found = false;
int tries = preloadMaxBytes / currentDownloadChunkSize + 2;
while (tries != 0) {
if (requestedPreloadedBytesRanges.get(downloadOffset, 0) == 0) {
found = true;
break;
}
downloadOffset += currentDownloadChunkSize;
if (downloadOffset > totalBytesCount) {
break;
}
if (moovFound == 2 && downloadOffset == currentDownloadChunkSize * 8) {
downloadOffset = (totalBytesCount - preloadMaxBytes / 2) / currentDownloadChunkSize * currentDownloadChunkSize;
}
tries--;
}
if (!found && requestInfos.isEmpty()) {
onFinishLoadingFile(false);
}
} else {
downloadOffset = nextPreloadDownloadOffset;
}
if (requestedPreloadedBytesRanges == null) {
requestedPreloadedBytesRanges = new SparseIntArray();
}
requestedPreloadedBytesRanges.put(downloadOffset, 1);
if (BuildVars.DEBUG_VERSION) {
FileLog.d("start next preload from " + downloadOffset + " size " + totalBytesCount + " for " + cacheFilePreload);
}
preloadNotRequestedBytesCount -= currentDownloadChunkSize;
} else {
if (notRequestedBytesRanges != null) {
int sreamOffset = streamPriorityStartOffset != 0 ? streamPriorityStartOffset : streamStartOffset;
int size = notRequestedBytesRanges.size();
int minStart = Integer.MAX_VALUE;
int minStreamStart = Integer.MAX_VALUE;
for (int b = 0; b < size; b++) {
Range range = notRequestedBytesRanges.get(b);
if (sreamOffset != 0) {
if (range.start <= sreamOffset && range.end > sreamOffset) {
minStreamStart = sreamOffset;
minStart = Integer.MAX_VALUE;
break;
}
if (sreamOffset < range.start && range.start < minStreamStart) {
minStreamStart = range.start;
}
}
minStart = Math.min(minStart, range.start);
}
if (minStreamStart != Integer.MAX_VALUE) {
downloadOffset = minStreamStart;
} else if (minStart != Integer.MAX_VALUE) {
downloadOffset = minStart;
} else {
break;
}
} else {
downloadOffset = requestedBytesCount;
}
}
if (!isPreloadVideoOperation && notRequestedBytesRanges != null) {
addPart(notRequestedBytesRanges, downloadOffset, downloadOffset + currentDownloadChunkSize, false);
}
if (totalBytesCount > 0 && downloadOffset >= totalBytesCount) {
break;
}
boolean isLast = totalBytesCount <= 0 || a == count - 1 || totalBytesCount > 0 && downloadOffset + currentDownloadChunkSize >= totalBytesCount;
final TLObject request;
int connectionType = requestsCount % 2 == 0 ? ConnectionsManager.ConnectionTypeDownload : ConnectionsManager.ConnectionTypeDownload2;
int flags = (isForceRequest ? ConnectionsManager.RequestFlagForceDownload : 0);
if (isCdn) {
TLRPC.TL_upload_getCdnFile req = new TLRPC.TL_upload_getCdnFile();
req.file_token = cdnToken;
req.offset = downloadOffset;
req.limit = currentDownloadChunkSize;
request = req;
flags |= ConnectionsManager.RequestFlagEnableUnauthorized;
} else {
if (webLocation != null) {
TLRPC.TL_upload_getWebFile req = new TLRPC.TL_upload_getWebFile();
req.location = webLocation;
req.offset = downloadOffset;
req.limit = currentDownloadChunkSize;
request = req;
} else {
TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
req.location = location;
req.offset = downloadOffset;
req.limit = currentDownloadChunkSize;
req.cdn_supported = true;
request = req;
}
}
requestedBytesCount += currentDownloadChunkSize;
final RequestInfo requestInfo = new RequestInfo();
requestInfos.add(requestInfo);
requestInfo.offset = downloadOffset;
if (!isPreloadVideoOperation && supportsPreloading && preloadStream != null && preloadedBytesRanges != null) {
PreloadRange range = preloadedBytesRanges.get(requestInfo.offset);
if (range != null) {
requestInfo.response = new TLRPC.TL_upload_file();
try {
NativeByteBuffer buffer = new NativeByteBuffer(range.length);
preloadStream.seek(range.fileOffset);
preloadStream.getChannel().read(buffer.buffer);
buffer.buffer.position(0);
requestInfo.response.bytes = buffer;
Utilities.stageQueue.postRunnable(() -> {
processRequestResult(requestInfo, null);
requestInfo.response.freeResources();
});
continue;
} catch (Exception ignore) {
}
}
}
if (streamPriorityStartOffset != 0) {
if (BuildVars.DEBUG_VERSION) {
FileLog.d("frame get offset = " + streamPriorityStartOffset);
}
streamPriorityStartOffset = 0;
priorityRequestInfo = requestInfo;
}
requestInfo.requestToken = ConnectionsManager.getInstance(currentAccount).sendRequest(request, (response, error) -> {
if (!requestInfos.contains(requestInfo)) {
return;
}
if (requestInfo == priorityRequestInfo) {
if (BuildVars.DEBUG_VERSION) {
FileLog.d("frame get request completed " + priorityRequestInfo.offset);
}
priorityRequestInfo = null;
}
if (error != null) {
if (FileRefController.isFileRefError(error.text)) {
requestReference(requestInfo);
return;
} else if (request instanceof TLRPC.TL_upload_getCdnFile) {
if (error.text.equals("FILE_TOKEN_INVALID")) {
isCdn = false;
clearOperaion(requestInfo, false);
startDownloadRequest();
return;
}
}
}
if (response instanceof TLRPC.TL_upload_fileCdnRedirect) {
TLRPC.TL_upload_fileCdnRedirect res = (TLRPC.TL_upload_fileCdnRedirect) response;
if (!res.file_hashes.isEmpty()) {
if (cdnHashes == null) {
cdnHashes = new SparseArray<>();
}
for (int a1 = 0; a1 < res.file_hashes.size(); a1++) {
TLRPC.TL_fileHash hash = res.file_hashes.get(a1);
cdnHashes.put(hash.offset, hash);
}
}
if (res.encryption_iv == null || res.encryption_key == null || res.encryption_iv.length != 16 || res.encryption_key.length != 32) {
error = new TLRPC.TL_error();
error.text = "bad redirect response";
error.code = 400;
processRequestResult(requestInfo, error);
} else {
isCdn = true;
if (notCheckedCdnRanges == null) {
notCheckedCdnRanges = new ArrayList<>();
notCheckedCdnRanges.add(new Range(0, maxCdnParts));
}
cdnDatacenterId = res.dc_id;
cdnIv = res.encryption_iv;
cdnKey = res.encryption_key;
cdnToken = res.file_token;
clearOperaion(requestInfo, false);
startDownloadRequest();
}
} else if (response instanceof TLRPC.TL_upload_cdnFileReuploadNeeded) {
if (!reuploadingCdn) {
clearOperaion(requestInfo, false);
reuploadingCdn = true;
TLRPC.TL_upload_cdnFileReuploadNeeded res = (TLRPC.TL_upload_cdnFileReuploadNeeded) response;
TLRPC.TL_upload_reuploadCdnFile req = new TLRPC.TL_upload_reuploadCdnFile();
req.file_token = cdnToken;
req.request_token = res.request_token;
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response1, error1) -> {
reuploadingCdn = false;
if (error1 == null) {
TLRPC.Vector vector = (TLRPC.Vector) response1;
if (!vector.objects.isEmpty()) {
if (cdnHashes == null) {
cdnHashes = new SparseArray<>();
}
for (int a1 = 0; a1 < vector.objects.size(); a1++) {
TLRPC.TL_fileHash hash = (TLRPC.TL_fileHash) vector.objects.get(a1);
cdnHashes.put(hash.offset, hash);
}
}
startDownloadRequest();
} else {
if (error1.text.equals("FILE_TOKEN_INVALID") || error1.text.equals("REQUEST_TOKEN_INVALID")) {
isCdn = false;
clearOperaion(requestInfo, false);
startDownloadRequest();
} else {
onFail(false, 0);
}
}
}, null, null, 0, datacenterId, ConnectionsManager.ConnectionTypeGeneric, true);
}
} else {
if (response instanceof TLRPC.TL_upload_file) {
requestInfo.response = (TLRPC.TL_upload_file) response;
} else if (response instanceof TLRPC.TL_upload_webFile) {
requestInfo.responseWeb = (TLRPC.TL_upload_webFile) response;
if (totalBytesCount == 0 && requestInfo.responseWeb.size != 0) {
totalBytesCount = requestInfo.responseWeb.size;
}
} else {
requestInfo.responseCdn = (TLRPC.TL_upload_cdnFile) response;
}
if (response != null) {
if (currentType == ConnectionsManager.FileTypeAudio) {
StatsController.getInstance(currentAccount).incrementReceivedBytesCount(response.networkType, StatsController.TYPE_AUDIOS, response.getObjectSize() + 4);
} else if (currentType == ConnectionsManager.FileTypeVideo) {
StatsController.getInstance(currentAccount).incrementReceivedBytesCount(response.networkType, StatsController.TYPE_VIDEOS, response.getObjectSize() + 4);
} else if (currentType == ConnectionsManager.FileTypePhoto) {
StatsController.getInstance(currentAccount).incrementReceivedBytesCount(response.networkType, StatsController.TYPE_PHOTOS, response.getObjectSize() + 4);
} else if (currentType == ConnectionsManager.FileTypeFile) {
StatsController.getInstance(currentAccount).incrementReceivedBytesCount(response.networkType, StatsController.TYPE_FILES, response.getObjectSize() + 4);
}
}
processRequestResult(requestInfo, error);
}
}, null, null, flags, isCdn ? cdnDatacenterId : datacenterId, connectionType, isLast);
requestsCount++;
}
}
public void setDelegate(FileLoadOperationDelegate delegate) {
this.delegate = delegate;
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="BooksModel.Store" Provider="System.Data.SqlClient" ProviderManifestToken="2008" Alias="Self" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
<EntityType Name="Authors">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="FirstName" Type="nvarchar" MaxLength="50" Nullable="false" />
<Property Name="LastName" Type="nvarchar" MaxLength="50" Nullable="false" />
</EntityType>
<EntityType Name="Books">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="Title" Type="nvarchar" MaxLength="50" Nullable="false" />
<Property Name="Publisher" Type="nvarchar" MaxLength="50" Nullable="false" />
<Property Name="Isbn" Type="nvarchar" MaxLength="50" Nullable="false" />
</EntityType>
<EntityType Name="BooksAuthors">
<Key>
<PropertyRef Name="Authors_Id" />
<PropertyRef Name="Books_Id" />
</Key>
<Property Name="Authors_Id" Type="int" Nullable="false" />
<Property Name="Books_Id" Type="int" Nullable="false" />
</EntityType>
<Association Name="FK_BooksAuthors_ToAuthors">
<End Role="Authors" Type="Self.Authors" Multiplicity="1" />
<End Role="BooksAuthors" Type="Self.BooksAuthors" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Authors">
<PropertyRef Name="Id" />
</Principal>
<Dependent Role="BooksAuthors">
<PropertyRef Name="Authors_Id" />
</Dependent>
</ReferentialConstraint>
</Association>
<Association Name="FK_BooksAuthors_ToBooks">
<End Role="Books" Type="Self.Books" Multiplicity="1" />
<End Role="BooksAuthors" Type="Self.BooksAuthors" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Books">
<PropertyRef Name="Id" />
</Principal>
<Dependent Role="BooksAuthors">
<PropertyRef Name="Books_Id" />
</Dependent>
</ReferentialConstraint>
</Association>
<EntityContainer Name="BooksModelStoreContainer">
<EntitySet Name="Authors" EntityType="Self.Authors" Schema="dbo" p3:Type="Tables" xmlns:p3="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
<EntitySet Name="Books" EntityType="Self.Books" Schema="dbo" p3:Type="Tables" xmlns:p3="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
<EntitySet Name="BooksAuthors" EntityType="Self.BooksAuthors" Schema="dbo" p3:Type="Tables" xmlns:p3="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
<AssociationSet Name="FK_BooksAuthors_ToAuthors" Association="Self.FK_BooksAuthors_ToAuthors">
<End Role="Authors" EntitySet="Authors" />
<End Role="BooksAuthors" EntitySet="BooksAuthors" />
</AssociationSet>
<AssociationSet Name="FK_BooksAuthors_ToBooks" Association="Self.FK_BooksAuthors_ToBooks">
<End Role="Books" EntitySet="Books" />
<End Role="BooksAuthors" EntitySet="BooksAuthors" />
</AssociationSet>
</EntityContainer>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="BooksModel" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
<EntityType Name="Author">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="FirstName" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
<Property Name="LastName" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
<NavigationProperty Name="Books" Relationship="Self.BooksAuthors" FromRole="Authors" ToRole="Books" />
</EntityType>
<EntityType Name="Book">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="Title" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
<Property Name="Publisher" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
<Property Name="Isbn" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
<NavigationProperty Name="Authors" Relationship="Self.BooksAuthors" FromRole="Books" ToRole="Authors" />
</EntityType>
<Association Name="BooksAuthors">
<End Role="Authors" Type="Self.Author" Multiplicity="*" />
<End Role="Books" Type="Self.Book" Multiplicity="*" />
</Association>
<EntityContainer Name="BooksEntities" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Authors" EntityType="Self.Author" />
<EntitySet Name="Books" EntityType="Self.Book" />
<AssociationSet Name="BooksAuthors" Association="Self.BooksAuthors">
<End Role="Authors" EntitySet="Authors" />
<End Role="Books" EntitySet="Books" />
</AssociationSet>
</EntityContainer>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
<EntityContainerMapping StorageEntityContainer="BooksModelStoreContainer" CdmEntityContainer="BooksEntities">
<EntitySetMapping Name="Authors">
<EntityTypeMapping TypeName="BooksModel.Author">
<MappingFragment StoreEntitySet="Authors">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="FirstName" ColumnName="FirstName" />
<ScalarProperty Name="LastName" ColumnName="LastName" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="Books">
<EntityTypeMapping TypeName="BooksModel.Book">
<MappingFragment StoreEntitySet="Books">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="Title" ColumnName="Title" />
<ScalarProperty Name="Publisher" ColumnName="Publisher" />
<ScalarProperty Name="Isbn" ColumnName="Isbn" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<AssociationSetMapping Name="BooksAuthors" TypeName="BooksModel.BooksAuthors" StoreEntitySet="BooksAuthors">
<EndProperty Name="Authors">
<ScalarProperty Name="Id" ColumnName="Authors_Id" />
</EndProperty>
<EndProperty Name="Books">
<ScalarProperty Name="Id" ColumnName="Books_Id" />
</EndProperty>
</AssociationSetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<Designer xmlns="http://schemas.microsoft.com/ado/2009/11/edmx">
<Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</Connection>
<Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
<DesignerProperty Name="EnablePluralization" Value="true" />
<DesignerProperty Name="IncludeForeignKeysInModel" Value="true" />
<DesignerProperty Name="UseLegacyProvider" Value="false" />
<DesignerProperty Name="CodeGenerationStrategy" Value="None" />
</DesignerInfoPropertySet>
</Options>
<!-- Diagram content (shape and connector positions) -->
<Diagrams></Diagrams>
</Designer>
</edmx:Edmx> | {
"pile_set_name": "Github"
} |
package org.revenj.database.postgres.jinq.transform;
import ch.epfl.labos.iu.orm.queryll2.symbolic.TypedValueVisitorException;
import org.revenj.database.postgres.jinq.jpqlquery.ColumnExpressions;
import org.revenj.database.postgres.jinq.jpqlquery.JinqPostgresQuery;
import org.revenj.database.postgres.jinq.jpqlquery.SelectFromWhere;
public class SortingTransform extends RevenjOneLambdaQueryTransform {
public SortingTransform(RevenjQueryTransformConfiguration config, boolean isAscending) {
super(config);
this.isAscending = isAscending;
}
private boolean isAscending;
@Override
public <U, V> JinqPostgresQuery<U> apply(JinqPostgresQuery<V> query, LambdaAnalysis lambda, SymbExArgumentHandler parentArgumentScope) throws QueryTransformException {
try {
if (query instanceof SelectFromWhere && query.canSort()) {
SelectFromWhere<V> sfw = (SelectFromWhere<V>) query;
SelectFromWhereLambdaArgumentHandler argHandler = SelectFromWhereLambdaArgumentHandler.fromSelectFromWhere(sfw, lambda, config.metamodel, parentArgumentScope, false);
SymbExToColumns translator = config.newSymbExToColumns(argHandler, lambda.getLambdaIndex());
ColumnExpressions<U> returnExpr = makeSelectExpression(translator, lambda);
// Create the new query, merging in the analysis of the method
SelectFromWhere<U> toReturn = (SelectFromWhere<U>) sfw.shallowCopy();
SelectFromWhere.SortingParameters sort = new SelectFromWhere.SortingParameters();
sort.expr = returnExpr.getOnlyColumn();
sort.isAscending = isAscending;
toReturn.sort.add(sort);
return toReturn;
}
throw new QueryTransformException("Existing query cannot be transformed further");
} catch (TypedValueVisitorException e) {
throw new QueryTransformException(e);
}
}
@Override
public String getTransformationTypeCachingTag() {
return isAscending ? "sort-asc" : "sort-desc";
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project name="File_Iterator" default="build">
<property name="php" value="php"/>
<property name="phpunit" value="phpunit"/>
<target name="build"
depends="prepare,lint,phploc,pdepend,phpmd-ci,phpcs-ci,phpcpd,phpcb"/>
<target name="build-parallel"
depends="prepare,lint,tools-parallel,phpcb"/>
<target name="tools-parallel"
description="Run tools in parallel">
<parallel threadCount="2">
<sequential>
<antcall target="pdepend"/>
<antcall target="phpmd-ci"/>
</sequential>
<antcall target="phpcpd"/>
<antcall target="phpcs-ci"/>
<antcall target="phploc"/>
</parallel>
</target>
<target name="clean" description="Cleanup build artifacts">
<delete dir="${basedir}/build/api"/>
<delete dir="${basedir}/build/code-browser"/>
<delete dir="${basedir}/build/coverage"/>
<delete dir="${basedir}/build/logs"/>
<delete dir="${basedir}/build/pdepend"/>
</target>
<target name="prepare" depends="clean,phpab"
description="Prepare for build">
<mkdir dir="${basedir}/build/api"/>
<mkdir dir="${basedir}/build/code-browser"/>
<mkdir dir="${basedir}/build/coverage"/>
<mkdir dir="${basedir}/build/logs"/>
<mkdir dir="${basedir}/build/pdepend"/>
</target>
<target name="phpab" description="Generate autoloader scripts">
<exec executable="phpab">
<arg value="--output" />
<arg path="File/Iterator/Autoload.php" />
<arg value="--template" />
<arg path="File/Iterator/Autoload.php.in" />
<arg value="--indent" />
<arg value=" " />
<arg path="File" />
</exec>
</target>
<target name="lint">
<apply executable="${php}" failonerror="true">
<arg value="-l" />
<fileset dir="${basedir}/File">
<include name="**/*.php" />
<modified />
</fileset>
<!--
<fileset dir="${basedir}/Tests">
<include name="**/*.php" />
<modified />
</fileset>
-->
</apply>
</target>
<target name="phploc" description="Measure project size using PHPLOC">
<exec executable="phploc">
<arg value="--log-csv" />
<arg value="${basedir}/build/logs/phploc.csv" />
<arg path="${basedir}/File" />
</exec>
</target>
<target name="pdepend"
description="Calculate software metrics using PHP_Depend">
<exec executable="pdepend">
<arg value="--jdepend-xml=${basedir}/build/logs/jdepend.xml" />
<arg value="--jdepend-chart=${basedir}/build/pdepend/dependencies.svg" />
<arg value="--overview-pyramid=${basedir}/build/pdepend/overview-pyramid.svg" />
<arg path="${basedir}/File" />
</exec>
</target>
<target name="phpmd"
description="Perform project mess detection using PHPMD">
<exec executable="phpmd">
<arg path="${basedir}/File" />
<arg value="text" />
<arg value="${basedir}/build/phpmd.xml" />
</exec>
</target>
<target name="phpmd-ci"
description="Perform project mess detection using PHPMD">
<exec executable="phpmd">
<arg path="${basedir}/File" />
<arg value="xml" />
<arg value="${basedir}/build/phpmd.xml" />
<arg value="--reportfile" />
<arg value="${basedir}/build/logs/pmd.xml" />
</exec>
</target>
<target name="phpcs"
description="Find coding standard violations using PHP_CodeSniffer">
<exec executable="phpcs">
<arg value="--standard=${basedir}/build/PHPCS" />
<arg value="--extensions=php" />
<arg value="--ignore=Autoload.php" />
<arg path="${basedir}/File" />
</exec>
</target>
<target name="phpcs-ci"
description="Find coding standard violations using PHP_CodeSniffer">
<exec executable="phpcs" output="/dev/null">
<arg value="--report=checkstyle" />
<arg value="--report-file=${basedir}/build/logs/checkstyle.xml" />
<arg value="--standard=${basedir}/build/PHPCS" />
<arg value="--extensions=php" />
<arg value="--ignore=Autoload.php" />
<arg path="${basedir}/File" />
</exec>
</target>
<target name="phpcpd" description="Find duplicate code using PHPCPD">
<exec executable="phpcpd">
<arg value="--log-pmd" />
<arg value="${basedir}/build/logs/pmd-cpd.xml" />
<arg path="${basedir}/File" />
</exec>
</target>
<target name="phpunit" description="Run unit tests with PHPUnit">
<condition property="phpunit_cmd" value="${php} ${phpunit}" else="${phpunit}">
<not>
<equals arg1="${phpunit}" arg2="phpunit" />
</not>
</condition>
<exec executable="${phpunit_cmd}" failonerror="true"/>
</target>
<target name="phpcb"
description="Aggregate tool output with PHP_CodeBrowser">
<exec executable="phpcb">
<arg value="--log" />
<arg path="${basedir}/build/logs" />
<arg value="--source" />
<arg path="${basedir}/File" />
<arg value="--output" />
<arg path="${basedir}/build/code-browser" />
</exec>
</target>
</project>
| {
"pile_set_name": "Github"
} |
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"wafPolicyName": {
"type": "string",
"metadata": {
"description": "The name of the WAF policy"
}
},
"wafMode": {
"type": "string",
"allowedValues": [
"Detection",
"Prevention"
],
"defaultValue": "Detection",
"metadata": {
"description": "Describes if it is in detection mode or prevention mode at policy level."
}
}
},
"variables": {
"wafLocation": "global"
},
"resources": [
{
"apiVersion": "2019-03-01",
"type": "Microsoft.Network/FrontDoorWebApplicationFirewallPolicies",
"name": "[parameters('wafPolicyName')]",
"location": "[variables('wafLocation')]",
"properties": {
"policySettings": {
"mode": "[parameters('wafMode')]",
"enabledState": "Enabled"
},
"managedRules": {
"managedRuleSets": [
{
"ruleSetType": "DefaultRuleSet",
"ruleSetVersion": "1.0"
}
]
}
}
}
],
"outputs": {}
} | {
"pile_set_name": "Github"
} |
# Copyright (c) 2005-2010 Resolver Systems Ltd, PythonAnywhere LLP
# See LICENSE.md
#
try:
import unittest2 as unittest
except ImportError:
import unittest
from sheet.parser.parse_node import ParseNode
def Expr(children):
return ParseNode.construct_node(ParseNode.EXPR, children)
def Name(children):
return ParseNode.construct_node(ParseNode.NAME, children)
def ShiftExpr(children):
return ParseNode.construct_node(ParseNode.SHIFT_EXPR, children)
class ParseNodeTest(unittest.TestCase):
def testStr(self):
node = Expr([Name(["a"])])
self.assertEquals(str(node), "<ParseNode type=\"EXPR\" children=[<ParseNode type=\"NAME\" children=['a']>]>", "Wrong string representation")
def testEquals(self):
node1 = Expr([Name(["a"])])
node2 = Expr([Name(["a"])])
self.assertTrue(node1 == node2, "Nodes expected to be equal were not")
self.assertFalse(node1 != node2, "Nodes not expected to be unequal were")
node3 = Expr([Name(["b"])])
self.assertFalse(node2 == node3, "Nodes not expected to be equal were")
self.assertTrue(node2 != node3, "Nodes expected to be unequal were not")
node4 = Expr([Name(5)])
self.assertFalse(node3 == None, "Nodes not expected to be equal were (None)")
self.assertFalse(node3 == node4, "Nodes not expected to be equal were (unsized)")
self.assertFalse(node4 == node3, "Nodes not expected to be equal were (unsized)")
self.assertFalse(node4 == "hello", "Nodes not expected to be equal were (type)")
def testFlatten(self):
node = Expr([None])
self.assertEquals(node.flatten(), "", "Unexpected flattening")
node = Expr([Name(["a"])])
self.assertEquals(node.flatten(), "a", "Unexpected flattening")
node = Expr([Name(["a "]), "or ", ShiftExpr([Name(["b "]), "<< ", Name(["c"])])])
self.assertEquals(node.flatten(), "a or b << c", "Unexpected flattening")
def testFlattenWithUnicode(self):
node = Expr([Name([u"\u20ac"])])
self.assertEquals(node.flatten(), u"\u20ac", "unexpected flattening")
def testFlattenHandlesSubclassed(self):
"test flatten handles subclassed parse nodes"
class ParseNodeSubclass(ParseNode):
pass
node = Expr([ParseNodeSubclass(ParseNode.NAME, ["Thing"])])
self.assertEquals(node.flatten(), "Thing", "Thing should have been thing. Merry Christmas!")
def testParseNodeShould(self):
"test ParseNode should allow registering of node classes"
class CustomParseNode(ParseNode):
def __init__(self, children):
ParseNode.__init__(self, "CUSTOM_NODE_TYPE", children)
ParseNode.register_node_type("CUSTOM_NODE_TYPE", CustomParseNode)
try:
node = ParseNode.construct_node("CUSTOM_NODE_TYPE", [])
self.assertEquals(type(node), CustomParseNode, "ParseNode.construct_node didn't dispatch to CustomParseNode")
self.assertEquals(node.type, "CUSTOM_NODE_TYPE", "Wrong type attribute")
self.assertEquals(node.children, [], "Wrong children")
node = ParseNode.construct_node("FISH BOWL", ["gox blamp"])
self.assertEquals(type(node), ParseNode, "ParseNode.construct_node didn't fall back to ParseNode")
self.assertEquals(node.type, "FISH BOWL", "Wrong type attribute")
self.assertEquals(node.children, ["gox blamp"], "Wrong children")
self.assertIsNotNone(ParseNode.classRegistry, "ParseNode didn't have a class registry")
finally:
del ParseNode.classRegistry["CUSTOM_NODE_TYPE"]
| {
"pile_set_name": "Github"
} |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * account_test
#
# Translators:
# Martin Trigaux, 2018
# Manuela Silva <[email protected]>, 2018
# Ricardo Martins <[email protected]>, 2018
# MS, 2018
# Diogo Fonseca <[email protected]>, 2018
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server saas~11.5\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-09-21 13:17+0000\n"
"PO-Revision-Date: 2018-08-24 09:15+0000\n"
"Last-Translator: Diogo Fonseca <[email protected]>, 2018\n"
"Language-Team: Portuguese (https://www.transifex.com/odoo/teams/41243/pt/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Language: pt\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.report_accounttest
msgid ""
"<br/>\n"
" <strong>Description:</strong>"
msgstr ""
"<br/>\n"
" <strong>Descrição:</strong>"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.report_accounttest
msgid "<strong>Name:</strong>"
msgstr "<strong>Nome:</strong>"
#. module: account_test
#: model:ir.model,name:account_test.model_report_account_test_report_accounttest
msgid "Account Test Report"
msgstr "Relatório de Conta de Teste"
#. module: account_test
#: model:ir.model,name:account_test.model_accounting_assert_test
msgid "Accounting Assert Test"
msgstr ""
#. module: account_test
#: model:ir.actions.act_window,name:account_test.action_accounting_assert
#: model:ir.actions.report,name:account_test.account_assert_test_report
#: model:ir.ui.menu,name:account_test.menu_action_license
msgid "Accounting Tests"
msgstr "Testes de Contabilidade"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.report_accounttest
msgid "Accouting tests on"
msgstr "Testes de Contabilidade em"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__active
msgid "Active"
msgstr "Ativo"
#. module: account_test
#: model:accounting.assert.test,desc:account_test.account_test_03
msgid "Check if movement lines are balanced and have the same date and period"
msgstr ""
"Verifique se as linhas de movimento estão saldadas e têm a mesma data e "
"período"
#. module: account_test
#: model:accounting.assert.test,desc:account_test.account_test_07
msgid ""
"Check on bank statement that the Closing Balance = Starting Balance + sum of"
" statement lines"
msgstr ""
"Verifique no extrato bancário se o Saldo Final = Saldo Inicial + soma das "
"linhas do extrato"
#. module: account_test
#: model:accounting.assert.test,desc:account_test.account_test_06
msgid "Check that paid/reconciled invoices are not in 'Open' state"
msgstr ""
"Verifique se as faturas pagas/reconciliadas não estão no estado 'Em Aberto'"
#. module: account_test
#: model:accounting.assert.test,desc:account_test.account_test_05_2
msgid ""
"Check that reconciled account moves, that define Payable and Receivable "
"accounts, are belonging to reconciled invoices"
msgstr ""
"Verifique se os movimentos contabilísticos reconciliados que definem as "
"contas 'A Pagar' e 'A Receber', pertencem às faturas reconciliadas"
#. module: account_test
#: model:accounting.assert.test,desc:account_test.account_test_05
msgid ""
"Check that reconciled invoice for Sales/Purchases has reconciled entries for"
" Payable and Receivable Accounts"
msgstr ""
"Verifique se a fatura reconciliada para Vendas/Compras tem movimentos "
"reconciliados para as contas 'A Pagar' e 'A Receber'"
#. module: account_test
#: model:accounting.assert.test,desc:account_test.account_test_01
msgid "Check the balance: Debit sum = Credit sum"
msgstr "Verifique o saldo: soma do Débito = soma do Crédito"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.account_assert_form
msgid "Code Help"
msgstr "Código de Ajuda"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.account_assert_form
msgid ""
"Code should always set a variable named `result` with the result of your test, that can be a list or\n"
"a dictionary. If `result` is an empty list, it means that the test was succesful. Otherwise it will\n"
"try to translate and print what is inside `result`.\n"
"\n"
"If the result of your test is a dictionary, you can set a variable named `column_order` to choose in\n"
"what order you want to print `result`'s content.\n"
"\n"
"Should you need them, you can also use the following variables into your code:\n"
" * cr: cursor to the database\n"
" * uid: ID of the current user\n"
"\n"
"In any ways, the code must be legal python statements with correct indentation (if needed).\n"
"\n"
"Example: \n"
" sql = '''SELECT id, name, ref, date\n"
" FROM account_move_line \n"
" WHERE account_id IN (SELECT id FROM account_account WHERE type = 'view')\n"
" '''\n"
" cr.execute(sql)\n"
" result = cr.dictfetchall()"
msgstr ""
"Código deve sempre definir uma variável chamada `result` com o resultado de seu teste, que \n"
"pode ser uma lista ou um dicionário. Se `result` é uma lista vazia, significa que o teste foi bem \n"
"sucedido. Caso contrário, irá tentar traduzir e imprimir o que está dentro de `result`.\n"
"\n"
"Se o resultado do seu teste é um dicionário, pode definir uma variável chamada `column_order` \n"
"para escolher em que ordem deseja imprimir o conteúdo de `result`.\n"
"\n"
"Se precisar deles, também pode usar as seguintes variáveis no seu código:\n"
" * cr: cursor para a base de dados\n"
" * uid: ID do utilizador atual\n"
"\n"
"Em todas as maneiras, o código deve ser comandos Python com recuo correto ( se necessário).\n"
"\n"
"Exemplo: \n"
" sql = '''SELECT id, name, ref, date\n"
" FROM account_move_line \n"
" WHERE account_id IN (SELECT id FROM account_account WHERE type = 'view')\n"
" '''\n"
" cr.execute(sql)\n"
" result = cr.dictfetchall()"
#. module: account_test
#: model_terms:ir.actions.act_window,help:account_test.action_accounting_assert
msgid "Create a new accounting test"
msgstr "Criar nova Conta de Teste"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__create_uid
msgid "Created by"
msgstr "Criado por"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__create_date
msgid "Created on"
msgstr "Criada em"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.account_assert_form
msgid "Description"
msgstr "Descrição"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__display_name
#: model:ir.model.fields,field_description:account_test.field_report_account_test_report_accounttest__display_name
msgid "Display Name"
msgstr "Nome a Exibir"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.account_assert_form
msgid "Expression"
msgstr "Expressão"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__id
#: model:ir.model.fields,field_description:account_test.field_report_account_test_report_accounttest__id
msgid "ID"
msgstr "Id."
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test____last_update
#: model:ir.model.fields,field_description:account_test.field_report_account_test_report_accounttest____last_update
msgid "Last Modified on"
msgstr "Última Modificação em"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__write_uid
msgid "Last Updated by"
msgstr "Última Atualização por"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__write_date
msgid "Last Updated on"
msgstr "Última Atualização em"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.account_assert_form
msgid "Python Code"
msgstr "Código Python"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__code_exec
msgid "Python code"
msgstr "Código em python"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__sequence
msgid "Sequence"
msgstr "Sequência"
#. module: account_test
#: model:accounting.assert.test,name:account_test.account_test_01
msgid "Test 1: General balance"
msgstr "Teste 1: Saldo geral"
#. module: account_test
#: model:accounting.assert.test,name:account_test.account_test_03
msgid "Test 3: Movement lines"
msgstr "Teste 3: Linhas de movimento"
#. module: account_test
#: model:accounting.assert.test,name:account_test.account_test_05
msgid ""
"Test 5.1 : Payable and Receivable accountant lines of reconciled invoices"
msgstr ""
"Teste 5.1 : Linhas de contabilidade 'A Pagar' e 'A Receber' das faturas "
"reconciliadas"
#. module: account_test
#: model:accounting.assert.test,name:account_test.account_test_05_2
msgid "Test 5.2 : Reconcilied invoices and Payable/Receivable accounts"
msgstr "Teste 5.2 : Faturas reconciliadas e contas 'A Pagar' / 'A Receber'"
#. module: account_test
#: model:accounting.assert.test,name:account_test.account_test_06
msgid "Test 6 : Invoices status"
msgstr "Teste 6 : Estado de Faturas"
#. module: account_test
#: model:accounting.assert.test,name:account_test.account_test_07
msgid "Test 7 : Closing balance on bank statements"
msgstr "Teste 7 : Saldo final nos extratos bancários"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__desc
msgid "Test Description"
msgstr "Descrição do teste"
#. module: account_test
#: model:ir.model.fields,field_description:account_test.field_accounting_assert_test__name
msgid "Test Name"
msgstr "Nome de teste"
#. module: account_test
#: model_terms:ir.ui.view,arch_db:account_test.account_assert_form
#: model_terms:ir.ui.view,arch_db:account_test.account_assert_tree
msgid "Tests"
msgstr "Testes"
#. module: account_test
#: code:addons/account_test/report/report_account_test.py:53
#, python-format
msgid "The test was passed successfully"
msgstr "O teste passou com êxito"
| {
"pile_set_name": "Github"
} |
module ActiveRecord
module AttributeMethods #:nodoc:
DEFAULT_SUFFIXES = %w(= ? _before_type_cast)
ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
def self.included(base)
base.extend ClassMethods
base.attribute_method_suffix(*DEFAULT_SUFFIXES)
base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
base.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false
base.time_zone_aware_attributes = false
base.class_inheritable_accessor :skip_time_zone_conversion_for_attributes, :instance_writer => false
base.skip_time_zone_conversion_for_attributes = []
end
# Declare and check for suffixed attribute methods.
module ClassMethods
# Declares a method available for all attributes with the given suffix.
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method
#
# #{attr}#{suffix}(*args, &block)
#
# to
#
# attribute#{suffix}(#{attr}, *args, &block)
#
# An <tt>attribute#{suffix}</tt> instance method must exist and accept at least
# the +attr+ argument.
#
# For example:
#
# class Person < ActiveRecord::Base
# attribute_method_suffix '_changed?'
#
# private
# def attribute_changed?(attr)
# ...
# end
# end
#
# person = Person.find(1)
# person.name_changed? # => false
# person.name = 'Hubert'
# person.name_changed? # => true
def attribute_method_suffix(*suffixes)
attribute_method_suffixes.concat suffixes
rebuild_attribute_method_regexp
end
# Returns MatchData if method_name is an attribute method.
def match_attribute_method?(method_name)
rebuild_attribute_method_regexp unless defined?(@@attribute_method_regexp) && @@attribute_method_regexp
@@attribute_method_regexp.match(method_name)
end
# Contains the names of the generated attribute methods.
def generated_methods #:nodoc:
@generated_methods ||= Set.new
end
def generated_methods?
!generated_methods.empty?
end
# Generates all the attribute related methods for columns in the database
# accessors, mutators and query methods.
def define_attribute_methods
return if generated_methods?
columns_hash.each do |name, column|
unless instance_method_already_implemented?(name)
if self.serialized_attributes[name]
define_read_method_for_serialized_attribute(name)
elsif create_time_zone_conversion_attribute?(name, column)
define_read_method_for_time_zone_conversion(name)
else
define_read_method(name.to_sym, name, column)
end
end
unless instance_method_already_implemented?("#{name}=")
if create_time_zone_conversion_attribute?(name, column)
define_write_method_for_time_zone_conversion(name)
else
define_write_method(name.to_sym)
end
end
unless instance_method_already_implemented?("#{name}?")
define_question_method(name)
end
end
end
# Checks whether the method is defined in the model or any of its subclasses
# that also derive from Active Record. Raises DangerousAttributeError if the
# method is defined by Active Record though.
def instance_method_already_implemented?(method_name)
method_name = method_name.to_s
return true if method_name =~ /^id(=$|\?$|$)/
@_defined_class_methods ||= ancestors.first(ancestors.index(ActiveRecord::Base)).sum([]) { |m| m.public_instance_methods(false) | m.private_instance_methods(false) | m.protected_instance_methods(false) }.map(&:to_s).to_set
@@_defined_activerecord_methods ||= (ActiveRecord::Base.public_instance_methods(false) | ActiveRecord::Base.private_instance_methods(false) | ActiveRecord::Base.protected_instance_methods(false)).map(&:to_s).to_set
raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord" if @@_defined_activerecord_methods.include?(method_name)
@_defined_class_methods.include?(method_name)
end
alias :define_read_methods :define_attribute_methods
# +cache_attributes+ allows you to declare which converted attribute values should
# be cached. Usually caching only pays off for attributes with expensive conversion
# methods, like time related columns (e.g. +created_at+, +updated_at+).
def cache_attributes(*attribute_names)
attribute_names.each {|attr| cached_attributes << attr.to_s}
end
# Returns the attributes which are cached. By default time related columns
# with datatype <tt>:datetime, :timestamp, :time, :date</tt> are cached.
def cached_attributes
@cached_attributes ||=
columns.select{|c| attribute_types_cached_by_default.include?(c.type)}.map(&:name).to_set
end
# Returns +true+ if the provided attribute is being cached.
def cache_attribute?(attr_name)
cached_attributes.include?(attr_name)
end
private
# Suffixes a, ?, c become regexp /(a|\?|c)$/
def rebuild_attribute_method_regexp
suffixes = attribute_method_suffixes.map { |s| Regexp.escape(s) }
@@attribute_method_regexp = /(#{suffixes.join('|')})$/.freeze
end
# Default to =, ?, _before_type_cast
def attribute_method_suffixes
@@attribute_method_suffixes ||= []
end
def create_time_zone_conversion_attribute?(name, column)
time_zone_aware_attributes && !skip_time_zone_conversion_for_attributes.include?(name.to_sym) && [:datetime, :timestamp].include?(column.type)
end
# Define an attribute reader method. Cope with nil column.
def define_read_method(symbol, attr_name, column)
cast_code = column.type_cast_code('v') if column
access_code = cast_code ? "(v=@attributes['#{attr_name}']) && #{cast_code}" : "@attributes['#{attr_name}']"
unless attr_name.to_s == self.primary_key.to_s
access_code = access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ")
end
if cache_attribute?(attr_name)
access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})"
end
evaluate_attribute_method attr_name, "def #{symbol}; #{access_code}; end"
end
# Define read method for serialized attribute.
def define_read_method_for_serialized_attribute(attr_name)
evaluate_attribute_method attr_name, "def #{attr_name}; unserialize_attribute('#{attr_name}'); end"
end
# Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
# This enhanced read method automatically converts the UTC time stored in the database to the time zone stored in Time.zone.
def define_read_method_for_time_zone_conversion(attr_name)
method_body = <<-EOV
def #{attr_name}(reload = false)
cached = @attributes_cache['#{attr_name}']
return cached if cached && !reload
time = read_attribute('#{attr_name}')
@attributes_cache['#{attr_name}'] = time.acts_like?(:time) ? time.in_time_zone : time
end
EOV
evaluate_attribute_method attr_name, method_body
end
# Defines a predicate method <tt>attr_name?</tt>.
def define_question_method(attr_name)
evaluate_attribute_method attr_name, "def #{attr_name}?; query_attribute('#{attr_name}'); end", "#{attr_name}?"
end
def define_write_method(attr_name)
evaluate_attribute_method attr_name, "def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end", "#{attr_name}="
end
# Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
# This enhanced write method will automatically convert the time passed to it to the zone stored in Time.zone.
def define_write_method_for_time_zone_conversion(attr_name)
method_body = <<-EOV
def #{attr_name}=(time)
unless time.acts_like?(:time)
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
end
time = time.in_time_zone rescue nil if time
write_attribute(:#{attr_name}, time)
end
EOV
evaluate_attribute_method attr_name, method_body, "#{attr_name}="
end
# Evaluate the definition for an attribute related method
def evaluate_attribute_method(attr_name, method_definition, method_name=attr_name)
unless method_name.to_s == primary_key.to_s
generated_methods << method_name
end
begin
class_eval(method_definition, __FILE__, __LINE__)
rescue SyntaxError => err
generated_methods.delete(attr_name)
if logger
logger.warn "Exception occurred during reader method compilation."
logger.warn "Maybe #{attr_name} is not a valid Ruby identifier?"
logger.warn err.message
end
end
end
end # ClassMethods
# Allows access to the object attributes, which are held in the <tt>@attributes</tt> hash, as though they
# were first-class methods. So a Person class with a name attribute can use Person#name and
# Person#name= and never directly use the attributes hash -- except for multiple assigns with
# ActiveRecord#attributes=. A Milestone class can also ask Milestone#completed? to test that
# the completed attribute is not +nil+ or 0.
#
# It's also possible to instantiate related objects, so a Client class belonging to the clients
# table with a +master_id+ foreign key can instantiate master through Client#master.
def method_missing(method_id, *args, &block)
method_name = method_id.to_s
if self.class.private_method_defined?(method_name)
raise NoMethodError.new("Attempt to call private method", method_name, args)
end
# If we haven't generated any methods yet, generate them, then
# see if we've created the method we're looking for.
if !self.class.generated_methods?
self.class.define_attribute_methods
if self.class.generated_methods.include?(method_name)
return self.send(method_id, *args, &block)
end
end
if self.class.primary_key.to_s == method_name
id
elsif md = self.class.match_attribute_method?(method_name)
attribute_name, method_type = md.pre_match, md.to_s
if @attributes.include?(attribute_name)
__send__("attribute#{method_type}", attribute_name, *args, &block)
else
super
end
elsif @attributes.include?(method_name)
read_attribute(method_name)
else
super
end
end
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
def read_attribute(attr_name)
attr_name = attr_name.to_s
if !(value = @attributes[attr_name]).nil?
if column = column_for_attribute(attr_name)
if unserializable_attribute?(attr_name, column)
unserialize_attribute(attr_name)
else
column.type_cast(value)
end
else
value
end
else
nil
end
end
def read_attribute_before_type_cast(attr_name)
@attributes[attr_name]
end
# Returns true if the attribute is of a text column and marked for serialization.
def unserializable_attribute?(attr_name, column)
column.text? && self.class.serialized_attributes[attr_name]
end
# Returns the unserialized object of the attribute.
def unserialize_attribute(attr_name)
unserialized_object = object_from_yaml(@attributes[attr_name])
if unserialized_object.is_a?(self.class.serialized_attributes[attr_name]) || unserialized_object.nil?
@attributes.frozen? ? unserialized_object : @attributes[attr_name] = unserialized_object
else
raise SerializationTypeMismatch,
"#{attr_name} was supposed to be a #{self.class.serialized_attributes[attr_name]}, but was a #{unserialized_object.class.to_s}"
end
end
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings for fixnum and float
# columns are turned into +nil+.
def write_attribute(attr_name, value)
attr_name = attr_name.to_s
@attributes_cache.delete(attr_name)
if (column = column_for_attribute(attr_name)) && column.number?
@attributes[attr_name] = convert_number_column_value(value)
else
@attributes[attr_name] = value
end
end
def query_attribute(attr_name)
unless value = read_attribute(attr_name)
false
else
column = self.class.columns_hash[attr_name]
if column.nil?
if Numeric === value || value !~ /[^0-9]/
!value.to_i.zero?
else
return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
!value.blank?
end
elsif column.number?
!value.zero?
else
!value.blank?
end
end
end
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
# which will all return +true+.
alias :respond_to_without_attributes? :respond_to?
def respond_to?(method, include_private_methods = false)
method_name = method.to_s
if super
return true
elsif !include_private_methods && super(method, true)
# If we're here than we haven't found among non-private methods
# but found among all methods. Which means that given method is private.
return false
elsif !self.class.generated_methods?
self.class.define_attribute_methods
if self.class.generated_methods.include?(method_name)
return true
end
end
if @attributes.nil?
return super
elsif @attributes.include?(method_name)
return true
elsif md = self.class.match_attribute_method?(method_name)
return true if @attributes.include?(md.pre_match)
end
super
end
private
def missing_attribute(attr_name, stack)
raise ActiveRecord::MissingAttributeError, "missing attribute: #{attr_name}", stack
end
# Handle *? for method_missing.
def attribute?(attribute_name)
query_attribute(attribute_name)
end
# Handle *= for method_missing.
def attribute=(attribute_name, value)
write_attribute(attribute_name, value)
end
# Handle *_before_type_cast for method_missing.
def attribute_before_type_cast(attribute_name)
read_attribute_before_type_cast(attribute_name)
end
end
end
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Defines utilities for the Timestamp and Duration well known types.
#ifndef GOOGLE_PROTOBUF_UTIL_TIME_UTIL_H__
#define GOOGLE_PROTOBUF_UTIL_TIME_UTIL_H__
#include <ctime>
#include <ostream>
#include <string>
#ifdef _MSC_VER
#include <winsock2.h>
#else
#include <sys/time.h>
#endif
#include <google/protobuf/duration.pb.h>
#include <google/protobuf/timestamp.pb.h>
namespace google {
namespace protobuf {
namespace util {
// Utility functions for Timestamp and Duration.
class LIBPROTOBUF_EXPORT TimeUtil {
typedef google::protobuf::Timestamp Timestamp;
typedef google::protobuf::Duration Duration;
public:
// The min/max Timestamp/Duration values we support.
//
// For "0001-01-01T00:00:00Z".
static const int64 kTimestampMinSeconds = -62135596800LL;
// For "9999-12-31T23:59:59.999999999Z".
static const int64 kTimestampMaxSeconds = 253402300799LL;
static const int64 kDurationMinSeconds = -315576000000LL;
static const int64 kDurationMaxSeconds = 315576000000LL;
// Converts Timestamp to/from RFC 3339 date string format.
// Generated output will always be Z-normalized and uses 3, 6 or 9
// fractional digits as required to represent the exact time. When
// parsing, any fractional digits (or none) and any offset are
// accepted as long as they fit into nano-seconds precision.
// Note that Timestamp can only represent time from
// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. Converting
// a Timestamp outside of this range is undefined behavior.
// See https://www.ietf.org/rfc/rfc3339.txt
//
// Example of generated format:
// "1972-01-01T10:00:20.021Z"
//
// Example of accepted format:
// "1972-01-01T10:00:20.021-05:00"
static string ToString(const Timestamp& timestamp);
static bool FromString(const string& value, Timestamp* timestamp);
// Converts Duration to/from string format. The string format will contains
// 3, 6, or 9 fractional digits depending on the precision required to
// represent the exact Duration value. For example:
// "1s", "1.010s", "1.000000100s", "-3.100s"
// The range that can be represented by Duration is from -315,576,000,000
// to +315,576,000,000 inclusive (in seconds).
static string ToString(const Duration& duration);
static bool FromString(const string& value, Duration* timestamp);
#ifdef GetCurrentTime
#undef GetCurrentTime // Visual Studio has macro GetCurrentTime
#endif
// Gets the current UTC time.
static Timestamp GetCurrentTime();
// Returns the Time representing "1970-01-01 00:00:00".
static Timestamp GetEpoch();
// Converts between Duration and integer types. The behavior is undefined if
// the input value is not in the valid range of Duration.
static Duration NanosecondsToDuration(int64 nanos);
static Duration MicrosecondsToDuration(int64 micros);
static Duration MillisecondsToDuration(int64 millis);
static Duration SecondsToDuration(int64 seconds);
static Duration MinutesToDuration(int64 minutes);
static Duration HoursToDuration(int64 hours);
// Result will be truncated towards zero. For example, "-1.5s" will be
// truncated to "-1s", and "1.5s" to "1s" when converting to seconds.
// It's undefined behavior if the input duration is not valid or the result
// exceeds the range of int64. A duration is not valid if it's not in the
// valid range of Duration, or have an invalid nanos value (i.e., larger
// than 999999999, less than -999999999, or have a different sign from the
// seconds part).
static int64 DurationToNanoseconds(const Duration& duration);
static int64 DurationToMicroseconds(const Duration& duration);
static int64 DurationToMilliseconds(const Duration& duration);
static int64 DurationToSeconds(const Duration& duration);
static int64 DurationToMinutes(const Duration& duration);
static int64 DurationToHours(const Duration& duration);
// Creates Timestamp from integer types. The integer value indicates the
// time elapsed from Epoch time. The behavior is undefined if the input
// value is not in the valid range of Timestamp.
static Timestamp NanosecondsToTimestamp(int64 nanos);
static Timestamp MicrosecondsToTimestamp(int64 micros);
static Timestamp MillisecondsToTimestamp(int64 millis);
static Timestamp SecondsToTimestamp(int64 seconds);
// Result will be truncated down to the nearest integer value. For example,
// with "1969-12-31T23:59:59.9Z", TimestampToMilliseconds() returns -100
// and TimestampToSeconds() returns -1. It's undefined behavior if the input
// Timestamp is not valid (i.e., its seconds part or nanos part does not fall
// in the valid range) or the return value doesn't fit into int64.
static int64 TimestampToNanoseconds(const Timestamp& timestamp);
static int64 TimestampToMicroseconds(const Timestamp& timestamp);
static int64 TimestampToMilliseconds(const Timestamp& timestamp);
static int64 TimestampToSeconds(const Timestamp& timestamp);
// Conversion to/from other time/date types. Note that these types may
// have a different precision and time range from Timestamp/Duration.
// When converting to a lower precision type, the value will be truncated
// to the nearest value that can be represented. If the value is
// out of the range of the result type, the return value is undefined.
//
// Conversion to/from time_t
static Timestamp TimeTToTimestamp(time_t value);
static time_t TimestampToTimeT(const Timestamp& value);
// Conversion to/from timeval
static Timestamp TimevalToTimestamp(const timeval& value);
static timeval TimestampToTimeval(const Timestamp& value);
static Duration TimevalToDuration(const timeval& value);
static timeval DurationToTimeval(const Duration& value);
};
} // namespace util
} // namespace protobuf
namespace protobuf {
// Overloaded operators for Duration.
//
// Assignment operators.
LIBPROTOBUF_EXPORT Duration& operator+=(Duration& d1, const Duration& d2); // NOLINT
LIBPROTOBUF_EXPORT Duration& operator-=(Duration& d1, const Duration& d2); // NOLINT
LIBPROTOBUF_EXPORT Duration& operator*=(Duration& d, int64 r); // NOLINT
LIBPROTOBUF_EXPORT Duration& operator*=(Duration& d, double r); // NOLINT
LIBPROTOBUF_EXPORT Duration& operator/=(Duration& d, int64 r); // NOLINT
LIBPROTOBUF_EXPORT Duration& operator/=(Duration& d, double r); // NOLINT
// Overload for other integer types.
template <typename T>
Duration& operator*=(Duration& d, T r) { // NOLINT
int64 x = r;
return d *= x;
}
template <typename T>
Duration& operator/=(Duration& d, T r) { // NOLINT
int64 x = r;
return d /= x;
}
LIBPROTOBUF_EXPORT Duration& operator%=(Duration& d1, const Duration& d2); // NOLINT
// Relational operators.
inline bool operator<(const Duration& d1, const Duration& d2) {
if (d1.seconds() == d2.seconds()) {
return d1.nanos() < d2.nanos();
}
return d1.seconds() < d2.seconds();
}
inline bool operator>(const Duration& d1, const Duration& d2) {
return d2 < d1;
}
inline bool operator>=(const Duration& d1, const Duration& d2) {
return !(d1 < d2);
}
inline bool operator<=(const Duration& d1, const Duration& d2) {
return !(d2 < d1);
}
inline bool operator==(const Duration& d1, const Duration& d2) {
return d1.seconds() == d2.seconds() && d1.nanos() == d2.nanos();
}
inline bool operator!=(const Duration& d1, const Duration& d2) {
return !(d1 == d2);
}
// Additive operators
inline Duration operator-(const Duration& d) {
Duration result;
result.set_seconds(-d.seconds());
result.set_nanos(-d.nanos());
return result;
}
inline Duration operator+(const Duration& d1, const Duration& d2) {
Duration result = d1;
return result += d2;
}
inline Duration operator-(const Duration& d1, const Duration& d2) {
Duration result = d1;
return result -= d2;
}
// Multiplicative operators
template<typename T>
inline Duration operator*(Duration d, T r) {
return d *= r;
}
template<typename T>
inline Duration operator*(T r, Duration d) {
return d *= r;
}
template<typename T>
inline Duration operator/(Duration d, T r) {
return d /= r;
}
LIBPROTOBUF_EXPORT int64 operator/(const Duration& d1, const Duration& d2);
inline Duration operator%(const Duration& d1, const Duration& d2) {
Duration result = d1;
return result %= d2;
}
inline std::ostream& operator<<(std::ostream& out, const Duration& d) {
out << google::protobuf::util::TimeUtil::ToString(d);
return out;
}
// Overloaded operators for Timestamp
//
// Assignement operators.
LIBPROTOBUF_EXPORT Timestamp& operator+=(Timestamp& t, const Duration& d); // NOLINT
LIBPROTOBUF_EXPORT Timestamp& operator-=(Timestamp& t, const Duration& d); // NOLINT
// Relational operators.
inline bool operator<(const Timestamp& t1, const Timestamp& t2) {
if (t1.seconds() == t2.seconds()) {
return t1.nanos() < t2.nanos();
}
return t1.seconds() < t2.seconds();
}
inline bool operator>(const Timestamp& t1, const Timestamp& t2) {
return t2 < t1;
}
inline bool operator>=(const Timestamp& t1, const Timestamp& t2) {
return !(t1 < t2);
}
inline bool operator<=(const Timestamp& t1, const Timestamp& t2) {
return !(t2 < t1);
}
inline bool operator==(const Timestamp& t1, const Timestamp& t2) {
return t1.seconds() == t2.seconds() && t1.nanos() == t2.nanos();
}
inline bool operator!=(const Timestamp& t1, const Timestamp& t2) {
return !(t1 == t2);
}
// Additive operators.
inline Timestamp operator+(const Timestamp& t, const Duration& d) {
Timestamp result = t;
return result += d;
}
inline Timestamp operator+(const Duration& d, const Timestamp& t) {
Timestamp result = t;
return result += d;
}
inline Timestamp operator-(const Timestamp& t, const Duration& d) {
Timestamp result = t;
return result -= d;
}
LIBPROTOBUF_EXPORT Duration operator-(const Timestamp& t1, const Timestamp& t2);
inline std::ostream& operator<<(std::ostream& out, const Timestamp& t) {
out << google::protobuf::util::TimeUtil::ToString(t);
return out;
}
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_UTIL_TIME_UTIL_H__
| {
"pile_set_name": "Github"
} |
/**
* Simplified Chinese translation for bootstrap-datepicker
* Yuan Cheung <[email protected]>
*/
;(function($){
$.fn.datepicker.dates['zh-CN'] = {
days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
daysMin: ["日", "一", "二", "三", "四", "五", "六"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
today: "今日",
clear: "清除",
format: "yyyy年mm月dd日",
titleFormat: "yyyy年mm月",
weekStart: 1
};
}(jQuery));
| {
"pile_set_name": "Github"
} |
/******************************************************************************
* Copyright (c) 2008 - 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Ungar, IBM Research - Initial Implementation
* Sam Adams, IBM Research - Initial Implementation
* Stefan Marr, Vrije Universiteit Brussel - Port to x86 Multi-Core Systems
******************************************************************************/
const int Tag_Size = 1;
const int Tag_Mask = 1;
const int Int_Tag = 1;
const int Mem_Tag = 0;
| {
"pile_set_name": "Github"
} |
# RFC: Improved Customization of Composite Layers
* **Authors**: Ib Green, Xiaoji Chen
* **Date**: Jan 2019
* **Status**: Draft
## Motivation
deck.gl has strong support for customizing primitive layers, for instance through subclassing and modifying shaders. But things get harder when those shaders are access through a composite layer.
### Proposal: CompositeLayers document which sub layers they render
Each composite layer will be expected to document names for its sublayers. This makes it possible for applications to specify overrides for particular layers.
There are two types of naming possible
- name the actual layer types being rendered: Scatterplot, Path, Polygon in the case of GeoJSON
- name the actual layer instances being rendered (Points, Lines, PolygonOutlines, ExtrudedPolygons, ...)
**QUESTION** - Pick one of these schemes, or support both?
### Proposal: CompositeLayers take a new prop `transferAllProps`
* Currently composite layers carefully pick what props to forward.
* This was done deliberately to ensure a more rigid interface specification for layers.
* When replacing sublayers with custom layers, it can be critical to be able to supply a new prop.
The `forwardBaseLayerProps()` method could check for `transferAllProps`
### Proposal: CompositeLayers take a new `subLayerProps` prop
The `subLayerProps` prop would be a recursive object. The keys are sublayer ids and the values are object of props to override. A special prop `type` can be used to override the default layer constructor.
In application:
```js
const customizedGeoJsonLayer = new GeoJsonLayer({
...,
transferAllProps: true,
subLayerProps: {
points: {
type: ExtendedScatterplotLayer,
extendedProp: 100
},
'polygons-fill': {
subLayerProps: { // Recursive application of sublayerProps!
fill: {
type: HollowPolygonLayer
}
}
}
}
})
```
#### Changes to the CompositeLayer API
**getSubLayerProps**
The overriding props supplied by the user can be merged inside `compositeLayer.getSubLayerProps` so that each layer does not have to implement their own handling of `subLayerProps`.
**getSubLayerClass**
A new CompositeLayer class method that extracts the `type` field from `subLayerProps`, if any. This will replace the ad-hoc implementations in e.g. [HexagonLayer](https://github.com/visgl/deck.gl/blob/6.3-release/modules/layers/src/hexagon-layer/hexagon-layer.js#L396) and [GeoJsonLayer](https://github.com/visgl/deck.gl/blob/6.3-release/modules/layers/src/geojson-layer/geojson-layer.js#L71).
#### Open Questions
**Should keys be layer class name or sublayer id?**
Composite layers may render multiple sublayers of the same type. For example, the GeoJsonLayer renders two `PathLayer` instances, one for polygon outlines and one for line strings. Differentiating them with unique ids would give the user finer grain control.
**How do user props merge with props created by the parent layer?**
In `getSubLayerProps`, external overriding props supplied via `subLayerProps` always override those generated by the composite layer.
As a general rule, all sublayer props should be kept overridable.
However, layers can prevent override of props using the following mechanism:
```js
renderLayers() {
const SubLayer = new this.getSubLayerClass('child-layer', ScatterplotLayer);
return new SubLayer(
// where subLayerProps are merged in
this.getSubLayerProps({
id: 'child-layer',
// "overridable" props
stroked: this.props.stroked,
filled: this.props.filled
}),
{
// "non-overridable" props
data: this.state.data,
getPosition: d => d.point
}
);
}
```
In this case, the "non-overridable" props are the ones generated internally by the parent layer (e.g. the aggregated data in a HexagonLayer), as well as the accessors that target that specific format. These are considered private implementation of the composite layer, never documentated and may change between patch releases, therefore preventing the users from overriding them is reasonable.
**Creating new Layers by overriding sublayers in an existing composite Layer**
It is possible to use this mechanism to creating a new layer by overriding layer props in an existing composite layer. In this case, the resulting sublayers would not be overridable. If an overridable layer is desired, the original composite layer will need to be extended into a new class.
| {
"pile_set_name": "Github"
} |
.es-admin-container-down{
margin-top:52px;
}
.es-admin-alert{
margin-bottom: 0;
} | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="dns-prefetch" href="https://github.githubassets.com">
<link rel="dns-prefetch" href="https://avatars0.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars1.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars2.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars3.githubusercontent.com">
<link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">
<link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">
<link crossorigin="anonymous" media="all" integrity="sha512-pWLt6abkYhNeAHaDrPVG0yXCtIGRuCkwSUqQpsyN6smAIpIt+Iuq2IZKmoH9l3Cy/9ZnjvVrFZnvFFjGiqE3EA==" rel="stylesheet" href="https://github.githubassets.com/assets/frameworks-a3b8a10d4a9e37a78f033ef4a4f525f5.css" />
<link crossorigin="anonymous" media="all" integrity="sha512-jcxTrbrSk8025WF8eJeKqN7LkuqJ/U9RqXsZE9K/GTnmeP4U98OquugL7we+CAL/+6xqWzN4G571+zLgn/wxbg==" rel="stylesheet" href="https://github.githubassets.com/assets/github-7ce4804f585323ae749a0f401b09c6e0.css" />
<meta name="viewport" content="width=device-width">
<title>material-design-icons/material-icons.css at master · google/material-design-icons</title>
<meta name="description" content="Material Design icons by Google. Contribute to google/material-design-icons development by creating an account on GitHub.">
<link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub">
<link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub">
<meta property="fb:app_id" content="1401488693436528">
<meta property="og:image" content="https://avatars0.githubusercontent.com/u/1342004?s=400&v=4" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="google/material-design-icons" /><meta property="og:url" content="https://github.com/google/material-design-icons" /><meta property="og:description" content="Material Design icons by Google. Contribute to google/material-design-icons development by creating an account on GitHub." />
<link rel="assets" href="https://github.githubassets.com/">
<link rel="web-socket" href="wss://live.github.com/_sockets/VjI6MzA0NjU5ODgyOmZkOTUyNDVmNDRiMmQ3YjgxNGI0NGM0MTdhMzNmZDk4NjJhMzE0OTY5OTFlNGViOTJlYWVhMmZhZWQ3YjAxYjU=--80c8e034b6fb88635cf6f57876e926ffa1e7b8c5">
<meta name="pjax-timeout" content="1000">
<link rel="sudo-modal" href="/sessions/sudo_modal">
<meta name="request-id" content="EA61:2CDA2:15B1CD4:207BD36:5C5D8C07" data-pjax-transient>
<meta name="selected-link" value="repo_source" data-pjax-transient>
<meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU">
<meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA">
<meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc">
<meta name="octolytics-host" content="collector.githubapp.com" /><meta name="octolytics-app-id" content="github" /><meta name="octolytics-event-url" content="https://collector.githubapp.com/github-external/browser_event" /><meta name="octolytics-dimension-request_id" content="EA61:2CDA2:15B1CD4:207BD36:5C5D8C07" /><meta name="octolytics-dimension-region_edge" content="ams" /><meta name="octolytics-dimension-region_render" content="iad" /><meta name="octolytics-actor-id" content="7072278" /><meta name="octolytics-actor-login" content="richturner" /><meta name="octolytics-actor-hash" content="6966a709251ec4933efc7a9a944c6f1caa1f624db5955dee031065221bcdcdc0" />
<meta name="analytics-location" content="/<user-name>/<repo-name>/blob/show" data-pjax-transient="true" />
<meta name="google-analytics" content="UA-3769691-2">
<meta class="js-ga-set" name="userId" content="eb1dbcbfaf7af9ce648d3241436aa474">
<meta class="js-ga-set" name="dimension1" content="Logged In">
<meta name="hostname" content="github.com">
<meta name="user-login" content="richturner">
<meta name="expected-hostname" content="github.com">
<meta name="js-proxy-site-detection-payload" content="ZGJiMmJjZjkwNmVlMzIyMzUwMDAzNGUxYzFhZDUyNGFmNDRkYTU0YzA0M2FiMTM1YjI2NTlmZTY1MDQxMDg1NHx7InJlbW90ZV9hZGRyZXNzIjoiODAuMjI5LjE2NC4yMjIiLCJyZXF1ZXN0X2lkIjoiRUE2MToyQ0RBMjoxNUIxQ0Q0OjIwN0JEMzY6NUM1RDhDMDciLCJ0aW1lc3RhbXAiOjE1NDk2MzQ1NzMsImhvc3QiOiJnaXRodWIuY29tIn0=">
<meta name="enabled-features" content="UNIVERSE_BANNER,MARKETPLACE_PLAN_RESTRICTION_EDITOR,NOTIFY_ON_BLOCK,RELATED_ISSUES,MARKETPLACE_BROWSING_V2,MARKETPLACE_INSIGHTS_V2,LAZY_JAVASCRIPT">
<meta name="html-safe-nonce" content="bfc23a7c035e6d51e897871e2e0170005bc960ab">
<meta http-equiv="x-pjax-version" content="294669a3459b1e9fa48981567a1bc312">
<link href="https://github.com/google/material-design-icons/commits/master.atom" rel="alternate" title="Recent Commits to material-design-icons:master" type="application/atom+xml">
<meta name="go-import" content="github.com/google/material-design-icons git https://github.com/google/material-design-icons.git">
<meta name="octolytics-dimension-user_id" content="1342004" /><meta name="octolytics-dimension-user_login" content="google" /><meta name="octolytics-dimension-repository_id" content="24953448" /><meta name="octolytics-dimension-repository_nwo" content="google/material-design-icons" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="24953448" /><meta name="octolytics-dimension-repository_network_root_nwo" content="google/material-design-icons" /><meta name="octolytics-dimension-repository_explore_github_marketplace_ci_cta_shown" content="false" />
<link rel="canonical" href="https://github.com/google/material-design-icons/blob/master/iconfont/material-icons.css" data-pjax-transient>
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000">
<link rel="icon" type="image/x-icon" class="js-site-favicon" href="https://github.githubassets.com/favicon.ico">
<meta name="theme-color" content="#1e2327">
<meta name="u2f-support" content="true">
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-in env-production page-blob">
<div class="position-relative js-header-wrapper ">
<a href="#start-of-content" tabindex="1" class="p-3 bg-blue text-white show-on-focus js-skip-to-content">Skip to content</a>
<div id="js-pjax-loader-bar" class="pjax-loader-bar"><div class="progress"></div></div>
<header class="Header f5" role="banner">
<div class="d-flex flex-justify-between px-3 ">
<div class="d-flex flex-justify-between ">
<div class="">
<a class="header-logo-invertocat" href="https://github.com/" data-hotkey="g d" aria-label="Homepage" data-ga-click="Header, go to dashboard, icon:logo">
<svg height="32" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
</a>
</div>
</div>
<div class="HeaderMenu d-flex flex-justify-between flex-auto">
<nav class="d-flex" aria-label="Global">
<div class="">
<div class="header-search scoped-search site-scoped-search js-site-search position-relative js-jump-to"
role="combobox"
aria-owns="jump-to-results"
aria-label="Search or jump to"
aria-haspopup="listbox"
aria-expanded="false"
>
<div class="position-relative">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="js-site-search-form" data-scope-type="Repository" data-scope-id="24953448" data-scoped-search-url="/google/material-design-icons/search" data-unscoped-search-url="/search" action="/google/material-design-icons/search" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" />
<label class="form-control header-search-wrapper header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center js-chromeless-input-container">
<input type="text"
class="form-control header-search-input jump-to-field js-jump-to-field js-site-search-focus js-site-search-field is-clearable"
data-hotkey="s,/"
name="q"
value=""
placeholder="Search or jump to…"
data-unscoped-placeholder="Search or jump to…"
data-scoped-placeholder="Search or jump to…"
autocapitalize="off"
aria-autocomplete="list"
aria-controls="jump-to-results"
aria-label="Search or jump to…"
data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations#csrf-token=OtyDjJ7LYv3WWhotUSvulateIv+dvmD3I3Gr1Ags69Uo0yg+BTaNEQ4cszQvGYcswym9cf/i1CUFaJYfZ3E8yg=="
spellcheck="false"
autocomplete="off"
>
<input type="hidden" class="js-site-search-type-field" name="type" >
<img src="https://github.githubassets.com/images/search-key-slash.svg" alt="" class="mr-2 header-search-key-slash">
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<ul class="d-none js-jump-to-suggestions-template-container">
<li class="d-flex flex-justify-start flex-items-center p-0 f5 navigation-item js-navigation-item js-jump-to-suggestion" role="option">
<a tabindex="-1" class="no-underline d-flex flex-auto flex-items-center jump-to-suggestions-path js-jump-to-suggestion-path js-navigation-open p-2" href="">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none">
<svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg>
<svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg>
<svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0 0 13 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 0 0 0-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"/></svg>
</div>
<img class="avatar mr-2 flex-shrink-0 js-jump-to-suggestion-avatar d-none" alt="" aria-label="Team" src="" width="28" height="28">
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target">
</div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search">
<span class="js-jump-to-badge-search-text-default d-none" aria-label="in this repository">
In this repository
</span>
<span class="js-jump-to-badge-search-text-global d-none" aria-label="in all of GitHub">
All GitHub
</span>
<span aria-hidden="true" class="d-inline-block ml-1 v-align-middle">↵</span>
</div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump">
Jump to
<span class="d-inline-block ml-1 v-align-middle">↵</span>
</div>
</a>
</li>
</ul>
<ul class="d-none js-jump-to-no-results-template-container">
<li class="d-flex flex-justify-center flex-items-center f5 d-none js-jump-to-suggestion p-2">
<span class="text-gray">No suggested jump to results</span>
</li>
</ul>
<ul id="jump-to-results" role="listbox" class="p-0 m-0 js-navigation-container jump-to-suggestions-results-container js-jump-to-suggestions-results-container">
<li class="d-flex flex-justify-start flex-items-center p-0 f5 navigation-item js-navigation-item js-jump-to-scoped-search d-none" role="option">
<a tabindex="-1" class="no-underline d-flex flex-auto flex-items-center jump-to-suggestions-path js-jump-to-suggestion-path js-navigation-open p-2" href="">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none">
<svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg>
<svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg>
<svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0 0 13 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 0 0 0-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"/></svg>
</div>
<img class="avatar mr-2 flex-shrink-0 js-jump-to-suggestion-avatar d-none" alt="" aria-label="Team" src="" width="28" height="28">
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target">
</div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search">
<span class="js-jump-to-badge-search-text-default d-none" aria-label="in this repository">
In this repository
</span>
<span class="js-jump-to-badge-search-text-global d-none" aria-label="in all of GitHub">
All GitHub
</span>
<span aria-hidden="true" class="d-inline-block ml-1 v-align-middle">↵</span>
</div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump">
Jump to
<span class="d-inline-block ml-1 v-align-middle">↵</span>
</div>
</a>
</li>
<li class="d-flex flex-justify-start flex-items-center p-0 f5 navigation-item js-navigation-item js-jump-to-global-search d-none" role="option">
<a tabindex="-1" class="no-underline d-flex flex-auto flex-items-center jump-to-suggestions-path js-jump-to-suggestion-path js-navigation-open p-2" href="">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none">
<svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg>
<svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg>
<svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0 0 13 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 0 0 0-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"/></svg>
</div>
<img class="avatar mr-2 flex-shrink-0 js-jump-to-suggestion-avatar d-none" alt="" aria-label="Team" src="" width="28" height="28">
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target">
</div>
<div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search">
<span class="js-jump-to-badge-search-text-default d-none" aria-label="in this repository">
In this repository
</span>
<span class="js-jump-to-badge-search-text-global d-none" aria-label="in all of GitHub">
All GitHub
</span>
<span aria-hidden="true" class="d-inline-block ml-1 v-align-middle">↵</span>
</div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump">
Jump to
<span class="d-inline-block ml-1 v-align-middle">↵</span>
</div>
</a>
</li>
<li class="d-flex flex-justify-center flex-items-center p-0 f5 js-jump-to-suggestion">
<img src="https://github.githubassets.com/images/spinners/octocat-spinner-128.gif" alt="Octocat Spinner Icon" class="m-2" width="28">
</li>
</ul>
</div>
</label>
</form> </div>
</div>
</div>
<ul class="d-flex pl-2 flex-items-center text-bold list-style-none">
<li>
<a class="js-selected-navigation-item HeaderNavlink px-2" data-hotkey="g p" data-ga-click="Header, click, Nav menu - item:pulls context:user" aria-label="Pull requests you created" data-selected-links="/pulls /pulls/assigned /pulls/mentioned /pulls" href="/pulls">
Pull requests
</a> </li>
<li>
<a class="js-selected-navigation-item HeaderNavlink px-2" data-hotkey="g i" data-ga-click="Header, click, Nav menu - item:issues context:user" aria-label="Issues you created" data-selected-links="/issues /issues/assigned /issues/mentioned /issues" href="/issues">
Issues
</a> </li>
<li class="position-relative">
<a class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:marketplace context:user" data-octo-click="marketplace_click" data-octo-dimensions="location:nav_bar" data-selected-links=" /marketplace" href="/marketplace">
Marketplace
</a>
</li>
<li>
<a class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:explore" data-selected-links="/explore /trending /trending/developers /integrations /integrations/feature/code /integrations/feature/collaborate /integrations/feature/ship showcases showcases_search showcases_landing /explore" href="/explore">
Explore
</a> </li>
</ul>
</nav>
<div class="d-flex">
<ul class="user-nav d-flex flex-items-center list-style-none" id="user-links">
<li class="dropdown">
<span class="d-inline-block px-2">
<a aria-label="You have unread notifications" class="notification-indicator tooltipped tooltipped-s js-socket-channel js-notification-indicator" data-hotkey="g n" data-ga-click="Header, go to notifications, icon:unread" data-channel="notification-changed:7072278" href="/notifications">
<span class="mail-status unread"></span>
<svg class="octicon octicon-bell" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14 12v1H0v-1l.73-.58c.77-.77.81-2.55 1.19-4.42C2.69 3.23 6 2 6 2c0-.55.45-1 1-1s1 .45 1 1c0 0 3.39 1.23 4.16 5 .38 1.88.42 3.66 1.19 4.42l.66.58H14zm-7 4c1.11 0 2-.89 2-2H5c0 1.11.89 2 2 2z"/></svg>
</a>
</span>
</li>
<li class="dropdown">
<details class="details-overlay details-reset d-flex px-2 flex-items-center">
<summary class="HeaderNavlink"
aria-label="Create new…"
data-ga-click="Header, create new, icon:add">
<svg class="octicon octicon-plus float-left mr-1 mt-1" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 9H7v5H5V9H0V7h5V2h2v5h5v2z"/></svg>
<span class="dropdown-caret mt-1"></span>
</summary>
<details-menu class="dropdown-menu dropdown-menu-sw">
<a role="menuitem" class="dropdown-item" href="/new" data-ga-click="Header, create new repository">
New repository
</a>
<a role="menuitem" class="dropdown-item" href="/new/import" data-ga-click="Header, import a repository">
Import repository
</a>
<a role="menuitem" class="dropdown-item" href="https://gist.github.com/" data-ga-click="Header, create new gist">
New gist
</a>
<a role="menuitem" class="dropdown-item" href="/organizations/new" data-ga-click="Header, create new organization">
New organization
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-header">
<span title="google/material-design-icons">This repository</span>
</div>
<a role="menuitem" class="dropdown-item" href="/google/material-design-icons/issues/new" data-ga-click="Header, create new issue">
New issue
</a>
</details-menu>
</details>
</li>
<li class="dropdown">
<details class="details-overlay details-reset d-flex pl-2 flex-items-center">
<summary class="HeaderNavlink name mt-1"
aria-label="View profile and more"
data-ga-click="Header, show menu, icon:avatar">
<img alt="@richturner" class="avatar float-left mr-1" src="https://avatars2.githubusercontent.com/u/7072278?s=40&v=4" height="20" width="20">
<span class="dropdown-caret"></span>
</summary>
<details-menu class="dropdown-menu dropdown-menu-sw">
<div class="header-nav-current-user css-truncate"><a role="menuitem" class="no-underline user-profile-link px-3 pt-2 pb-2 mb-n2 mt-n1 d-block" href="/richturner" data-ga-click="Header, go to profile, text:Signed in as">Signed in as <strong class="css-truncate-target">richturner</strong></a></div>
<div role="none" class="dropdown-divider"></div>
<div class="px-3 f6 user-status-container js-user-status-context pb-1" data-url="/users/status?compact=1&link_mentions=0&truncate=1">
<div class="js-user-status-container user-status-compact" data-team-hovercards-enabled>
<details class="js-user-status-details details-reset details-overlay details-overlay-dark">
<summary class="btn-link no-underline js-toggle-user-status-edit toggle-user-status-edit width-full" aria-haspopup="dialog" role="menuitem">
<div class="f6 d-inline-block v-align-middle user-status-emoji-only-header pl-0 circle lh-condensed user-status-header " style="max-width: 29px">
<div class="user-status-emoji-container flex-shrink-0 mr-1">
<svg class="octicon octicon-smiley" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm4.81 12.81a6.72 6.72 0 0 1-2.17 1.45c-.83.36-1.72.53-2.64.53-.92 0-1.81-.17-2.64-.53-.81-.34-1.55-.83-2.17-1.45a6.773 6.773 0 0 1-1.45-2.17A6.59 6.59 0 0 1 1.21 8c0-.92.17-1.81.53-2.64.34-.81.83-1.55 1.45-2.17.62-.62 1.36-1.11 2.17-1.45A6.59 6.59 0 0 1 8 1.21c.92 0 1.81.17 2.64.53.81.34 1.55.83 2.17 1.45.62.62 1.11 1.36 1.45 2.17.36.83.53 1.72.53 2.64 0 .92-.17 1.81-.53 2.64-.34.81-.83 1.55-1.45 2.17zM4 6.8v-.59c0-.66.53-1.19 1.2-1.19h.59c.66 0 1.19.53 1.19 1.19v.59c0 .67-.53 1.2-1.19 1.2H5.2C4.53 8 4 7.47 4 6.8zm5 0v-.59c0-.66.53-1.19 1.2-1.19h.59c.66 0 1.19.53 1.19 1.19v.59c0 .67-.53 1.2-1.19 1.2h-.59C9.53 8 9 7.47 9 6.8zm4 3.2c-.72 1.88-2.91 3-5 3s-4.28-1.13-5-3c-.14-.39.23-1 .66-1h8.59c.41 0 .89.61.75 1z"/></svg>
</div>
</div>
<div class="d-inline-block v-align-middle user-status-message-wrapper f6 lh-condensed ws-normal pt-1">
<span class="link-gray">Set your status</span>
</div>
</summary>
<details-dialog class="details-dialog rounded-1 anim-fade-in fast Box Box--overlay" role="dialog" tabindex="-1">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="position-relative flex-auto js-user-status-form" action="/users/status?compact=1&link_mentions=0&truncate=1" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="_method" value="put" /><input type="hidden" name="authenticity_token" value="zVMLLoNz5o3Q0pB6dKtNG6KYF9wMXVG5g3CB1QZC2i2O97Dui105zUCUJw2zoQ7/bDanAnsnbWXFib/APHl3pw==" />
<div class="Box-header bg-gray border-bottom p-3">
<button class="Box-btn-octicon js-toggle-user-status-edit btn-octicon float-right" type="reset" aria-label="Close dialog" data-close-dialog>
<svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg>
</button>
<h3 class="Box-title f5 text-bold text-gray-dark">Edit status</h3>
</div>
<input type="hidden" name="emoji" class="js-user-status-emoji-field" value="">
<input type="hidden" name="organization_id" class="js-user-status-org-id-field" value="">
<div class="px-3 py-2 text-gray-dark">
<div class="js-characters-remaining-container js-suggester-container position-relative mt-2">
<div class="input-group d-table form-group my-0 js-user-status-form-group">
<span class="input-group-button d-table-cell v-align-middle" style="width: 1%">
<button type="button" aria-label="Choose an emoji" class="btn-outline btn js-toggle-user-status-emoji-picker bg-white btn-open-emoji-picker">
<span class="js-user-status-original-emoji" hidden></span>
<span class="js-user-status-custom-emoji"></span>
<span class="js-user-status-no-emoji-icon" >
<svg class="octicon octicon-smiley" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm4.81 12.81a6.72 6.72 0 0 1-2.17 1.45c-.83.36-1.72.53-2.64.53-.92 0-1.81-.17-2.64-.53-.81-.34-1.55-.83-2.17-1.45a6.773 6.773 0 0 1-1.45-2.17A6.59 6.59 0 0 1 1.21 8c0-.92.17-1.81.53-2.64.34-.81.83-1.55 1.45-2.17.62-.62 1.36-1.11 2.17-1.45A6.59 6.59 0 0 1 8 1.21c.92 0 1.81.17 2.64.53.81.34 1.55.83 2.17 1.45.62.62 1.11 1.36 1.45 2.17.36.83.53 1.72.53 2.64 0 .92-.17 1.81-.53 2.64-.34.81-.83 1.55-1.45 2.17zM4 6.8v-.59c0-.66.53-1.19 1.2-1.19h.59c.66 0 1.19.53 1.19 1.19v.59c0 .67-.53 1.2-1.19 1.2H5.2C4.53 8 4 7.47 4 6.8zm5 0v-.59c0-.66.53-1.19 1.2-1.19h.59c.66 0 1.19.53 1.19 1.19v.59c0 .67-.53 1.2-1.19 1.2h-.59C9.53 8 9 7.47 9 6.8zm4 3.2c-.72 1.88-2.91 3-5 3s-4.28-1.13-5-3c-.14-.39.23-1 .66-1h8.59c.41 0 .89.61.75 1z"/></svg>
</span>
</button>
</span>
<input type="text" autocomplete="off" autofocus data-maxlength="80" class="js-suggester-field d-table-cell width-full form-control js-user-status-message-field js-characters-remaining-field" placeholder="What's happening?" name="message" required value="" aria-label="What is your current status?">
<div class="error">Could not update your status, please try again.</div>
</div>
<div class="suggester-container">
<div class="suggester js-suggester js-navigation-container" data-url="/autocomplete/user-suggestions" data-no-org-url="/autocomplete/user-suggestions" data-org-url="/suggestions" hidden>
</div>
</div>
<div style="margin-left: 53px" class="my-1 text-small label-characters-remaining js-characters-remaining" data-suffix="remaining" hidden>
80 remaining
</div>
</div>
<include-fragment class="js-user-status-emoji-picker" data-url="/users/status/emoji"></include-fragment>
<div class="overflow-auto" style="max-height: 33vh">
<div class="user-status-suggestions js-user-status-suggestions">
<h4 class="f6 text-normal my-3">Suggestions:</h4>
<div class="mx-3 mt-2 clearfix">
<div class="float-left col-6">
<button type="button" value=":palm_tree:" class="d-flex flex-items-baseline flex-items-stretch lh-condensed f6 btn-link link-gray no-underline js-predefined-user-status mb-1">
<div class="emoji-status-width mr-2 v-align-middle js-predefined-user-status-emoji">
<g-emoji alias="palm_tree" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f334.png">🌴</g-emoji>
</div>
<div class="d-flex flex-items-center no-underline js-predefined-user-status-message" style="border-left: 1px solid transparent">
On vacation
</div>
</button>
<button type="button" value=":face_with_thermometer:" class="d-flex flex-items-baseline flex-items-stretch lh-condensed f6 btn-link link-gray no-underline js-predefined-user-status mb-1">
<div class="emoji-status-width mr-2 v-align-middle js-predefined-user-status-emoji">
<g-emoji alias="face_with_thermometer" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f912.png">🤒</g-emoji>
</div>
<div class="d-flex flex-items-center no-underline js-predefined-user-status-message" style="border-left: 1px solid transparent">
Out sick
</div>
</button>
</div>
<div class="float-left col-6">
<button type="button" value=":house:" class="d-flex flex-items-baseline flex-items-stretch lh-condensed f6 btn-link link-gray no-underline js-predefined-user-status mb-1">
<div class="emoji-status-width mr-2 v-align-middle js-predefined-user-status-emoji">
<g-emoji alias="house" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f3e0.png">🏠</g-emoji>
</div>
<div class="d-flex flex-items-center no-underline js-predefined-user-status-message" style="border-left: 1px solid transparent">
Working from home
</div>
</button>
<button type="button" value=":dart:" class="d-flex flex-items-baseline flex-items-stretch lh-condensed f6 btn-link link-gray no-underline js-predefined-user-status mb-1">
<div class="emoji-status-width mr-2 v-align-middle js-predefined-user-status-emoji">
<g-emoji alias="dart" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f3af.png">🎯</g-emoji>
</div>
<div class="d-flex flex-items-center no-underline js-predefined-user-status-message" style="border-left: 1px solid transparent">
Focusing
</div>
</button>
</div>
</div>
</div>
<div class="user-status-limited-availability-container">
<div class="form-checkbox my-0">
<input type="checkbox" name="limited_availability" value="1" class="js-user-status-limited-availability-checkbox" data-default-message="I may be slow to respond." aria-describedby="limited-availability-help-text-truncate-true" id="limited-availability-truncate-true">
<label class="d-block f5 text-gray-dark mb-1" for="limited-availability-truncate-true">
Busy
</label>
<p class="note" id="limited-availability-help-text-truncate-true">
When others mention you, assign you, or request your review,
GitHub will let them know that you have limited availability.
</p>
</div>
</div>
</div>
<include-fragment class="js-user-status-org-picker" data-url="/users/status/organizations"></include-fragment>
</div>
<div class="d-flex flex-items-center flex-justify-between p-3 border-top">
<button type="submit" disabled class="width-full btn btn-primary mr-2 js-user-status-submit">
Set status
</button>
<button type="button" disabled class="width-full js-clear-user-status-button btn ml-2 ">
Clear status
</button>
</div>
</form> </details-dialog>
</details>
</div>
</div>
<div role="none" class="dropdown-divider"></div>
<a role="menuitem" class="dropdown-item" href="/richturner" data-ga-click="Header, go to profile, text:your profile">Your profile</a>
<a role="menuitem" class="dropdown-item" href="/richturner?tab=repositories" data-ga-click="Header, go to repositories, text:your repositories">Your repositories</a>
<a role="menuitem" class="dropdown-item" href="/richturner?tab=projects" data-ga-click="Header, go to projects, text:your projects">Your projects</a>
<a role="menuitem" class="dropdown-item" href="/richturner?tab=stars" data-ga-click="Header, go to starred repos, text:your stars">Your stars</a>
<a role="menuitem" class="dropdown-item" href="https://gist.github.com/" data-ga-click="Header, your gists, text:your gists">Your gists</a>
<div role="none" class="dropdown-divider"></div>
<a role="menuitem" class="dropdown-item" href="https://help.github.com" data-ga-click="Header, go to help, text:help">Help</a>
<a role="menuitem" class="dropdown-item" href="/settings/profile" data-ga-click="Header, go to settings, icon:settings">Settings</a>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="logout-form" action="/logout" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="n0bvnbUo19gOzKDq0ipPgEJYgJcPaJKl/JlIfXB0a5NrxTUrRCE2hsbh4evo+2TvoyYOFPvw3EgDP4DHYeh6Cg==" />
<button type="submit" class="dropdown-item dropdown-signout" data-ga-click="Header, sign out, icon:logout" role="menuitem">
Sign out
</button>
</form> </details-menu>
</details>
</li>
</ul>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="sr-only right-0" action="/logout" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="YR3DhtlRJaku8a0aCWDMN1ZDMffaDCvadFNcxVhthJyVnhkwKFjE9+bc7BszsedYtz2/dC6UZTeL9ZR/SfGVBQ==" />
<button type="submit" class="dropdown-item dropdown-signout" data-ga-click="Header, sign out, icon:logout">
Sign out
</button>
</form> </div>
</div>
</div>
</header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container">
</div>
<div role="main" class="application-main " data-commit-hovercards-enabled>
<div itemscope itemtype="http://schema.org/SoftwareSourceCode" class="">
<div id="js-repo-pjax-container" data-pjax-container >
<div class="pagehead repohead instapaper_ignore readability-menu experiment-repo-nav ">
<div class="repohead-details-container clearfix container">
<ul class="pagehead-actions">
<li>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form data-remote="true" class="js-social-form js-social-container" action="/notifications/subscribe" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="Xkbe6oplP3IH7NEfe+FYF7bfK65O3bhz5h73lrK6ecV2VYLSiXdaGrrW3HbrJl+BaFeeZbeX5U2brSKcm2t84Q==" /> <input type="hidden" name="repository_id" id="repository_id" value="24953448" class="form-control" />
<details class="details-reset details-overlay select-menu float-left">
<summary class="btn btn-sm btn-with-count select-menu-button" data-ga-click="Repository, click Watch settings, action:blob#show">
<span data-menu-button>
<svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Watch
</span>
</summary>
<details-menu class="select-menu-modal position-absolute mt-5" style="z-index: 99;">
<div class="select-menu-header">
<span class="select-menu-title">Notifications</span>
</div>
<div class="select-menu-list">
<button type="submit" name="do" value="included" class="select-menu-item width-full" aria-checked="true" role="menuitemradio">
<svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg>
<div class="select-menu-item-text">
<span class="select-menu-item-heading">Not watching</span>
<span class="description">Be notified only when participating or @mentioned.</span>
<span class="hidden-select-button-text" data-menu-button-contents>
<svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Watch
</span>
</div>
</button>
<button type="submit" name="do" value="release_only" class="select-menu-item width-full" aria-checked="false" role="menuitemradio">
<svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg>
<div class="select-menu-item-text">
<span class="select-menu-item-heading">Releases only</span>
<span class="description">Be notified of new releases, and when participating or @mentioned.</span>
<span class="hidden-select-button-text" data-menu-button-contents>
<svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Unwatch releases
</span>
</div>
</button>
<button type="submit" name="do" value="subscribed" class="select-menu-item width-full" aria-checked="false" role="menuitemradio">
<svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg>
<div class="select-menu-item-text">
<span class="select-menu-item-heading">Watching</span>
<span class="description">Be notified of all conversations.</span>
<span class="hidden-select-button-text" data-menu-button-contents>
<svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Unwatch
</span>
</div>
</button>
<button type="submit" name="do" value="ignore" class="select-menu-item width-full" aria-checked="false" role="menuitemradio">
<svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg>
<div class="select-menu-item-text">
<span class="select-menu-item-heading">Ignoring</span>
<span class="description">Never be notified.</span>
<span class="hidden-select-button-text" data-menu-button-contents>
<svg class="octicon octicon-mute v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 2.81v10.38c0 .67-.81 1-1.28.53L3 10H1c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h2l3.72-3.72C7.19 1.81 8 2.14 8 2.81zm7.53 3.22l-1.06-1.06-1.97 1.97-1.97-1.97-1.06 1.06L11.44 8 9.47 9.97l1.06 1.06 1.97-1.97 1.97 1.97 1.06-1.06L13.56 8l1.97-1.97z"/></svg>
Stop ignoring
</span>
</div>
</button>
</div>
</details-menu>
</details>
<a class="social-count js-social-count"
href="/google/material-design-icons/watchers"
aria-label="1903 users are watching this repository">
1,903
</a>
</form>
</li>
<li>
<div class="js-toggler-container js-social-container starring-container ">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="starred js-social-form" action="/google/material-design-icons/unstar" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="Hw4ecA+VgFgouim/IM9v4fRkYAl/powz4yX8ufCBDuzuH4XEzpCB/taYk+Dw4ySapMUMteYmmT99lq2z/duF1g==" />
<input type="hidden" name="context" value="repository"></input>
<button
type="submit"
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Unstar this repository" title="Unstar google/material-design-icons"
data-ga-click="Repository, click unstar button, action:blob#show; text:Unstar">
<svg class="octicon octicon-star v-align-text-bottom" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74L14 6z"/></svg>
Unstar
</button>
<a class="social-count js-social-count" href="/google/material-design-icons/stargazers"
aria-label="37097 users starred this repository">
37,097
</a>
</form>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="unstarred js-social-form" action="/google/material-design-icons/star" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="bBcgDKDC8Oh+ohDcEHE2kkTaOeTvjPVFp7ND0bozRHHDPE4mSdq4Kfck/Y0iVW/KQZ4PKydHU+vx4cs9AKzLCA==" />
<input type="hidden" name="context" value="repository"></input>
<button
type="submit"
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Star this repository" title="Star google/material-design-icons"
data-ga-click="Repository, click star button, action:blob#show; text:Star">
<svg class="octicon octicon-star v-align-text-bottom" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74L14 6z"/></svg>
Star
</button>
<a class="social-count js-social-count" href="/google/material-design-icons/stargazers"
aria-label="37097 users starred this repository">
37,097
</a>
</form> </div>
</li>
<li>
<details class="details-reset details-overlay details-overlay-dark d-inline-block float-left"
data-deferred-details-content-url="/google/material-design-icons/fork?fragment=1">
<summary class="btn btn-sm btn-with-count"
title="Fork your own copy of google/material-design-icons to your account"
data-ga-click="Repository, show fork modal, action:blob#show; text:Fork">
<svg class="octicon octicon-repo-forked v-align-text-bottom" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 0 0-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 0 0 2 1a1.993 1.993 0 0 0-1 3.72V6.5l3 3v1.78A1.993 1.993 0 0 0 5 15a1.993 1.993 0 0 0 1-3.72V9.5l3-3V4.72A1.993 1.993 0 0 0 8 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
Fork
</summary>
<details-dialog class="anim-fade-in fast Box Box--overlay d-flex flex-column">
<div class="Box-header">
<button class="Box-btn-octicon btn-octicon float-right" type="button" aria-label="Close dialog" data-close-dialog>
<svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg>
</button>
<h3 class="Box-title">Fork material-design-icons</h3>
</div>
<div class="overflow-auto text-center">
<include-fragment>
<div class="octocat-spinner my-3" aria-label="Loading..."></div>
<p class="f5 text-gray">If this dialog fails to load, you can visit <a href="/google/material-design-icons/fork">the fork page</a> directly.</p>
</include-fragment>
</div>
</details-dialog>
</details>
<a href="/google/material-design-icons/network/members" class="social-count"
aria-label="7487 users forked this repository">
7,487
</a>
</li>
</ul>
<h1 class="public ">
<svg class="octicon octicon-repo" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg>
<span class="author" itemprop="author"><a class="url fn" rel="author" data-hovercard-type="organization" data-hovercard-url="/orgs/google/hovercard" href="/google">google</a></span><!--
--><span class="path-divider">/</span><!--
--><strong itemprop="name"><a data-pjax="#js-repo-pjax-container" href="/google/material-design-icons">material-design-icons</a></strong>
</h1>
</div>
<nav class="reponav js-repo-nav js-sidenav-container-pjax container"
itemscope
itemtype="http://schema.org/BreadcrumbList"
aria-label="Repository"
data-pjax="#js-repo-pjax-container">
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a class="js-selected-navigation-item selected reponav-item" itemprop="url" data-hotkey="g c" aria-current="page" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches repo_packages /google/material-design-icons" href="/google/material-design-icons">
<svg class="octicon octicon-code" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"/></svg>
<span itemprop="name">Code</span>
<meta itemprop="position" content="1">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a itemprop="url" data-hotkey="g i" class="js-selected-navigation-item reponav-item" data-selected-links="repo_issues repo_labels repo_milestones /google/material-design-icons/issues" href="/google/material-design-icons/issues">
<svg class="octicon octicon-issue-opened" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"/></svg>
<span itemprop="name">Issues</span>
<span class="Counter">506</span>
<meta itemprop="position" content="2">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a data-hotkey="g p" itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="repo_pulls checks /google/material-design-icons/pulls" href="/google/material-design-icons/pulls">
<svg class="octicon octicon-git-pull-request" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
<span itemprop="name">Pull requests</span>
<span class="Counter">30</span>
<meta itemprop="position" content="3">
</a> </span>
<a data-hotkey="g b" class="js-selected-navigation-item reponav-item" data-selected-links="repo_projects new_repo_project repo_project /google/material-design-icons/projects" href="/google/material-design-icons/projects">
<svg class="octicon octicon-project" viewBox="0 0 15 16" version="1.1" width="15" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg>
Projects
<span class="Counter" >0</span>
</a>
<a class="js-selected-navigation-item reponav-item" data-hotkey="g w" data-selected-links="repo_wiki /google/material-design-icons/wiki" href="/google/material-design-icons/wiki">
<svg class="octicon octicon-book" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M3 5h4v1H3V5zm0 3h4V7H3v1zm0 2h4V9H3v1zm11-5h-4v1h4V5zm0 2h-4v1h4V7zm0 2h-4v1h4V9zm2-6v9c0 .55-.45 1-1 1H9.5l-1 1-1-1H2c-.55 0-1-.45-1-1V3c0-.55.45-1 1-1h5.5l1 1 1-1H15c.55 0 1 .45 1 1zm-8 .5L7.5 3H2v9h6V3.5zm7-.5H9.5l-.5.5V12h6V3z"/></svg>
Wiki
</a>
<a class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors dependency_graph pulse alerts security people /google/material-design-icons/pulse" href="/google/material-design-icons/pulse">
<svg class="octicon octicon-graph" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"/></svg>
Insights
</a>
</nav>
</div>
<div class="container new-discussion-timeline experiment-repo-nav ">
<div class="repository-content ">
<a class="d-none js-permalink-shortcut" data-hotkey="y" href="/google/material-design-icons/blob/224895a86501195e7a7ff3dde18e39f00b8e3d5a/iconfont/material-icons.css">Permalink</a>
<!-- blob contrib key: blob_contributors:v21:1823783dee9276501ccd74d555d37346 -->
<div class="file-navigation">
<details class="details-reset details-overlay select-menu branch-select-menu float-left">
<summary class="btn btn-sm select-menu-button css-truncate"
data-hotkey="w"
title="Switch branches or tags">
<i>Branch:</i>
<span class="css-truncate-target">master</span>
</summary>
<details-menu class="select-menu-modal position-absolute" style="z-index: 99;" src="/google/material-design-icons/ref-list/master/iconfont/material-icons.css?source_action=show&source_controller=blob" preload>
<include-fragment class="select-menu-loading-overlay anim-pulse">
<svg height="32" class="octicon octicon-octoface" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M14.7 5.34c.13-.32.55-1.59-.13-3.31 0 0-1.05-.33-3.44 1.3-1-.28-2.07-.32-3.13-.32s-2.13.04-3.13.32c-2.39-1.64-3.44-1.3-3.44-1.3-.68 1.72-.26 2.99-.13 3.31C.49 6.21 0 7.33 0 8.69 0 13.84 3.33 15 7.98 15S16 13.84 16 8.69c0-1.36-.49-2.48-1.3-3.35zM8 14.02c-3.3 0-5.98-.15-5.98-3.35 0-.76.38-1.48 1.02-2.07 1.07-.98 2.9-.46 4.96-.46 2.07 0 3.88-.52 4.96.46.65.59 1.02 1.3 1.02 2.07 0 3.19-2.68 3.35-5.98 3.35zM5.49 9.01c-.66 0-1.2.8-1.2 1.78s.54 1.79 1.2 1.79c.66 0 1.2-.8 1.2-1.79s-.54-1.78-1.2-1.78zm5.02 0c-.66 0-1.2.79-1.2 1.78s.54 1.79 1.2 1.79c.66 0 1.2-.8 1.2-1.79s-.53-1.78-1.2-1.78z"/></svg>
</include-fragment>
</details-menu>
</details>
<div class="BtnGroup float-right">
<a href="/google/material-design-icons/find/master"
class="js-pjax-capture-input btn btn-sm BtnGroup-item"
data-pjax
data-hotkey="t">
Find file
</a>
<clipboard-copy for="blob-path" class="btn btn-sm BtnGroup-item">
Copy path
</clipboard-copy>
</div>
<div id="blob-path" class="breadcrumb">
<span class="repo-root js-repo-root"><span class="js-path-segment"><a data-pjax="true" href="/google/material-design-icons"><span>material-design-icons</span></a></span></span><span class="separator">/</span><span class="js-path-segment"><a data-pjax="true" href="/google/material-design-icons/tree/master/iconfont"><span>iconfont</span></a></span><span class="separator">/</span><strong class="final-path">material-icons.css</strong>
</div>
</div>
<div class="commit-tease">
<span class="float-right">
<a class="commit-tease-sha" href="/google/material-design-icons/commit/eae603ae946b6f813b7edc5611226d8ceae327ff" data-pjax>
eae603a
</a>
<relative-time datetime="2016-03-21T20:35:14Z">Mar 21, 2016</relative-time>
</span>
<div>
<a rel="contributor" data-skip-pjax="true" data-hovercard-user-id="42326" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/shyndman"><img class="avatar" src="https://avatars3.githubusercontent.com/u/42326?s=40&v=4" width="20" height="20" alt="@shyndman" /></a>
<a class="user-mention" rel="contributor" data-hovercard-user-id="42326" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/shyndman">shyndman</a>
<a data-pjax="true" title="Removes width and height from icon font CSS." class="message" href="/google/material-design-icons/commit/eae603ae946b6f813b7edc5611226d8ceae327ff">Removes width and height from icon font CSS.</a>
</div>
<div class="commit-tease-contributors">
<details class="details-reset details-overlay details-overlay-dark lh-default text-gray-dark float-left mr-2" id="blob_contributors_box">
<summary class="btn-link" aria-haspopup="dialog" >
<span><strong>2</strong> contributors</span>
</summary>
<details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast " aria-label="Users who have contributed to this file">
<div class="Box-header">
<button class="Box-btn-octicon btn-octicon float-right" type="button" aria-label="Close dialog" data-close-dialog>
<svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg>
</button>
<h3 class="Box-title">Users who have contributed to this file</h3>
</div>
<ul class="list-style-none overflow-auto">
<li class="Box-row">
<a class="link-gray-dark no-underline" href="/shyndman">
<img class="avatar mr-2" alt="" src="https://avatars3.githubusercontent.com/u/42326?s=40&v=4" width="20" height="20" />
shyndman
</a> </li>
<li class="Box-row">
<a class="link-gray-dark no-underline" href="/otomeskhy">
<img class="avatar mr-2" alt="" src="https://avatars2.githubusercontent.com/u/589801?s=40&v=4" width="20" height="20" />
otomeskhy
</a> </li>
</ul>
</details-dialog>
</details>
<a class="avatar-link" data-hovercard-user-id="42326" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/google/material-design-icons/commits/master/iconfont/material-icons.css?author=shyndman">
<img class="avatar" src="https://avatars3.githubusercontent.com/u/42326?s=40&v=4" width="20" height="20" alt="@shyndman" />
</a> <a class="avatar-link" data-hovercard-user-id="589801" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/google/material-design-icons/commits/master/iconfont/material-icons.css?author=otomeskhy">
<img class="avatar" src="https://avatars2.githubusercontent.com/u/589801?s=40&v=4" width="20" height="20" alt="@otomeskhy" />
</a>
</div>
</div>
<div class="file ">
<div class="file-header">
<div class="file-actions">
<div class="BtnGroup">
<a id="raw-url" class="btn btn-sm BtnGroup-item" href="/google/material-design-icons/raw/master/iconfont/material-icons.css">Raw</a>
<a class="btn btn-sm js-update-url-with-hash BtnGroup-item" data-hotkey="b" href="/google/material-design-icons/blame/master/iconfont/material-icons.css">Blame</a>
<a rel="nofollow" class="btn btn-sm BtnGroup-item" href="/google/material-design-icons/commits/master/iconfont/material-icons.css">History</a>
</div>
<a class="btn-octicon tooltipped tooltipped-nw"
href="https://desktop.github.com"
aria-label="Open this file in GitHub Desktop"
data-ga-click="Repository, open with desktop, type:windows">
<svg class="octicon octicon-device-desktop" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M15 2H1c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5.34c-.25.61-.86 1.39-2.34 2h8c-1.48-.61-2.09-1.39-2.34-2H15c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm0 9H1V3h14v8z"/></svg>
</a>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="inline-form js-update-url-with-hash" action="/google/material-design-icons/edit/master/iconfont/material-icons.css" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="FRpGCA+tzkyfiMGRL1dFESX+fnT9MyExxeqXKrGJT4Bil7WwzfCgpDM2jHoyqivovCwsJmW81cxDzOO5wSoKWg==" />
<button class="btn-octicon tooltipped tooltipped-nw" type="submit"
aria-label="Fork this project and edit the file" data-hotkey="e" data-disable-with>
<svg class="octicon octicon-pencil" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 0 1 1.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"/></svg>
</button>
</form>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="inline-form" action="/google/material-design-icons/delete/master/iconfont/material-icons.css" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="UfYb3BvXMNjSiHhDx2b0AXMTxQAqWfL1vg394jL83cebFpcVQmaF0TeWPHIK/efyWZPU+n7Dyfaly4ZiLrmeRQ==" />
<button class="btn-octicon btn-octicon-danger tooltipped tooltipped-nw" type="submit"
aria-label="Fork this project and delete the file" data-disable-with>
<svg class="octicon octicon-trashcan" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"/></svg>
</button>
</form> </div>
<div class="file-info">
37 lines (32 sloc)
<span class="file-info-divider"></span>
970 Bytes
</div>
</div>
<div itemprop="text" class="blob-wrapper data type-css ">
<table class="highlight tab-size js-file-line-container" data-tab-size="8">
<tr>
<td id="L1" class="blob-num js-line-number" data-line-number="1"></td>
<td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-k">@font-face</span> {</td>
</tr>
<tr>
<td id="L2" class="blob-num js-line-number" data-line-number="2"></td>
<td id="LC2" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">font-family</span></span>: <span class="pl-s"><span class="pl-pds">'</span>Material Icons<span class="pl-pds">'</span></span>;</td>
</tr>
<tr>
<td id="L3" class="blob-num js-line-number" data-line-number="3"></td>
<td id="LC3" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">font-style</span></span>: <span class="pl-c1">normal</span>;</td>
</tr>
<tr>
<td id="L4" class="blob-num js-line-number" data-line-number="4"></td>
<td id="LC4" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">font-weight</span></span>: <span class="pl-c1">400</span>;</td>
</tr>
<tr>
<td id="L5" class="blob-num js-line-number" data-line-number="5"></td>
<td id="LC5" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">src</span></span>: <span class="pl-c1">url</span>(<span class="pl-v">MaterialIcons-Regular.eot</span>); <span class="pl-c"><span class="pl-c">/*</span> For IE6-8 <span class="pl-c">*/</span></span></td>
</tr>
<tr>
<td id="L6" class="blob-num js-line-number" data-line-number="6"></td>
<td id="LC6" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">src</span></span>: <span class="pl-c1">local</span>(<span class="pl-s"><span class="pl-pds">'</span>Material Icons<span class="pl-pds">'</span></span>),</td>
</tr>
<tr>
<td id="L7" class="blob-num js-line-number" data-line-number="7"></td>
<td id="LC7" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">local</span>(<span class="pl-s"><span class="pl-pds">'</span>MaterialIcons-Regular<span class="pl-pds">'</span></span>),</td>
</tr>
<tr>
<td id="L8" class="blob-num js-line-number" data-line-number="8"></td>
<td id="LC8" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">url</span>(<span class="pl-v">MaterialIcons-Regular.woff2</span>) <span class="pl-c1">format</span>(<span class="pl-s"><span class="pl-pds">'</span>woff2<span class="pl-pds">'</span></span>),</td>
</tr>
<tr>
<td id="L9" class="blob-num js-line-number" data-line-number="9"></td>
<td id="LC9" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">url</span>(<span class="pl-v">MaterialIcons-Regular.woff</span>) <span class="pl-c1">format</span>(<span class="pl-s"><span class="pl-pds">'</span>woff<span class="pl-pds">'</span></span>),</td>
</tr>
<tr>
<td id="L10" class="blob-num js-line-number" data-line-number="10"></td>
<td id="LC10" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">url</span>(<span class="pl-v">MaterialIcons-Regular.ttf</span>) <span class="pl-c1">format</span>(<span class="pl-s"><span class="pl-pds">'</span>truetype<span class="pl-pds">'</span></span>);</td>
</tr>
<tr>
<td id="L11" class="blob-num js-line-number" data-line-number="11"></td>
<td id="LC11" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="L12" class="blob-num js-line-number" data-line-number="12"></td>
<td id="LC12" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L13" class="blob-num js-line-number" data-line-number="13"></td>
<td id="LC13" class="blob-code blob-code-inner js-file-line"><span class="pl-e">.material-icons</span> {</td>
</tr>
<tr>
<td id="L14" class="blob-num js-line-number" data-line-number="14"></td>
<td id="LC14" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">font-family</span></span>: <span class="pl-s"><span class="pl-pds">'</span>Material Icons<span class="pl-pds">'</span></span>;</td>
</tr>
<tr>
<td id="L15" class="blob-num js-line-number" data-line-number="15"></td>
<td id="LC15" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">font-weight</span></span>: <span class="pl-c1">normal</span>;</td>
</tr>
<tr>
<td id="L16" class="blob-num js-line-number" data-line-number="16"></td>
<td id="LC16" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">font-style</span></span>: <span class="pl-c1">normal</span>;</td>
</tr>
<tr>
<td id="L17" class="blob-num js-line-number" data-line-number="17"></td>
<td id="LC17" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">font-size</span></span>: <span class="pl-c1">24<span class="pl-k">px</span></span>; <span class="pl-c"><span class="pl-c">/*</span> Preferred icon size <span class="pl-c">*/</span></span></td>
</tr>
<tr>
<td id="L18" class="blob-num js-line-number" data-line-number="18"></td>
<td id="LC18" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">display</span></span>: <span class="pl-c1">inline-block</span>;</td>
</tr>
<tr>
<td id="L19" class="blob-num js-line-number" data-line-number="19"></td>
<td id="LC19" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">line-height</span></span>: <span class="pl-c1">1</span>;</td>
</tr>
<tr>
<td id="L20" class="blob-num js-line-number" data-line-number="20"></td>
<td id="LC20" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">text-transform</span></span>: <span class="pl-c1">none</span>;</td>
</tr>
<tr>
<td id="L21" class="blob-num js-line-number" data-line-number="21"></td>
<td id="LC21" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">letter-spacing</span></span>: <span class="pl-c1">normal</span>;</td>
</tr>
<tr>
<td id="L22" class="blob-num js-line-number" data-line-number="22"></td>
<td id="LC22" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">word-wrap</span></span>: <span class="pl-c1">normal</span>;</td>
</tr>
<tr>
<td id="L23" class="blob-num js-line-number" data-line-number="23"></td>
<td id="LC23" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">white-space</span></span>: <span class="pl-c1">nowrap</span>;</td>
</tr>
<tr>
<td id="L24" class="blob-num js-line-number" data-line-number="24"></td>
<td id="LC24" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">direction</span></span>: <span class="pl-c1">ltr</span>;</td>
</tr>
<tr>
<td id="L25" class="blob-num js-line-number" data-line-number="25"></td>
<td id="LC25" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L26" class="blob-num js-line-number" data-line-number="26"></td>
<td id="LC26" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">/*</span> Support for all WebKit browsers. <span class="pl-c">*/</span></span></td>
</tr>
<tr>
<td id="L27" class="blob-num js-line-number" data-line-number="27"></td>
<td id="LC27" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">-webkit-font-smoothing</span></span>: <span class="pl-c1">antialiased</span>;</td>
</tr>
<tr>
<td id="L28" class="blob-num js-line-number" data-line-number="28"></td>
<td id="LC28" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">/*</span> Support for Safari and Chrome. <span class="pl-c">*/</span></span></td>
</tr>
<tr>
<td id="L29" class="blob-num js-line-number" data-line-number="29"></td>
<td id="LC29" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">text-rendering</span></span>: <span class="pl-c1">optimizeLegibility</span>;</td>
</tr>
<tr>
<td id="L30" class="blob-num js-line-number" data-line-number="30"></td>
<td id="LC30" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L31" class="blob-num js-line-number" data-line-number="31"></td>
<td id="LC31" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">/*</span> Support for Firefox. <span class="pl-c">*/</span></span></td>
</tr>
<tr>
<td id="L32" class="blob-num js-line-number" data-line-number="32"></td>
<td id="LC32" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">-moz-osx-font-smoothing</span></span>: <span class="pl-c1">grayscale</span>;</td>
</tr>
<tr>
<td id="L33" class="blob-num js-line-number" data-line-number="33"></td>
<td id="LC33" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L34" class="blob-num js-line-number" data-line-number="34"></td>
<td id="LC34" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">/*</span> Support for IE. <span class="pl-c">*/</span></span></td>
</tr>
<tr>
<td id="L35" class="blob-num js-line-number" data-line-number="35"></td>
<td id="LC35" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1"><span class="pl-c1">font-feature-settings</span></span>: <span class="pl-s"><span class="pl-pds">'</span>liga<span class="pl-pds">'</span></span>;</td>
</tr>
<tr>
<td id="L36" class="blob-num js-line-number" data-line-number="36"></td>
<td id="LC36" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
<details class="details-reset details-overlay BlobToolbar position-absolute js-file-line-actions dropdown d-none" aria-hidden="true">
<summary class="btn-octicon ml-0 px-2 p-0 bg-white border border-gray-dark rounded-1" aria-label="Inline file action toolbar">
<svg class="octicon octicon-kebab-horizontal" viewBox="0 0 13 16" version="1.1" width="13" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zm5 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM13 7.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/></svg>
</summary>
<details-menu>
<ul class="BlobToolbar-dropdown dropdown-menu dropdown-menu-se mt-2" style="width:185px">
<li><clipboard-copy role="menuitem" class="dropdown-item" id="js-copy-lines" style="cursor:pointer;" data-original-text="Copy lines">Copy lines</clipboard-copy></li>
<li><clipboard-copy role="menuitem" class="dropdown-item" id="js-copy-permalink" style="cursor:pointer;" data-original-text="Copy permalink">Copy permalink</clipboard-copy></li>
<li><a class="dropdown-item js-update-url-with-hash" id="js-view-git-blame" role="menuitem" href="/google/material-design-icons/blame/224895a86501195e7a7ff3dde18e39f00b8e3d5a/iconfont/material-icons.css">View git blame</a></li>
<li><a class="dropdown-item" id="js-new-issue" role="menuitem" href="/google/material-design-icons/issues/new">Reference in new issue</a></li>
</ul>
</details-menu>
</details>
</div>
</div>
<details class="details-reset details-overlay details-overlay-dark">
<summary data-hotkey="l" aria-label="Jump to line"></summary>
<details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast linejump" aria-label="Jump to line">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form class="js-jump-to-line-form Box-body d-flex" action="" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" />
<input class="form-control flex-auto mr-3 linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line…" aria-label="Jump to line" autofocus>
<button type="submit" class="btn" data-close-dialog>Go</button>
</form> </details-dialog>
</details>
</div>
<div class="modal-backdrop js-touch-events"></div>
</div>
</div>
</div>
</div>
<div class="footer container-lg px-3" role="contentinfo">
<div class="position-relative d-flex flex-justify-between pt-6 pb-2 mt-6 f6 text-gray border-top border-gray-light ">
<ul class="list-style-none d-flex flex-wrap ">
<li class="mr-3">© 2019 <span title="0.27531s from unicorn-c5f49db48-x6p84">GitHub</span>, Inc.</li>
<li class="mr-3"><a data-ga-click="Footer, go to terms, text:terms" href="https://github.com/site/terms">Terms</a></li>
<li class="mr-3"><a data-ga-click="Footer, go to privacy, text:privacy" href="https://github.com/site/privacy">Privacy</a></li>
<li class="mr-3"><a data-ga-click="Footer, go to security, text:security" href="https://github.com/security">Security</a></li>
<li class="mr-3"><a href="https://githubstatus.com/" data-ga-click="Footer, go to status, text:status">Status</a></li>
<li><a data-ga-click="Footer, go to help, text:help" href="https://help.github.com">Help</a></li>
</ul>
<a aria-label="Homepage" title="GitHub" class="footer-octicon mr-lg-4" href="https://github.com">
<svg height="24" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="24" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
</a>
<ul class="list-style-none d-flex flex-wrap ">
<li class="mr-3"><a data-ga-click="Footer, go to contact, text:contact" href="https://github.com/contact">Contact GitHub</a></li>
<li class="mr-3"><a href="https://github.com/pricing" data-ga-click="Footer, go to Pricing, text:Pricing">Pricing</a></li>
<li class="mr-3"><a href="https://developer.github.com" data-ga-click="Footer, go to api, text:api">API</a></li>
<li class="mr-3"><a href="https://training.github.com" data-ga-click="Footer, go to training, text:training">Training</a></li>
<li class="mr-3"><a href="https://github.blog" data-ga-click="Footer, go to blog, text:blog">Blog</a></li>
<li><a data-ga-click="Footer, go to about, text:about" href="https://github.com/about">About</a></li>
</ul>
</div>
<div class="d-flex flex-justify-center pb-6">
<span class="f6 text-gray-light"></span>
</div>
</div>
<div id="ajax-error-message" class="ajax-error-message flash flash-error">
<svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 0 0 0 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 0 0 .01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"/></svg>
<button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error">
<svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg>
</button>
You can’t perform that action at this time.
</div>
<script crossorigin="anonymous" integrity="sha512-ZwVwxq7XuYTJgo+RvKEmeGyrm1OTN2Du77YWAfdEiJo9lZbmFO252M4KaMRyDZ3O0bw1OYpF/rJCyQ3g/aa0yA==" type="application/javascript" src="https://github.githubassets.com/assets/frameworks-5e5334deb0beba2b22d055907f8e10a4.js"></script>
<script crossorigin="anonymous" async="async" integrity="sha512-Kg2H4QtcFv6s9gVe98HW39XIidLR6itVpnCqUj3+F90wBpGL/g2ys2Z+fLIZ6H4uYZkWKMIht0Z1NGX7T0ODCg==" type="application/javascript" src="https://github.githubassets.com/assets/github-7c321d4983ea717deb4358464a917bba.js"></script>
<div class="js-stale-session-flash stale-session-flash flash flash-warn flash-banner d-none">
<svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 0 0 0 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 0 0 .01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"/></svg>
<span class="signed-in-tab-flash">You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span>
<span class="signed-out-tab-flash">You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span>
</div>
<template id="site-details-dialog">
<details class="details-reset details-overlay details-overlay-dark lh-default text-gray-dark" open>
<summary aria-haspopup="dialog" aria-label="Close dialog"></summary>
<details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast">
<button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog>
<svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg>
</button>
<div class="octocat-spinner my-6 js-details-dialog-spinner"></div>
</details-dialog>
</details>
</template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0">
<div class="Popover-message Popover-message--bottom-left Popover-message--large Box box-shadow-large" style="width:360px;">
</div>
</div>
<div id="hovercard-aria-description" class="sr-only">
Press h to open a hovercard with more details.
</div>
<div aria-live="polite" class="js-global-screen-reader-notice sr-only"></div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
Erica Sadun, http://ericasadun.com
iPhone Developer's Cookbook, 6.x Edition
BSD License, Use at your own risk
*/
#import <UIKit/UIKit.h>
#define COOKBOOK_PURPLE_COLOR [UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]
#define BARBUTTON(TITLE, SELECTOR) [[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR]
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define INITPAGES 3
typedef void (^AnimationBlock)(void);
typedef void (^CompletionBlock)(BOOL completed);
@interface TestBedViewController : UIViewController <UIScrollViewDelegate>
{
UIScrollView *scrollView;
CGFloat dimension;
IBOutlet UIPageControl *pageControl;
IBOutlet UIButton *addButton;
IBOutlet UIButton *cancelButton;
IBOutlet UIButton *confirmButton;
IBOutlet UIButton *deleteButton;
}
@end
@implementation TestBedViewController
- (void) pageTurn: (UIPageControl *) aPageControl
{
int whichPage = aPageControl.currentPage;
[UIView animateWithDuration:0.3f
animations:^{scrollView.contentOffset = CGPointMake(dimension * whichPage, 0.0f);}];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView
{
// Fudge a little and take the floor to accommodate division issues
pageControl.currentPage = floor((scrollView.contentOffset.x / dimension) + 0.25);
}
- (UIColor *)randomColor
{
float red = (64 + (random() % 191)) / 256.0f;
float green = (64 + (random() % 191)) / 256.0f;
float blue = (64 + (random() % 191)) / 256.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
}
- (void) layoutPages
{
int whichPage = pageControl.currentPage;
scrollView.frame = CGRectMake(0.0f, 0.0f, dimension, dimension);
scrollView.contentSize = CGSizeMake(pageControl.numberOfPages * dimension, dimension);
scrollView.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
float offset = 0.0f;
for (UIView *eachView in scrollView.subviews)
{
if (eachView.tag == 999)
{
eachView.frame = CGRectMake(offset, 0.0f, dimension, dimension);
offset += dimension;
}
}
scrollView.contentOffset = CGPointMake(dimension * whichPage, 0.0f);
}
- (void) addPage
{
pageControl.numberOfPages = pageControl.numberOfPages + 1;
pageControl.currentPage = pageControl.numberOfPages - 1;
UIView *aView = [[UIView alloc] init];
aView.backgroundColor = [self randomColor];
aView.tag = 999;
[scrollView addSubview:aView];
[self layoutPages];
}
- (void) requestAdd: (UIButton *) button
{
[self addPage];
addButton.enabled = (pageControl.numberOfPages < 8) ? YES : NO;
deleteButton.enabled = YES;
[self pageTurn:pageControl];
}
- (void) deletePage
{
int whichPage = pageControl.currentPage;
pageControl.numberOfPages = pageControl.numberOfPages - 1;
int i = 0;
for (UIView *eachView in scrollView.subviews)
{
if ((i == whichPage) && (eachView.tag == 999))
{
[eachView removeFromSuperview];
break;
}
if (eachView.tag == 999) i++;
}
[self layoutPages];
}
- (void) hideConfirmAndCancel
{
cancelButton.enabled = NO;
[UIView animateWithDuration:0.3f animations:^(void)
{
confirmButton.center = CGPointMake(deleteButton.center.x - 300.0f, deleteButton.center.y);
}];
}
- (void) confirmDelete: (UIButton *) button
{
[self deletePage];
addButton.enabled = YES;
deleteButton.enabled = (pageControl.numberOfPages > 1) ? YES : NO;
[self pageTurn:pageControl];
[self hideConfirmAndCancel];
}
- (void) cancelDelete: (UIButton *) button
{
[self hideConfirmAndCancel];
}
- (void) requestDelete: (UIButton *) button
{
// Bring forth the cancel and confirm buttons
[cancelButton.superview bringSubviewToFront:cancelButton];
[confirmButton.superview bringSubviewToFront:confirmButton];
cancelButton.enabled = YES;
// Animate the confirm button into place
confirmButton.center = CGPointMake(deleteButton.center.x - 300.0f, deleteButton.center.y);
[UIView animateWithDuration:0.3f animations:^(void)
{
confirmButton.center = deleteButton.center;
}];
}
- (void) viewDidLoad
{
self.navigationController.navigationBar.tintColor = COOKBOOK_PURPLE_COLOR;
srandom(time(0));
pageControl.numberOfPages = 0;
[pageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
// Create the scroll view and set its content size and delegate
scrollView = [[UIScrollView alloc] init];
scrollView.pagingEnabled = YES;
scrollView.delegate = self;
[self.view addSubview:scrollView];
// Load in pages
for (int i = 0; i < INITPAGES; i++)
[self addPage];
pageControl.currentPage = 0;
// Increase the size of the add button
addButton.frame = CGRectInset(addButton.frame, -20.0f, -20.0f);
}
- (void) viewDidAppear:(BOOL)animated
{
dimension = MIN(self.view.bounds.size.width, self.view.bounds.size.height) * 0.8f;
[self layoutPages];
}
- (void) viewDidLayoutSubviews
{
[self viewDidAppear:NO];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return UIDeviceOrientationIsPortrait(interfaceOrientation);
}
@end
#pragma mark -
#pragma mark Application Setup
@interface TestBedAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
}
@end
@implementation TestBedAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// [application setStatusBarHidden:YES];
[[UINavigationBar appearance] setTintColor:COOKBOOK_PURPLE_COLOR];
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
TestBedViewController *tbvc = [[TestBedViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:tbvc];
window.rootViewController = nav;
[window makeKeyAndVisible];
return YES;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
return retVal;
}
} | {
"pile_set_name": "Github"
} |
package am2.spell;
import am2.AMCore;
import am2.LogHelper;
import am2.texture.ResourceManager;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.init.Items;
import net.minecraft.util.IIcon;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
@SideOnly(Side.CLIENT)
public class SpellTextureHelper{
public static final SpellTextureHelper instance = new SpellTextureHelper();
private IIcon[] icons;
private static final String iconsPath = "/assets/arsmagica2/textures/items/spells/icons/";
private static final String iconsPrefix = "/spells/icons/";
private SpellTextureHelper(){
}
public void loadAllIcons(IIconRegister register){
List<String> resources;
try{
resources = getResourceListing();
if (resources.size() == 0){
LogHelper.error("No spell IIcons found?!?");
}else{
LogHelper.info("Located %d spell IIcons", resources.size());
}
icons = new IIcon[resources.size()];
int count = 0;
for (String s : resources){
icons[count++] = ResourceManager.RegisterTexture(s, register);
}
}catch (Throwable e){
if (icons == null)
icons = new IIcon[0];
e.printStackTrace();
}
}
public static List<String> getResourceListing() throws IOException, URISyntaxException{
CodeSource src = AMCore.class.getProtectionDomain().getCodeSource();
ArrayList<String> toReturn = new ArrayList<String>();
if (src != null){
URL jar = src.getLocation();
if (jar.getProtocol().equals("jar")){
String path = jar.toString().replace("jar:", "").replace("file:", "").replace("!/am2/AMCore.class", "").replace('/', File.separatorChar);
path = URLDecoder.decode(path, "UTF-8");
LogHelper.debug(path);
JarFile jarFile = new JarFile(path);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()){
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("assets/arsmagica2/textures/items/spells/icons/")){
String name = entry.getName().replace("assets/arsmagica2/textures/items/spells/icons/", "");
if (name.equals("")) continue;
toReturn.add("spells/icons/" + name.replace(".png", ""));
}
}
jarFile.close();
}else if (jar.getProtocol().equals("file")){
String path = jar.toURI().toString().replace("/am2/AMCore.class", iconsPath).replace("file:/", "").replace("%20", " ").replace("/", "\\");
File file = new File(path);
if (file.exists() && file.isDirectory()){
for (File sub : file.listFiles()){
toReturn.add(iconsPrefix + sub.getName().replace(".png", ""));
}
}
}
}
Collections.sort(toReturn, String.CASE_INSENSITIVE_ORDER);
return toReturn;
}
public IIcon getIcon(int index){
if (icons.length == 0)
return Items.diamond_sword.getIconFromDamage(0);
if (index < 0 || index >= icons.length) index = 0;
return icons[index];
}
public IIcon[] getAllIcons(){
return icons;
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.presentation
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.editor.markup.TextAttributes
import java.awt.Graphics2D
internal class TextPlaceholderPresentation(
val length: Int,
val textMetricsStorage: InlayTextMetricsStorage,
val small: Boolean
) : BasePresentation() {
override val width: Int
get() = EditorUtil.getPlainSpaceWidth(textMetricsStorage.editor) * length
override val height: Int
get() = getMetrics().fontHeight
private fun getMetrics() = textMetricsStorage.getFontMetrics(small)
override fun paint(g: Graphics2D, attributes: TextAttributes) {}
override fun toString(): String {
return " ".repeat(length)
}
} | {
"pile_set_name": "Github"
} |
var OK_LANG = 'Ok';
var CANCEL_LANG = 'Zrušit';
var RESET_LANG = 'Resetovat';
var ABOUT_LANG = 'O aplikaci';
var ZOOM_LANG = 'Přiblížení';
var BUTTON_TIME_LIST = 'seznam časů';
var BUTTON_OPTIONS = 'Nastavení';
var BUTTON_EXPORT = 'EXPORTOVAT';
var BUTTON_DONATE = 'DAROVAT';
var PROPERTY_SR = 'S relací';
var PROPERTY_USEINS = 'použít WCA inspekci';
var PROPERTY_USEINS_STR = 'Vždy|Vždy, BLD ne|Nikdy';
var PROPERTY_VOICEINS = 'hlasové upozornění při WCA inspekci';
var PROPERTY_VOICEINS_STR = 'žádný|mužský hlas|ženský hlas';
var PROPERTY_VOICEVOL = 'Hlasitost hlasu';
var PROPERTY_PHASES = 'multi-fáze';
var PROPERTY_TIMERSIZE = 'velikost timeru';
var PROPERTY_USEMILLI = 'použít milisekundy';
var PROPERTY_SMALLADP = 'použít malé písmo za desetinnou';
var PROPERTY_SCRSIZE = 'velikost scramblu';
var PROPERTY_SCRMONO = 'neproporcionální scramble';
var PROPERTY_SCRLIM = 'Omezit výšku v oblasti scramblu';
var PROPERTY_SCRALIGN = 'Zarovnání scramble oblasti';
var PROPERTY_SCRALIGN_STR = 'střed|vlevo|vpravo';
var PROPERTY_SCRFAST = 'Použít rychlí scramble pro 4x4x4(neoficiální)';
var PROPERTY_SCRKEYM = 'Klíčovy krok pohybů v zamíchání';
var PROPERTY_SCRCLK = 'Akce při kliknutí na zamíchání';
var PROPERTY_SCRCLK_STR = 'Žádný|Kopírovat|Další zamíchání';
var PROPERTY_WNDSCR = 'Styl zobrazení panelu s scramblem';
var PROPERTY_WNDSTAT = 'Styl zobrazení panelu Statistiky';
var PROPERTY_WNDTOOL = 'Styl zobrazení panelu nástrojů';
var PROPERTY_WND_STR = 'Normální|Plochý';
var EXPORT_DATAEXPORT = 'Import/Export dat';
var EXPORT_TOFILE = 'Exportovat do souboru';
var EXPORT_FROMFILE = 'Importovat ze souboru';
var EXPORT_TOSERV = 'Exportovat do serveru';
var EXPORT_FROMSERV = 'Importovat ze serveru';
var EXPORT_FROMOTHER = 'Importovat relace z jiných časovačů';
var EXPORT_USERID = 'Zadejte prosím váš účet (pouze abecedy nebo číslo)';
var EXPORT_INVID = 'Jenom abeceda nebo čísla jsou povolena!';
var EXPORT_ERROR = 'Došlo k chybám...';
var EXPORT_NODATA = 'Nenalezena žádná data pro tvůj účet';
var EXPORT_UPLOADED = 'Úspěšně nahráno';
var EXPORT_CODEPROMPT = 'Uložit tento kód, nebo napsat uložený kód pro import';
var EXPORT_ONLYOPT = 'jen Exportovací/Importovací Nastavení';
var EXPORT_ACCOUNT = 'Exportovat Účty';
var EXPORT_LOGINGGL = 'Přihlásit Pomocí Google Účtu';
var EXPORT_LOGINWCA = 'Přihlásit Pomocí WCA Účtu';
var EXPORT_LOGOUTCFM = 'Potvrdit odhlášení?';
var EXPORT_LOGINAUTHED = 'Autorizováno<br>Načítání Dat...';
var IMPORT_FINAL_CONFIRM = 'Toto přepíše všechna lokální data! Upraví %d relací, přidá %a odstraní %r řešení. Potvrdit import dat?';
var BUTTON_SCRAMBLE = 'Scramble';
var BUTTON_TOOLS = 'NÁSTROJE';
var IMAGE_UNAVAILABLE = 'Nedostupné pro tento typ scramblu';
var TOOLS_SELECTFUNC = 'Funkce';
var TOOLS_CROSS = 'složit kříž';
var TOOLS_EOLINE = 'složit EOLine';
var TOOLS_ROUX1 = 'složit Roux S1';
var TOOLS_222FACE = 'strana 2x2x2';
var TOOLS_GIIKER = 'Giiker kostka';
var TOOLS_IMAGE = 'nakreslit scramble';
var TOOLS_STATS = 'Statistiky';
var TOOLS_HUGESTATS = 'statistiky kříže';
var TOOLS_DISTRIBUTION = 'distribuce času';
var TOOLS_TREND = 'trend času';
var TOOLS_METRONOME = 'metronom';
var TOOLS_CFMTIME = 'Potvrďte čas';
var TOOLS_SOLVERS = 'Řešitelé';
var TOOLS_SYNCSEED = 'Běžné zamíchání';
var TOOLS_SYNCSEED_SEED = 'Semínko';
var TOOLS_SYNCSEED_INPUT = 'Vstupní semínko';
var TOOLS_SYNCSEED_30S = 'Použít semínko platné 30s';
var TOOLS_SYNCSEED_HELP = 'Pokud povoleno, bude zamíchání záviset pouze na nastavení semínka. Obecně lze říci, že pokud dva hráči sdílejí stejné semínko, získají stejné zamíchání.';
var TOOLS_SYNCSEED_DISABLE = 'Vypnout aktuální semínko?';
var TOOLS_SYNCSEED_INPUTA = 'Vložte hodnotu (a-zA-Z0-9) jako semínko';
var OLCOMP_UPDATELIST = 'Aktualizovat seznam soutěží';
var OLCOMP_VIEWRESULT = 'Zobrazit výsledek';
var OLCOMP_VIEWMYRESULT = 'Moje historie';
var OLCOMP_START = 'Začít!';
var OLCOMP_SUBMIT = 'Potvrdit!';
var OLCOMP_SUBMITAS = 'Potvrdit jako: ';
var OLCOMP_WCANOTICE = 'Potvrdit jako váš WCA účet? (Přihlašte se znovu pokud není účet po odeslání rozpoznán)';
var OLCOMP_OLCOMP = 'Online soutěž';
var OLCOMP_ANONYM = 'Anonym';
var OLCOMP_ME = 'Já';
var OLCOMP_WCAACCOUNT = 'Účet WCA';
var OLCOMP_ABORT = 'Zrušit soutěž a ukázat výsledky?';
var OLCOMP_WITHANONYM = 'S Anonymem';
var PROPERTY_IMGSIZE = 'Velikost zamíchaného obrázku';
var TIMER_INSPECT = 'zkontrolovat';
var TIMER_SOLVE = 'vyřešit';
var PROPERTY_USEMOUSE = 'použít časovač pomocí myši';
var PROPERTY_TIMEU = 'aktualizace timeru je';
var PROPERTY_TIMEU_STR = 'aktualizovat|0.1s|sekund|inspekce|nic';
var PROPERTY_PRETIME = 'čas držení mezery dole(sekund)';
var PROPERTY_ENTERING = 'vstup v dobách s';
var PROPERTY_ENTERING_STR = 'časovač|psaní|stackmat|MoYuČasovač|virtuální|Bluetooth|qCube';
var PROPERTY_INTUNIT = 'Jednotka při zadávání celého čísla';
var PROPERTY_INTUNIT_STR = 'sekunda|setina|tisícina';
var PROPERTY_COLOR = 'vybrat schéma barev';
var PROPERTY_COLORS = 'barva písma|barva pozadí|barva desky|barva tlačítka|odkaz barva|barva Loga|barva pozadí Loga';
var PROPERTY_VIEW = 'styl uživatelského rozhraní je';
var PROPERTY_VIEW_STR = 'Automaticky|Mobil|Obrazovka';
var PROPERTY_UIDESIGN = 'UI design je';
var PROPERTY_UIDESIGN_STR = 'Normální|Materiální design|Normální w/o stíny|Materiální design w/o stíny';
var COLOR_EXPORT = 'Prosím uložte soubor pro importování';
var COLOR_IMPORT = 'Prosím vložte exportovaný soubor';
var COLOR_FAIL = 'Špatná Data, Import Se Nepovedl';
var PROPERTY_FONTCOLOR_STR = 'černá|bíla';
var PROPERTY_COLOR_STR = 'ručně|importovat/exportovat...|náhodně|styl1|styl2|styl3|černá|bílá|styl6|slunečně tmavé|slunečně světlé';
var PROPERTY_FONT = 'vyberte písmo časovače';
var PROPERTY_FONT_STR = 'náhodně digitální|normální|digitální1|digitánlí2|digitální3|digitální4|digitální5';
var PROPERTY_FORMAT = 'formát času';
var PROPERTY_USEKSC = 'použít klávesové zkratky';
var PROPERTY_NTOOLS = 'počet nástrojů';
var PROPERTY_AHIDE = 'Skrýt všechny prvky při časování';
var SCRAMBLE_LAST = 'poslední';
var SCRAMBLE_NEXT = 'další';
var SCRAMBLE_SCRAMBLE = ' scramble';
var SCRAMBLE_LENGTH = 'délka';
var SCRAMBLE_INPUT = 'vstupní zamíchání';
var PROPERTY_VRCSPEED = 'VRS základní rychlost (tps)';
var PROPERTY_VRCMP = 'vícefázové';
var PROPERTY_VRCMPS = 'Nic|CFOP|CF+OP|CFFFFOP|CFFFFOOPP|Roux';
var PROPERTY_GIIKERVRC = 'Zobrazit virtuální Giiker kostku';
var PROPERTY_GIISOK_DELAY = 'Označit zamíchání pokud stojí';
var PROPERTY_GIISOK_DELAYS = '2s|3s|4s|5s|Nikdy|Správně zamícháno';
var PROPERTY_GIISOK_KEY = 'Označit zamíchaní s mezerou';
var PROPERTY_GIISOK_MOVE = 'Oznacit zamíchání s děláním';
var PROPERTY_GIISOK_MOVES = 'U4, R4, atd...|(U U\')2, (U\' U)2, atd...|Nikdy';
var PROPERTY_GIISBEEP = 'Pípnout když je zamícháno';
var PROPERTY_GIIRST = 'Restartovat Giiker kostku při připojení';
var PROPERTY_GIIRSTS = 'Vždy|rychle|nikdy';
var CONFIRM_GIIRST = 'Resetovat Giiker kostku jako zamíchanou?';
var PROPERTY_GIIAED = 'Automatická detekce hardwarové chyby';
var scrdata = [
['WCA', [
['3x3x3', "333", 0],
['2x2x2', "222so", 0],
['4x4x4', "444wca", -40],
['5x5x5', "555wca", -60],
['6x6x6', "666wca", -80],
['7x7x7', "777wca", -100],
['3x3 bld', "333ni", 0],
['3x3 fm', "333fm", 0],
['3x3 oh', "333oh", 0],
['clock', "clkwca", 0],
['megaminx', "mgmp", -70],
['pyraminx', "pyrso", -10],
['skewb', "skbso", 0],
['square-1', "sqrs", 0],
['4x4 bld', "444bld", -40],
['5x5 bld', "555bld", -60],
['3x3 mbld', "r3ni", 5]
]],
['Vstup', [
['Extern', "input", 0],
['Soutěž', "remoteComp", 0],
['Remote', "remoteOther", 0]
]],
['===WCA===', [
['--', "blank", 0]
]],
['3x3x3', [
["náhodný stav (WCA)", "333", 0],
['náhodný tah', "333o", 25],
['3x3x3 pro nooby', "333noob", 25],
['pouze hrany', "edges", 0],
['pouze rohy', "corners", 0],
['poslední vrstva', "ll", 0],
['zb poslední vrstva', "zbll", 0],
['rohy poslední vrstvy', "cll", 0],
['hrany poslední vrstvy', "ell", 0],
['posledních šest hran', "lse", 0],
['posledních šest hran & ltM, U & gt', "lsemu", 0],
['Roux L10P', "cmll", 0],
['kříž složený', "f2l", 0],
['poslední slot + poslední vrstva', "lsll2", 0],
['2GLL', "2gll", 0],
['ZBLS', "zbls", 0],
['ZZLL', "zzll", 0],
['OLL', "oll", 0],
['PLL', "pll", 0],
['EOLine', "eoline", 0],
['jednoduchý kříž', "easyc", 3],
['3x3 ft', "333ft", 0]
]],
['2x2x2', [
["náhodný stav (WCA)", "222so", 0],
['optimální', "222o", 0],
['3-gen', "2223", 25],
['EG', "222eg", 0],
['EG0', "222eg0", 0],
['EG1', "222eg1", 0],
['EG2', "222eg2", 0],
['Žádný bar', "222nb", 0]
]],
['4x4x4', [
["WCA", "444wca", -40],
['náhodný pohyb', "444m", 40],
['SiGN', "444", 40],
['YJ', "444yj", 40],
['4x4x4 hrany', "4edge", 8],
['R, r, U, u', "RrUu", 40]
]],
['5x5x5', [
["WCA", "555wca", 60],
['SiGN', "555", 60],
['5x5x5 hrany', "5edge", 8]
]],
['6x6x6', [
["WCA", "666wca", 80],
['SiGN', "666si", 80],
['prefix', "666p", 80],
['přípona', "666s", 80],
['6x6x6 strany', "6edge", 8]
]],
['7x7x7', [
["WCA", "777wca", 100],
['SiGN', "777si", 100],
['předpona', "777p", 100],
['přípona', "777s", 100],
['7x7x7 hrany', "7edge", 8]
]],
['Hodiny', [
['věci', "clk", 0],
['wca', "clkwca", 0],
['optimální', "clko", 0],
['stručně', "clkc", 0],
['efektivní pin řád', "clke", 0]
]],
['Megaminx', [
["WCA", "mgmp", 70],
['Mrkev', "mgmc", 70],
['starý styl', "mgmo", 70]
]],
['Pyraminx', [
["náhodný stav (WCA)", "pyrso", 10],
['optimální', "pyro", 0],
['náhodný tah', "pyrm", 25],
['L4E', "pyrl4e", 0],
['4 tips', "pyr4c", 0],
['No bar', "pyrnb", 0]
]],
['Skewb', [
["náhodný stav (WCA)", "skbso", 0],
['optimální', "skbo", 0],
['náhodný tah', "skb", 25],
['No bar', "skbnb", 0]
]],
['Square-1', [
["náhodný stav (WCA)", "sqrs", 0],
["CSP", "sqrcsp", 0],
['přední metrické otočení', "sq1h", 40],
['metrický twist', "sq1t", 20]
]],
['=== OSTATNÍ ===', [
['--', "blank", 0]
]],
['15 puzzle', [
['náhodný stav URLD', "15prp", 0],
['náhodný stav ^<>v', "15prap", 0],
['náhodný stav Blank', "15prmp", 0],
['náhodný tah URLD', "15p", 80],
['náhodný tah ^<>v', "15pat", 80],
['náhodný tah Blank', "15pm", 80]
]],
['8 puzzle', [
['náhodný stav URLD', "8prp", 0],
['náhodný stav ^<>v', "8prap", 0],
['náhodný stav Blank', "8prmp", 0]
]],
['LxMxN', [
['1x3x3 (Floppy Cube)', "133", 0],
['2x2x3 (Tower Cube)', "223", 0],
['2x3x3 (Domino)', "233", 25],
['3x3x4', "334", 40],
['3x3x5', "335", 25],
['3x3x6', "336", 40],
['3x3x7', "337", 40],
['8x8x8', "888", 120],
['9x9x9', "999", 120],
['10x10x10', "101010", 120],
['11x11x11', "111111", 120],
['NxNxN', "cubennn", 12]
]],
['Gear Cube', [
['náhodný stav', "gearso", 0],
['optimální', "gearo", 0],
['náhodný tah', "gear", 10]
]],
['Cmetrick', [
[' ', "cm3", 25]
]],
['Malý Cmetrick', [
[' ', "cm2", 25]
]],
['Gigaminx', [
['Pochmann', "giga", 300]
]],
['Helicopter Cube', [
[' ', "heli", 40]
]],
['Redi Cube', [
['MoYu', "redim", 8],
['starý', "redi", 20]
]],
['kostka Ivy', [
['náhodný stav', "ivyso", 0],
['optimální', "ivyo", 0],
['náhodný tah', "ivy", 10]
]],
['Master Pyraminx', [
[' ', "mpyr", 42]
]],
['Pyraminx krystal', [
['Pochmann', "prcp", 70],
['starý styl', "prco", 70]
]],
['Siamská kostka', [
['1x1x3 blok', "sia113", 25],
['1x2x3 blok', "sia123", 25],
['2x2x2 blok', "sia222", 25]
]],
['Square-2', [
[' ', "sq2", 20]
]],
['Super Floppy', [
[' ', "sfl", 25]
]],
['Super Square-1', [
['twist metrika', "ssq1t", 20]
]],
['UFO', [
['Jaap style', "ufo", 25]
]],
['"Ostatní"', [
['PSO (Přední Soutěžní Osmistěn)', "fto", 25]
]],
['==SPECIÁLNÍ==', [
['--', "blank", 0]
]],
['3 x 3 x 3 podskupiny', [
['2-generátor R,U', "2gen", 25],
['2-generátor L.U', "2genl", 25],
['Roux-generátor M,U', "roux", 25],
['3-generátor F,R,U', "3gen_F", 25],
['3-generátor R,U,L', "3gen_L", 25],
['3-generátor R,r,U', "RrU", 25],
['jen polovina otáčení', "half", 25],
['poslední slot + poslední vrstva (starý)', "lsll", 15]
]],
['Bangaged Kostka', [
['Bicube', "bic", 30],
['Čtverec-1 /,(1,0)', "bsq", 25]
]],
['Megaminx subsety', [
['2-generátor R,U', "minx2g", 30],
['poslední slot + poslední vrstva', "mlsll", 20]
]],
['Relace', [
['spousta 3x3x3', "r3", 5],
['234 relace', "r234", 0],
['2345 relace', "r2345", 0],
['23456 relace', "r23456", 0],
['234567 relace', "r234567", 0],
['234 relace (WCA)', "r234w", 0],
['2345 relace (WCA)', "r2345w", 0],
['23456 relace (WCA)', "r23456w", 0],
['234567 relace (WCA)', "r234567w", 0]
]],
['==VTIPY==', [
['--', "blank", 0]
]],
['1x1x1', [
['x y z', "111", 25]
]],
['-1x-1x-1', [
[' ', "-1", 25]
]],
['1x1x2', [
[' ', "112", 25]
]],
['LOL', [
[' ', "lol", 25]
]],
['Derrick Eide', [
[' ', "eide", 25]
]]
];
var SCRAMBLE_NOOBST = [
['otočit vrchní stranu', 'otočit spodní stranu'],
['otočit pravou stranu', 'otočit levou stranu'],
['otočit přední stranu', 'otočit zadní stranu']
];
var SCRAMBLE_NOOBSS = ' po směru hodin po 90 stupních,| proti směru hodin po 90 stupních,| po 180 supních,';
var STATS_CFM_RESET = 'resetovat všechny časy v této relaci?';
var STATS_CFM_DELSS = 'smazat relaci [%s]?';
var STATS_CFM_DELMUL = 'Číslo Smazaných Hodnot Z Aktuálního Indexu?';
var STATS_CFM_DELETE = 'smazat tento čas?';
var STATS_COMMENT = 'Okomentovat';
var STATS_REVIEW = 'Zkontrolovat';
var STATS_DATE = 'Datum';
var STATS_SSSTAT = 'statistika 1 řešení.';
var STATS_CURROUND = 'Statistiky Aktuálního Kola';
var STATS_CURSESSION = 'Statistiky Aktuální relace';
var STATS_CURSPLIT = 'Fáze %d Aktuální Statistiky Relace';
var STATS_EXPORTCSV = 'Exportovat CSV';
var STATS_SSMGR_TITLE = 'Správce Relací';
var STATS_SSMGR_NAME = 'Jméno';
var STATS_SSMGR_DETAIL = 'Detaily Relace';
var STATS_SSMGR_OPS = 'Přejmenovat|Vytvořit|Spojit|Rozpojit|Smazat|Seřadit';
var STATS_SSMGR_ORDER = 'Seřadit podle zamíchání';
var STATS_SSMGR_ODCFM = 'Řadit všechni relace jako zamíchání?';
var STATS_SSMGR_SORTCFM = '%d řešení bude přeřazeno, potvrdit?';
var STATS_ALERTMG = 'Spojit všechny časy v relaci [%f] do konce relace[%t]?';
var STATS_PROMPTSPL = 'Spojit počet posledních časů z relace[%s]?';
var STATS_ALERTSPL = 'Mělo by se rozdělit nebo nechat alespoň 1';
var STATS_AVG = 'průměr';
var STATS_SOLVE = 'vyřešit';
var STATS_TIME = 'čas';
var STATS_SESSION = 'Session';
var STATS_SESSION_NAME = 'Upravit jméno relace';
var STATS_SESSION_NAMEC = 'Jméno nové relace';
var STATS_STRING = 'nejlepší|aktuální|nejhorší|Generováno Časovačem na %D-%M-%Y|složení/celkem: %d|samotný|průměr %mk|průměrný z %mk|Průměrný: %v{(σ = %sgm)}|Pruměrný: %v|Časový List:|řešení %s do %e|Celkem utraceno: %d';
var STATS_PREC = 'precize distribuce času';
var STATS_PREC_STR = 'automaticky|0.1s|0.2s|0.5s|1s|2s|5s|10s|20s|50s|100s';
var STATS_TYPELEN = 'list %d typ|list %d délka|průměrný|průměr';
var STATS_STATCLR = 'Povolit vyprázdňování relace';
var STATS_ABSIDX = 'Zomrazit abolutní index ve zprávě o statistice';
var STATS_XSESSION_DATE = 'jakékoliv datum|minulých 24 hodin|minulých 7 dnů|minulých 30 dnů|minulých 365 dnů';
var STATS_XSESSION_NAME = 'jakkékoliv jméno';
var STATS_XSESSION_SCR = 'jakékoliv zamíchání';
var STATS_XSESSION_CALC = 'Calc';
var STATS_RSFORSS = 'Zobrazit statistiku při kliknutí na číslo řešení';
var PROPERTY_PRINTSCR = 'zobrazit zamíchání ve statistikách';
var PROPERTY_PRINTDATE = 'zobrazit datum složení ve statistikách';
var PROPERTY_SUMMARY = 'zobrazit shrnutí před časovím listem';
var PROPERTY_IMRENAME = 'přejmenovat relaci ihned po vytvoření';
var PROPERTY_SCR2SS = 'vytvořit novou relaci při změně typu zamíchání';
var PROPERTY_SS2SCR = 'obnovit typ zamíchání při změně relace';
var PROPERTY_SS2PHASES = 'obnovit vícefázové časování při relaci';
var PROPERTY_STATINV = 'Obrátit časový list';
var PROPERTY_STATAL = 'Statistické indikátory';
var PROPERTY_STATALU = 'Přispůsobený statický indikátor';
var PROPERTY_DELMUL = 'Povolit Více Odstranění';
var PROPERTY_TOOLSFUNC = 'Vybraná Funkce';
var PROPERTY_TRIM = 'Počet složení použitích na každé straně';
var PROPERTY_TRIM_MED = 'Medián';
var PROPERTY_STKHEAD = 'Použít Informace O Stavu Stackmatu';
var PROPERTY_HIDEFULLSOL = 'Ukázat řešení postupně';
var PROPERTY_IMPPREV = 'Importovat ne-aktuálnější data';
var PROPERTY_AUTOEXP = 'Automatický export dat (po 100 řešení)';
var PROPERTY_AUTOEXP_OPT = 'Nikdy|Do souboru|s ID csTimer|S účtem WCA';
var PROPERTY_SCRASIZE = 'Automatická velikost zamíchání';
var MODULE_NAMES = {
"kernel": 'globální',
"ui": 'displej',
"color": 'barva',
"timer": 'časovač',
"scramble": 'zamíchání',
"stats": 'statistiky',
"tools": 'nástroje',
"vrc": 'virtuální&<br>Giiker'
};
var BGIMAGE_URL = 'prosím vložte url obrázku';
var BGIMAGE_INVALID = 'neplatná adresa url';
var BGIMAGE_OPACITY = 'průhlednost pozadí obrázku';
var BGIMAGE_IMAGE = 'pozadí obrázku';
var BGIMAGE_IMAGE_STR = 'žádný|manuální|CCT';
var SHOW_AVG_LABEL = 'Zobrazit Průměrný Popisek';
var USE_LOGOHINT = 'Upozornění v logu';
var TOOLS_SCRGEN = 'Generátor Zamíchání';
var SCRGEN_NSCR = 'Počet zamíchání';
var SCRGEN_PRE = 'předpona';
var SCRGEN_GEN = 'Generovat Zamíchání!';
| {
"pile_set_name": "Github"
} |
package box_test
import (
crypto_rand "crypto/rand" // Custom so it's clear which rand we're using.
"fmt"
"io"
"golang.org/x/crypto/nacl/box"
)
func Example() {
senderPublicKey, senderPrivateKey, err := box.GenerateKey(crypto_rand.Reader)
if err != nil {
panic(err)
}
recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(crypto_rand.Reader)
if err != nil {
panic(err)
}
// You must use a different nonce for each message you encrypt with the
// same key. Since the nonce here is 192 bits long, a random value
// provides a sufficiently small probability of repeats.
var nonce [24]byte
if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil {
panic(err)
}
msg := []byte("Alas, poor Yorick! I knew him, Horatio")
// This encrypts msg and appends the result to the nonce.
encrypted := box.Seal(nonce[:], msg, &nonce, recipientPublicKey, senderPrivateKey)
// The recipient can decrypt the message using their private key and the
// sender's public key. When you decrypt, you must use the same nonce you
// used to encrypt the message. One way to achieve this is to store the
// nonce alongside the encrypted message. Above, we stored the nonce in the
// first 24 bytes of the encrypted text.
var decryptNonce [24]byte
copy(decryptNonce[:], encrypted[:24])
decrypted, ok := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
if !ok {
panic("decryption error")
}
fmt.Println(string(decrypted))
// Output: Alas, poor Yorick! I knew him, Horatio
}
func Example_precompute() {
senderPublicKey, senderPrivateKey, err := box.GenerateKey(crypto_rand.Reader)
if err != nil {
panic(err)
}
recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(crypto_rand.Reader)
if err != nil {
panic(err)
}
// The shared key can be used to speed up processing when using the same
// pair of keys repeatedly.
sharedEncryptKey := new([32]byte)
box.Precompute(sharedEncryptKey, recipientPublicKey, senderPrivateKey)
// You must use a different nonce for each message you encrypt with the
// same key. Since the nonce here is 192 bits long, a random value
// provides a sufficiently small probability of repeats.
var nonce [24]byte
if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil {
panic(err)
}
msg := []byte("A fellow of infinite jest, of most excellent fancy")
// This encrypts msg and appends the result to the nonce.
encrypted := box.SealAfterPrecomputation(nonce[:], msg, &nonce, sharedEncryptKey)
// The shared key can be used to speed up processing when using the same
// pair of keys repeatedly.
var sharedDecryptKey [32]byte
box.Precompute(&sharedDecryptKey, senderPublicKey, recipientPrivateKey)
// The recipient can decrypt the message using the shared key. When you
// decrypt, you must use the same nonce you used to encrypt the message.
// One way to achieve this is to store the nonce alongside the encrypted
// message. Above, we stored the nonce in the first 24 bytes of the
// encrypted text.
var decryptNonce [24]byte
copy(decryptNonce[:], encrypted[:24])
decrypted, ok := box.OpenAfterPrecomputation(nil, encrypted[24:], &decryptNonce, &sharedDecryptKey)
if !ok {
panic("decryption error")
}
fmt.Println(string(decrypted))
// Output: A fellow of infinite jest, of most excellent fancy
}
| {
"pile_set_name": "Github"
} |
import {
Placement,
Deletion,
Update,
PlacementAndUpdate
} from 'shared/ReactSideEffectTags';
import {
HostRoot,
HostText,
HostComponent,
FunctionComponent
} from 'shared/ReactWorkTags';
import {
insertBefore,
appendChild,
commitUpdate,
removeChild
} from 'reactDOM/ReactHostConfig';
import {
Passive
} from 'shared/ReactSideEffectTags';
import {
NoEffect
} from 'shared/ReactSideEffectTags';
import {
HasEffect as HookHasEffect,
Passive as HookPassive
} from 'shared/ReactHookEffectTags';
import * as Scheduler from 'scheduler';
import { NoWork } from './ReactFiberExpirationTime';
import {
NoPriority,
NormalPriority,
runWithPriority,
flushSyncCallbackQueue
} from 'scheduler';
import {
getCurrentExecutionContext,
setCurrentExecutionContext,
CommitContext
} from './ReactFiberWorkLoop';
// 在React中commitWork中大部分逻辑是杂糅在workloop中的,我将他们抽离到commitWork
// 为了在workLoop和当前模块间公用全局变量
export const globalVariables = {
rootWithPendingPassiveEffects: null,
rootDoesHavePassiveEffects: false,
pendingPassiveEffectsExpirationTime: NoWork,
pendingPassiveEffectsRenderPriority: NoPriority
};
function getHostParentFiber(fiber) {
let parent = fiber.return;
while(parent) {
if (isHostParent(parent)) {
return parent;
}
parent = parent.return;
}
}
function isHostParent(parent) {
return (
parent.tag === HostRoot ||
parent.tag === HostComponent
)
}
// 目标DOM需要插入在哪个DOM之前(DOMElement.insertBefore)
function getHostSibling(fiber) {
let node = fiber;
// 嵌套循环的原因是 fiber节点可能没有对应DOM节点,相应的fiber树层级和DOM树也不一定匹配
siblings: while(true) {
while (!node.sibling) {
// 考虑 fiber.return 是 FunctionComponent,fiber.return.sibling 是 HostCompoennt
// 则 fiber.stateNode 和 fiber.return.sibling.stateNode在DOM树上是兄弟关系
if (!node.return || isHostParent(node.return)) {
return null;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
// 当前节点不是Host节点,目标节点不能直接插在当前节点之前
while (node.tag !== HostComponent && node.tag !== HostText) {
if (node.effectTag & Placement) {
// 如果当前节点也是需要执行插入操作,再进行一次整个流程
continue siblings;
}
// 节点不是Host节点,但是他的子节点如果是Host节点,则目标DOM和子节点DOM是兄弟节点
// 目标DOM应该插入在子节点DOM前面
// 如果节点没有子节点,则继续寻找兄弟节点
if (!node.child) {
continue siblings;
} else {
node.child.return = node;
node = node.child;
}
}
// 到这一步时一定是一个Host节点,判断下该节点是否也是需要插入的节点
if (!(node.effectTag & Placement)) {
return node.stateNode;
}
}
}
function commitPlacement(finishedWork) {
const parentFiber = getHostParentFiber(finishedWork);
const parentStateNode = parentFiber.stateNode;
let parent;
switch (parentFiber.tag) {
case HostComponent:
parent = parentStateNode;
break;
case HostRoot:
parent = parentStateNode.containerInfo;
break;
}
// 目标DOM节点需要插入在谁之前
const before = getHostSibling(finishedWork);
insertOrAppendPlacementNode(finishedWork, before, parent);
}
function commitWork(current, finishedWork) {
switch (finishedWork.tag) {
case FunctionComponent:
// TODO layoutEffect 在 mutation阶段执行destroy
// 由于 layoutEffect 的 create是在commitRoot尾部执行,所以任何fiber的任何layoutEffect destroy会先于任何fiber的任何layoutEffect create执行
// 这避免了兄弟fiber互相影响
// ex:在同一个commit阶段,一个FunctionComponent的destroy不应该复写掉另一个FunctionComponent在create中设置的ref
return;
case HostComponent:
// 处理组件completeWork产生的updateQueue
const instance = finishedWork.stateNode;
if (instance) {
const updatePayload = finishedWork.updateQueue;
finishedWork.updatePayload = null;
if (updatePayload) {
commitUpdate(instance, updatePayload);
}
}
return;
}
}
function commitUnmount(finishedRoot, current) {
// TODO 触发 componentWillUnmout 清除ref等操作
}
function commitNestedUnmounts(finishedRoot, root) {
// 整体采用深度优先遍历 树结构
let node = root;
while (true) {
commitUnmount(finishedRoot, node);
if (node.child) {
node.child.return = node;
node = node.child;
continue;
}
if (node === root) {
return;
}
while (!node.sibling) {
if (!node.return || node.return === root) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
function unmountHostComponents(finishedRoot, current) {
// 当前节点可能是FunctionComponent,或者ClassComponent之类
// 即当前节点可能没有对应的DOM节点
// 所以有可能需要child、child.sibling遍历
// 所以这是个循环的过程
let node = current;
// 当找到要删除节点的父级DOM节点,该变量置为true,这样当遍历到zi节点时不会再执行寻找父级DOM节点的操作
let currentParentIsValid = false;
let currentParent;
while (true) {
// 这个循环到目的是找到要删除的目标节点的父级DOM节点
if (!currentParentIsValid) {
let parent = node.return;
findParent: while (true) {
const parentStateNode = parent.stateNode;
switch (parent.tag) {
case HostComponent:
currentParent = parentStateNode;
break findParent;
case HostRoot:
currentParent = parentStateNode.containerInfo;
break findParent;
}
parent = parent.return;
}
currentParentIsValid = true;
}
if (node.tag === HostComponent || node.tag === HostText) {
// 我们需要遍历下去每个节点,直到叶子节点,从叶子节点触发 componentWillUnmount,再一直往上到当前节点
commitNestedUnmounts(finishedRoot, node);
removeChild(currentParent, node.stateNode);
} else {
// 同commitNestedUnmounts一样的深度优先遍历
commitUnmount(finishedRoot, node);
if (node.child) {
node.child.return = node;
node = node.child;
continue;
}
}
if (node === current) {
return;
}
while (!node.sibling) {
if (!node.return || node.return === current) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
function commitDeletion(finishedRoot, current) {
unmountHostComponents(finishedRoot, current);
}
function insertOrAppendPlacementNode(fiber, before, parent) {
const {tag} = fiber;
if (tag === HostComponent || tag === HostText) {
const stateNode = fiber.stateNode;
if (before) {
insertBefore(parent, stateNode, before);
} else {
appendChild(parent, stateNode);
}
} else {
// 当前fiber不是host类型,递归其子fiber
const child = fiber.child;
if (child) {
insertOrAppendPlacementNode(child, before, parent);
// 对于ClassComponent FunctionComponent 可能返回一个数组,即有多个需要插入的节点
// 所以还需要遍历其兄弟节点执行插入
const sibling = child.sibling;
while (sibling) {
insertOrAppendPlacementNode(sibling, before, parent);
sibling = sibling.sibling;
}
}
}
}
export function flushPassiveEffects() {
if (globalVariables.pendingPassiveEffectsRenderPriority !== NoPriority) {
// passiveEffects 的优先级按 <= NormalPriority
const prioriyLevel = globalVariables.pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : globalVariables.pendingPassiveEffectsRenderPriority;
globalVariables.pendingPassiveEffectsRenderPriority = NoPriority;
return runWithPriority(prioriyLevel, flushPassiveEffectsImpl);
}
}
// 遍历effectList执行 passive effect
function flushPassiveEffectsImpl() {
// 该变量在commitRoot DOM渲染完成后被赋值
if (!globalVariables.rootWithPendingPassiveEffects) {
return false;
}
const root = globalVariables.rootWithPendingPassiveEffects;
globalVariables.rootWithPendingPassiveEffects = null;
const expirationTime = globalVariables.pendingPassiveEffectsExpirationTime;
globalVariables.pendingPassiveEffectsExpirationTime = NoWork;
const prevExecutionContext = getCurrentExecutionContext();
setCurrentExecutionContext(CommitContext);
let effect = root.current.firstEffect;
while (effect) {
try {
commitPassiveHookEffects(effect);
} catch(e) {
// TODO captureCommitPhaseError
console.warn(e);
}
const nextNextEffect = effect.nextEffect;
effect.nextEffect = null;
effect = nextNextEffect;
}
setCurrentExecutionContext(prevExecutionContext);
flushSyncCallbackQueue();
return true;
}
// commit阶段的第一项工作(before mutation)
// 调用ClassComponent getSnapshotBeforeUpdate生命周期钩子
// 异步调用 前一次useEffect的destroy和下一次的mount
// 由于 commitHookEffectListUnmount 调用后会马上调用 commitHookEffectListMount,
// 所以前一次同一个useEffect的destroy和下一次的mount是依次同步调用的
export function commitBeforeMutationEffects(nextEffect) {
if (nextEffect) {
// TODO getSnapshotBeforeUpdate生命周期钩子
const effectTag = nextEffect.effectTag;
if ((effectTag & Passive) !== NoEffect) {
// 与 componentDidMount 或 componentDidUpdate 不同,useEffect是在DOM更新后异步调用的
// 所以不会阻塞页面渲染,见下文
// https://zh-hans.reactjs.org/docs/hooks-effect.html#detailed-explanation
if (!globalVariables.rootDoesHavePassiveEffects) {
// 标记rootDoesHavePassiveEffects为true,在commitRoot中渲染完DOM后会为rootWithPendingPassiveEffects赋值
globalVariables.rootDoesHavePassiveEffects = true;
Scheduler.scheduleCallback(Scheduler.NormalPriority ,() => {
flushPassiveEffects();
return null;
});
}
}
nextEffect = nextEffect.nextEffect;
}
return nextEffect;
}
// 处理DOM增删查改
export function commitMutationEffects(root, nextEffect) {
while (nextEffect) {
const effectTag = nextEffect.effectTag;
// 处理 Placement / Update / Deletion,排除其他effectTag干扰
const primaryEffectTag = effectTag & (Placement | Deletion | Update);
let current;
switch (primaryEffectTag) {
case Placement:
commitPlacement(nextEffect);
// 去掉已使用的effectTag
nextEffect.effectTag &= ~Placement;
break;
case Update:
current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
case Deletion:
commitDeletion(root, nextEffect);
break;
case PlacementAndUpdate:
// Placement
commitPlacement(nextEffect);
nextEffect.effectTag &= ~Placement;
// Update
current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
}
nextEffect = nextEffect.nextEffect;
}
return null;
}
function commitHookEffectListUnmount(tag, finishedWork) {
const updateQueue = finishedWork.updateQueue;
let lastEffect = updateQueue ? updateQueue.lastEffect : null;
if (lastEffect) {
const firstEffect = lastEffect.next;
let effect = firstEffect;
do {
if ((effect.tag & tag) === tag) {
// unmount
const destroy = effect.destroy;
effect.destroy = undefined;
if (destroy) {
destroy();
}
}
effect = effect.next;
} while (effect !== firstEffect)
}
}
function commitHookEffectListMount(tag, finishedWork) {
const updateQueue = finishedWork.updateQueue;
let lastEffect = updateQueue ? updateQueue.lastEffect : null;
if (lastEffect) {
const firstEffect = lastEffect.next;
let effect = firstEffect;
do {
if ((effect.tag & tag) === tag) {
// mount
const create = effect.create;
effect.destroy = create();
}
effect = effect.next;
} while (effect !== firstEffect)
}
}
function commitPassiveHookEffects(finishedWork) {
if ((finishedWork.effectTag & Passive) !== NoEffect) {
switch (finishedWork.tag) {
case FunctionComponent:
// 遍历updateQueue执行 useEffect unmount函数
commitHookEffectListUnmount(HookPassive | HookHasEffect, finishedWork);
commitHookEffectListMount(HookPassive | HookHasEffect, finishedWork);
break;
default:
break;
}
}
} | {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Barcode
* @subpackage Renderer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Image.php 20366 2010-01-18 03:56:52Z ralph $
*/
/** @see Zend_Barcode_Renderer_RendererAbstract*/
#require_once 'Zend/Barcode/Renderer/RendererAbstract.php';
/**
* Class for rendering the barcode as svg
*
* @category Zend
* @package Zend_Barcode
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Barcode_Renderer_Svg extends Zend_Barcode_Renderer_RendererAbstract
{
/**
* Resource for the image
* @var DOMDocument
*/
protected $_resource = null;
/**
* Root element of the XML structure
* @var DOMElement
*/
protected $_rootElement = null;
/**
* Height of the rendered image wanted by user
* @var integer
*/
protected $_userHeight = 0;
/**
* Width of the rendered image wanted by user
* @var integer
*/
protected $_userWidth = 0;
/**
* Set height of the result image
*
* @param null|integer $value
* @return Zend_Image_Barcode_Abstract
* @throws Zend_Barcode_Renderer_Exception
*/
public function setHeight($value)
{
if (!is_numeric($value) || intval($value) < 0) {
#require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Svg height must be greater than or equals 0'
);
}
$this->_userHeight = intval($value);
return $this;
}
/**
* Get barcode height
*
* @return int
*/
public function getHeight()
{
return $this->_userHeight;
}
/**
* Set barcode width
*
* @param mixed $value
* @return self
* @throws Zend_Barcode_Renderer_Exception
*/
public function setWidth($value)
{
if (!is_numeric($value) || intval($value) < 0) {
#require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Svg width must be greater than or equals 0'
);
}
$this->_userWidth = intval($value);
return $this;
}
/**
* Get barcode width
*
* @return int
*/
public function getWidth()
{
return $this->_userWidth;
}
/**
* Set an image resource to draw the barcode inside
*
* @param $svg
* @return Zend_Barcode_Renderer
* @throws Zend_Barcode_Renderer_Exception
*/
public function setResource($svg)
{
if (!$svg instanceof DOMDocument) {
#require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Invalid DOMDocument resource provided to setResource()'
);
}
$this->_resource = $svg;
return $this;
}
/**
* Initialize the image resource
*
* @return void
*/
protected function _initRenderer()
{
$barcodeWidth = $this->_barcode->getWidth(true);
$barcodeHeight = $this->_barcode->getHeight(true);
$backgroundColor = $this->_barcode->getBackgroundColor();
$imageBackgroundColor = 'rgb(' . implode(', ', array(($backgroundColor & 0xFF0000) >> 16,
($backgroundColor & 0x00FF00) >> 8,
($backgroundColor & 0x0000FF))) . ')';
$width = $barcodeWidth;
$height = $barcodeHeight;
if ($this->_userWidth && $this->_barcode->getType() != 'error') {
$width = $this->_userWidth;
}
if ($this->_userHeight && $this->_barcode->getType() != 'error') {
$height = $this->_userHeight;
}
if ($this->_resource === null) {
$this->_resource = new DOMDocument('1.0', 'utf-8');
$this->_resource->formatOutput = true;
$this->_rootElement = $this->_resource->createElement('svg');
$this->_rootElement->setAttribute('xmlns', "http://www.w3.org/2000/svg");
$this->_rootElement->setAttribute('version', '1.1');
$this->_rootElement->setAttribute('width', $width);
$this->_rootElement->setAttribute('height', $height);
$this->_appendRootElement('title',
array(),
"Barcode " . strtoupper($this->_barcode->getType()) . " " . $this->_barcode->getText());
} else {
$this->_readRootElement();
$width = $this->_rootElement->getAttribute('width');
$height = $this->_rootElement->getAttribute('height');
}
$this->_adjustPosition($height, $width);
$this->_appendRootElement('rect',
array('x' => $this->_leftOffset,
'y' => $this->_topOffset,
'width' => ($this->_leftOffset + $barcodeWidth - 1),
'height' => ($this->_topOffset + $barcodeHeight - 1),
'fill' => $imageBackgroundColor));
}
protected function _readRootElement()
{
if ($this->_resource !== null) {
$this->_rootElement = $this->_resource->documentElement;
}
}
/**
* Append a new DOMElement to the root element
*
* @param string $tagName
* @param array $attributes
* @param string $textContent
*/
protected function _appendRootElement($tagName, $attributes = array(), $textContent = null)
{
$newElement = $this->_createElement($tagName, $attributes, $textContent);
$this->_rootElement->appendChild($newElement);
}
/**
* Create DOMElement
*
* @param string $tagName
* @param array $attributes
* @param string $textContent
* @return DOMElement
*/
protected function _createElement($tagName, $attributes = array(), $textContent = null)
{
$element = $this->_resource->createElement($tagName);
foreach ($attributes as $k =>$v) {
$element->setAttribute($k, $v);
}
if ($textContent !== null) {
$element->appendChild(new DOMText((string) $textContent));
}
return $element;
}
/**
* Check barcode parameters
*
* @return void
*/
protected function _checkParams()
{
$this->_checkDimensions();
}
/**
* Check barcode dimensions
*
* @return void
* @throws Zend_Barcode_Renderer_Exception
*/
protected function _checkDimensions()
{
if ($this->_resource !== null) {
$this->_readRootElement();
$height = (float) $this->_rootElement->getAttribute('height');
if ($height < $this->_barcode->getHeight(true)) {
#require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Barcode is define outside the image (height)'
);
}
} else {
if ($this->_userHeight) {
$height = $this->_barcode->getHeight(true);
if ($this->_userHeight < $height) {
#require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(sprintf(
"Barcode is define outside the image (calculated: '%d', provided: '%d')",
$height,
$this->_userHeight
));
}
}
}
if ($this->_resource !== null) {
$this->_readRootElement();
$width = $this->_rootElement->getAttribute('width');
if ($width < $this->_barcode->getWidth(true)) {
#require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Barcode is define outside the image (width)'
);
}
} else {
if ($this->_userWidth) {
$width = (float) $this->_barcode->getWidth(true);
if ($this->_userWidth < $width) {
#require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(sprintf(
"Barcode is define outside the image (calculated: '%d', provided: '%d')",
$width,
$this->_userWidth
));
}
}
}
}
/**
* Draw the barcode in the rendering resource
* @return mixed
*/
public function draw()
{
parent::draw();
$this->_resource->appendChild($this->_rootElement);
return $this->_resource;
}
/**
* Draw and render the barcode with correct headers
*
* @return mixed
*/
public function render()
{
$this->draw();
header("Content-Type: image/svg+xml");
echo $this->_resource->saveXML();
}
/**
* Draw a polygon in the svg resource
*
* @param array $points
* @param integer $color
* @param boolean $filled
*/
protected function _drawPolygon($points, $color, $filled = true)
{
$color = 'rgb(' . implode(', ', array(($color & 0xFF0000) >> 16,
($color & 0x00FF00) >> 8,
($color & 0x0000FF))) . ')';
$orientation = $this->getBarcode()->getOrientation();
$newPoints = array(
$points[0][0] + $this->_leftOffset,
$points[0][1] + $this->_topOffset,
$points[1][0] + $this->_leftOffset,
$points[1][1] + $this->_topOffset,
$points[2][0] + $this->_leftOffset + cos(-$orientation),
$points[2][1] + $this->_topOffset - sin($orientation),
$points[3][0] + $this->_leftOffset + cos(-$orientation),
$points[3][1] + $this->_topOffset - sin($orientation),
);
$newPoints = implode(' ', $newPoints);
$attributes['points'] = $newPoints;
$attributes['fill'] = $color;
$this->_appendRootElement('polygon', $attributes);
}
/**
* Draw a polygon in the svg resource
*
* @param string $text
* @param float $size
* @param array $position
* @param string $font
* @param integer $color
* @param string $alignment
* @param float|int $orientation
*/
protected function _drawText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0)
{
$color = 'rgb(' . implode(', ', array(($color & 0xFF0000) >> 16,
($color & 0x00FF00) >> 8,
($color & 0x0000FF))) . ')';
$attributes['x'] = $position[0] + $this->_leftOffset;
$attributes['y'] = $position[1] + $this->_topOffset;
//$attributes['font-family'] = $font;
$attributes['color'] = $color;
$attributes['font-size'] = $size * 1.2;
switch ($alignment) {
case 'left':
$textAnchor = 'start';
break;
case 'right':
$textAnchor = 'end';
break;
case 'center':
default:
$textAnchor = 'middle';
}
$attributes['style'] = 'text-anchor: ' . $textAnchor;
$attributes['transform'] = 'rotate('
. (- $orientation)
. ', '
. ($position[0] + $this->_leftOffset)
. ', ' . ($position[1] + $this->_topOffset)
. ')';
$this->_appendRootElement('text', $attributes, $text);
}
}
| {
"pile_set_name": "Github"
} |
package com.juns.wechat.widght.swipe.adapters;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.juns.wechat.widght.swipe.SwipeLayout;
import com.juns.wechat.widght.swipe.implments.SwipeItemMangerImpl;
import com.juns.wechat.widght.swipe.interfaces.SwipeAdapterInterface;
import com.juns.wechat.widght.swipe.interfaces.SwipeItemMangerInterface;
public abstract class CursorSwipeAdapter extends CursorAdapter implements
SwipeItemMangerInterface, SwipeAdapterInterface {
private SwipeItemMangerImpl mItemManger = new SwipeItemMangerImpl(this);
protected CursorSwipeAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
}
protected CursorSwipeAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
boolean convertViewIsNull = convertView == null;
View v = super.getView(position, convertView, parent);
if (convertViewIsNull) {
mItemManger.initialize(v, position);
} else {
mItemManger.updateConvertView(v, position);
}
return v;
}
@Override
public void openItem(int position) {
mItemManger.openItem(position);
}
@Override
public void closeItem(int position) {
mItemManger.closeItem(position);
}
@Override
public void closeAllExcept(SwipeLayout layout) {
mItemManger.closeAllExcept(layout);
}
@Override
public List<Integer> getOpenItems() {
return mItemManger.getOpenItems();
}
@Override
public List<SwipeLayout> getOpenLayouts() {
return mItemManger.getOpenLayouts();
}
@Override
public void removeShownLayouts(SwipeLayout layout) {
mItemManger.removeShownLayouts(layout);
}
@Override
public boolean isOpen(int position) {
return mItemManger.isOpen(position);
}
@Override
public SwipeItemMangerImpl.Mode getMode() {
return mItemManger.getMode();
}
@Override
public void setMode(SwipeItemMangerImpl.Mode mode) {
mItemManger.setMode(mode);
}
}
| {
"pile_set_name": "Github"
} |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%reload_ext autoreload\n",
"%autoreload 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from nb_004 import *"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"DATA_PATH = Path('../data')\n",
"PATH = DATA_PATH/'caltech101'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data_mean,data_std = map(tensor, ([0.5355,0.5430,0.5280], [0.2909,0.2788,0.2979]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#export\n",
"class ImageDataset(Dataset):\n",
" def __init__(self, fns, labels, classes=None):\n",
" if classes is None: classes = list(set(labels))\n",
" self.classes = classes\n",
" self.class2idx = {v:k for k,v in enumerate(classes)}\n",
" self.fns = np.array(fns)\n",
" self.y = [self.class2idx[o] for o in labels]\n",
" \n",
" @classmethod\n",
" def from_folder(cls, folder, classes=None, test_pct=0., tfms=None):\n",
" if classes is None: classes = [cls.name for cls in find_classes(folder)]\n",
" \n",
" fns,labels = [],[]\n",
" for cl in classes:\n",
" fnames = get_image_files(folder/cl)\n",
" fns += fnames\n",
" labels += [cl] * len(fnames)\n",
" \n",
" if test_pct==0.: return cls(fns, labels)\n",
" fns,labels = np.array(fns),np.array(labels)\n",
" is_test = np.random.uniform(size=(len(fns),)) < test_pct\n",
" return cls(fns[~is_test], labels[~is_test]), cls(fns[is_test], labels[is_test])\n",
"\n",
" def __len__(self): return len(self.fns)\n",
"\n",
" def __getitem__(self,i):\n",
" x = PIL.Image.open(self.fns[i]).convert('RGB')\n",
" x = pil2tensor(x)\n",
" return x,self.y[i]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@reg_transform\n",
"def crop_with_ratio(x, scale:uniform, ratio:uniform, invert:rand_bool, row_pct:uniform, col_pct:uniform) -> TfmType.Start:\n",
" #scale, ratio and invert are supposed to have a size corresponding to the number of attempts before fallback.\n",
" for s,r,i in zip(scale, ratio, invert):\n",
" area = x.size(1) * x.size(2)\n",
" target_area = area * s\n",
" cols = int(round(math.sqrt(target_area * r)))\n",
" rows = int(round(math.sqrt(target_area / r)))\n",
"\n",
" if i: cols,rows = rows,cols\n",
"\n",
" if cols <= x.size(2) and rows <= x.size(1):\n",
" row = int((x.size(1)-rows+1)*row_pct)\n",
" col = int((x.size(2)-cols+1)*col_pct)\n",
" return x[:, row:row+rows, col:col+cols].contiguous()\n",
" # Fallback\n",
" rows = min(x.size(1), x.size(2))\n",
" row = (x.size(1) - rows) // 2\n",
" col = (x.size(2) - rows) // 2\n",
" return x[:, row:row+rows, col:col+rows].contiguous()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@reg_transform\n",
"def center_crop(x, b:uniform=0.5) -> TfmType.Pixel:\n",
" rows = min(x.size(1), x.size(2))\n",
" row = (x.size(1) - rows) // 2\n",
" col = (x.size(2) - rows) // 2\n",
" return x[:, row:row+rows, col:col+rows].contiguous()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#random_resized_crop = crop_with_ratio_tfm(scale=(0.5,1.,10), ratio=(0.75,1.33,10),invert=(0.5,10),\n",
"# row_pct=(0,1.), col_pct=(0,1.))\n",
"random_resized_crop = zoom_squish_tfm(scale=(0.5,1,10), squish=(0.75,1.33,10), invert=(0.5,10),\n",
" row_pct=(0,1.), col_pct=(0,1.))\n",
"center_crop1 = zoom_squish_tfm(scale=(1.1,1.1,2), squish=(1,1,2), invert=(0.5,2))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sz = 224\n",
"trn_tfms = [random_resized_crop,\n",
" flip_lr_tfm(p=0.5),\n",
" normalize_tfm(mean=data_mean,std=data_std)] #torchvision.transforms.RandomRotation(10),\n",
"val_tfms = [center_crop1,\n",
" normalize_tfm(mean=data_mean,std=data_std)]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#classes = ['airplanes','Motorbikes','Faces','watch','Leopards']\n",
"np.random.seed(42)\n",
"train_ds,valid_ds = ImageDataset.from_folder(PATH, test_pct=0.2)\n",
"classes = train_ds.classes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"train_ds = TfmDataset(train_ds, trn_tfms, size=224)\n",
"valid_ds = TfmDataset(valid_ds, val_tfms, size=224)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x,y = train_ds[0]\n",
"x,y = valid_ds[0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = DataBunch(train_ds, valid_ds, bs=64, num_workers=8)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def conv_layer(ni, nf, ks=3, stride=1):\n",
" return nn.Sequential(\n",
" nn.Conv2d(ni, nf, kernel_size=ks, bias=False, stride=stride, padding=ks//2),\n",
" nn.BatchNorm2d(nf),\n",
" nn.LeakyReLU(negative_slope=0.1, inplace=True))\n",
"\n",
"class ResLayer(nn.Module):\n",
" def __init__(self, ni):\n",
" super().__init__()\n",
" self.conv1=conv_layer(ni, ni//2, ks=1)\n",
" self.conv2=conv_layer(ni//2, ni, ks=3)\n",
" \n",
" def forward(self, x): return x + self.conv2(self.conv1(x))\n",
"\n",
"class Darknet(nn.Module):\n",
" def make_group_layer(self, ch_in, num_blocks, stride=1):\n",
" return [conv_layer(ch_in, ch_in*2,stride=stride)\n",
" ] + [(ResLayer(ch_in*2)) for i in range(num_blocks)]\n",
"\n",
" def __init__(self, num_blocks, num_classes, nf=32):\n",
" super().__init__()\n",
" layers = [conv_layer(3, nf, ks=3, stride=1)]\n",
" for i,nb in enumerate(num_blocks):\n",
" layers += self.make_group_layer(nf, nb, stride=2-(i==1))\n",
" nf *= 2\n",
" layers += [nn.AdaptiveAvgPool2d(1), Flatten(), nn.Linear(nf, num_classes)]\n",
" self.layers = nn.Sequential(*layers)\n",
" \n",
" def forward(self, x): return self.layers(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model = Darknet([1, 2, 4, 6, 2, 1], num_classes=len(classes), nf=16).cuda()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Recorder(Callback):\n",
" beta = 0.98\n",
" \n",
" def __init__(self, opt, train_dl=None):\n",
" self.opt,self.train_dl = opt,train_dl\n",
" \n",
" def on_train_begin(self):\n",
" self.epoch,self.n,self.avg_loss = 0,0,0.\n",
" self.losses,self.val_losses,self.lrs,self.moms,self.metrics = [],[],[],[],[]\n",
" \n",
" def on_batch_begin(self, xb, yb):\n",
" self.lrs.append(self.opt.lr)\n",
" self.moms.append(self.opt.mom)\n",
" return xb, yb\n",
" \n",
" def on_backward_begin(self, loss, out):\n",
" #We record the loss here before any other callback has a chance to modify it.\n",
" self.n += 1\n",
" self.avg_loss = self.beta * self.avg_loss + (1-self.beta) * loss.item()\n",
" self.smooth_loss = self.avg_loss / (1 - self.beta ** self.n)\n",
" self.losses.append(self.smooth_loss)\n",
" if self.train_dl is not None and self.train_dl.progress_func is not None: \n",
" self.train_dl.gen.set_postfix_str(self.smooth_loss)\n",
" \n",
" def on_epoch_end(self, val_metrics):\n",
" if val_metrics is not None:\n",
" self.val_losses.append(val_metrics[0])\n",
" if len(val_metrics) > 1: self.metrics.append(val_metrics[1:])\n",
" print(self.epoch, self.smooth_loss, *val_metrics)\n",
" self.epoch += 1\n",
" \n",
" def plot_lr(self, show_moms=False):\n",
" iterations = list(range(len(learn.recorder.lrs)))\n",
" if show_moms:\n",
" fig, axs = plt.subplots(1,2, figsize=(12,4))\n",
" axs[0].plot(iterations, self.lrs)\n",
" axs[1].plot(iterations, self.moms)\n",
" else: plt.plot(iterations, self.lrs)\n",
" \n",
" def plot(self, skip_start=10, skip_end=5):\n",
" lrs = self.lrs[skip_start:-skip_end] if skip_end > 0 else self.lrs[skip_start:]\n",
" losses = self.losses[skip_start:-skip_end] if skip_end > 0 else self.losses[skip_start:]\n",
" fig, ax = plt.subplots(1,1)\n",
" ax.plot(lrs, losses)\n",
" ax.set_xscale('log') "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## First training: SGD with 1cycle"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def accuracy(out, yb):\n",
" preds = torch.max(out, dim=1)[1]\n",
" return (preds==yb).float().mean()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from typing import Callable, List"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@dataclass\n",
"class Learner():\n",
" \n",
" loss_fn: Callable = F.cross_entropy\n",
" opt_fn: Callable = optim.SGD\n",
" metrics: List = None\n",
" \n",
" def __init__(self, data, model):\n",
" self.data,self.model = data,model.to(data.device)\n",
"\n",
" def fit(self, epochs, lr, wd=0, callbacks=None):\n",
" self.opt = HPOptimizer(self.model.parameters(), self.opt_fn, init_lr=lr)\n",
" self.opt.wd = wd\n",
" self.recorder = Recorder(self.opt, self.data.train_dl)\n",
" callbacks.insert(0, self.recorder)\n",
" fit(epochs, self.model, self.loss_fn, self.opt, self.data, callbacks=callbacks, metrics=self.metrics)\n",
" \n",
" def lr_find(self, start_lr=1e-5, end_lr=10, num_it=200):\n",
" cb = LRFinder(self, start_lr, end_lr, num_it)\n",
" a = int(np.ceil(num_it/len(self.data.train_dl)))\n",
" self.fit(a, start_lr, callbacks=[cb])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#export\n",
"def loss_batch(model, xb, yb, loss_fn, opt=None, cb_handler=None, metrics=None):\n",
" out = model(xb)\n",
" loss = loss_fn(out, yb)\n",
" mets = [f(out,yb).item() for f in metrics] if metrics is not None else []\n",
" \n",
" if opt is not None:\n",
" if cb_handler is not None: loss = cb_handler.on_backward_begin(loss, out)\n",
" loss.backward()\n",
" if cb_handler is not None: cb_handler.on_backward_end()\n",
" opt.step()\n",
" if cb_handler is not None: cb_handler.on_step_end()\n",
" opt.zero_grad()\n",
" \n",
" return (loss.item(),) + tuple(mets) + (len(xb),)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#export\n",
"def fit(epochs, model, loss_fn, opt, data, callbacks=None, metrics=None):\n",
" \n",
" cb_handler = CallbackHandler(callbacks)\n",
" cb_handler.on_train_begin()\n",
" \n",
" for epoch in tnrange(epochs):\n",
" model.train()\n",
" cb_handler.on_epoch_begin()\n",
" \n",
" for xb,yb in data.train_dl:\n",
" xb, yb = cb_handler.on_batch_begin(xb, yb)\n",
" loss,_ = loss_batch(model, xb, yb, loss_fn, opt, cb_handler)\n",
" if cb_handler.on_batch_end(loss): break\n",
" \n",
" if hasattr(data,'valid_dl') and data.valid_dl is not None:\n",
" model.eval()\n",
" with torch.no_grad():\n",
" *val_metrics,nums = zip(*[loss_batch(model, xb, yb, loss_fn, metrics=metrics)\n",
" for xb,yb in data.valid_dl])\n",
" val_metrics = [np.sum(np.multiply(val,nums)) / np.sum(nums) for val in val_metrics]\n",
" \n",
" else: val_metrics=None\n",
" if cb_handler.on_epoch_end(val_metrics): break\n",
" \n",
" cb_handler.on_train_end()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class TrueWD(Callback):\n",
" \n",
" def __init__(self, learn, wd):\n",
" self.learn,self.wd = learn,wd\n",
" \n",
" def on_train_begin(self):\n",
" self.opt = self.learn.opt\n",
" self.opt.wd = 0\n",
" \n",
" def on_backward_end(self):\n",
" for pg in self.opt.opt.param_groups:\n",
" for p in pg['params']:\n",
" p.data.mul_(1 - self.wd * pg['lr'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model = Darknet([1, 2, 4, 6, 3], num_classes=len(classes), nf=16).cuda()\n",
"learn = Learner(data, model)\n",
"learn.loss_fn = F.cross_entropy\n",
"learn.metrics = [accuracy]\n",
"learn.opt_fn = partial(optim.Adam, betas=(0.95,0.99))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"learn.lr_find()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"learn.recorder.plot()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"scheds = [OneCycleScheduler(learn, 4e-3, 30, div_factor=10, pct_end=0.1), TrueWD(learn, 0.3)]\n",
"learn.fit(30, 2e-3, wd=1e-4, callbacks=scheds)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2e-3, 0.1, 76.4%\n",
"1e-3, 0.1, 76.3%\n",
"5e-4, 0.1, 76.5%\n",
"4e-3, 0.1, 77.8%"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## With perspective wrap"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def find_coeffs(ori_pts, targ_pts):\n",
" matrix = []\n",
" for p1, p2 in zip(targ_pts, ori_pts):\n",
" matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])\n",
" matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])\n",
"\n",
" A = FloatTensor(matrix)\n",
" B = FloatTensor(ori_pts).view(8)\n",
" #The 8 scalars we seek are solution of AX = B, we use the pseudo inverse to compute them.\n",
" \n",
" res = torch.mv(torch.mm(torch.inverse(torch.mm(A.t(),A)), A.t()), B)\n",
" #res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B)\n",
" return res"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def add_ones(coords):\n",
" coords = coords.view(-1,2)\n",
" ones = torch.ones(coords.size(0)).unsqueeze(1)\n",
" coords = torch.cat([coords, ones], 1)\n",
" return coords"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def apply_perspective(coords, coeffs):\n",
" ori_size = coords.size()\n",
" #compress all the dims expect the last one ang adds ones, coords become N * 3\n",
" coords = add_ones(coords)\n",
" #Transform the coeffs in a 3*3 matrix with a 1 at the bottom left\n",
" coeffs = torch.cat([coeffs, FloatTensor([1])]).view(3,3)\n",
" coords = torch.mm(coords, coeffs.t())\n",
" coords.mul_(1/coords[:,2].unsqueeze(1))\n",
" return coords[:,:2].view(ori_size)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@reg_transform\n",
"def perspective_warp(c, img_size, magnitude:uniform=0) -> TfmType.Coord:\n",
" magnitude = magnitude.view(4,2)\n",
" ori_pts = [[-1,-1], [-1,1], [1,-1], [1,1]]\n",
" targ_pts = [[x+m for x,m in zip(xs, ms)] for xs, ms in zip(ori_pts, magnitude)]\n",
" coeffs = find_coeffs(ori_pts, targ_pts)\n",
" return apply_perspective(c, coeffs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def rand_int(low,high): return random.randint(low, high)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@reg_affine\n",
"def zoom(scale: uniform = 1.0, row_pct:uniform = 0.5, col_pct:uniform = 0.5) -> TfmType.Affine:\n",
" s = 1-1/scale\n",
" col_c = s * (2*col_pct - 1)\n",
" row_c = s * (2*row_pct - 1)\n",
" return [[1/scale, 0, col_c],\n",
" [0, 1/scale, row_c],\n",
" [0, 0, 1. ]]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@reg_transform\n",
"def tilt(c, img_size, direction:rand_int, magnitude:uniform=0) -> TfmType.Coord:\n",
" ori_pts = [[-1,-1], [-1,1], [1,-1], [1,1]]\n",
" if direction == 0: targ_pts = [[-1,-1], [-1,1], [1,-1-magnitude], [1,1+magnitude]]\n",
" elif direction == 1: targ_pts = [[-1,-1-magnitude], [-1,1+magnitude], [1,-1], [1,1]]\n",
" elif direction == 2: targ_pts = [[-1,-1], [-1-magnitude,1], [1,-1], [1+magnitude,1]]\n",
" elif direction == 3: targ_pts = [[-1-magnitude,-1], [-1,1], [1+magnitude,-1], [1,1]] \n",
" coeffs = find_coeffs(ori_pts, targ_pts)\n",
" return apply_perspective(c, coeffs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@reg_affine\n",
"def zoom1(scale: uniform = 1.0, row_pct:uniform = 0.5, col_pct:uniform = 0.5) -> TfmType.Affine:\n",
" s = 1-math.sqrt(scale)\n",
" col_c = s * (2*col_pct - 1)\n",
" row_c = s * (2*row_pct - 1)\n",
" return [[math.sqrt(scale), 0, col_c],\n",
" [0, math.sqrt(scale), row_c],\n",
" [0, 0, 1. ]]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@reg_affine\n",
"def stretch(scale: uniform = 1.0) -> TfmType.Affine:\n",
" return [[math.sqrt(scale), 0, 0],\n",
" [0, 1/math.sqrt(scale), 0],\n",
" [0, 0, 1. ]]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sz = 224\n",
"trn_tfms = [stretch_tfm(scale=(0.75,1.33)),\n",
" zoom_tfm(scale=(0.08,0.8), row_pct=(0,1.), col_pct=(0,1.)),\n",
" flip_lr_tfm(p=0.5),\n",
" center_crop_tfm(b=(0,1)),\n",
" normalize_tfm(mean=data_mean,std=data_std)] #torchvision.transforms.RandomRotation(10),\n",
"val_tfms = [center_crop_tfm(b=(0,1)),\n",
" normalize_tfm(mean=data_mean,std=data_std)]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#classes = ['airplanes','Motorbikes','Faces','watch','Leopards']\n",
"np.random.seed(42)\n",
"train_ds,valid_ds = ImageDataset.from_folder(PATH, test_pct=0.2)\n",
"classes = train_ds.classes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"train_ds = TfmDataset(train_ds, trn_tfms, size=224)\n",
"valid_ds = TfmDataset(valid_ds, val_tfms, size=224)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x,y = train_ds[0]\n",
"x,y = valid_ds[0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = DataBunch(train_ds, valid_ds, bs=64, num_workers=8)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model = Darknet([1, 2, 4, 6, 3], num_classes=len(classes), nf=16).cuda()\n",
"learn = Learner(data, model)\n",
"learn.loss_fn = F.cross_entropy\n",
"learn.metrics = [accuracy]\n",
"learn.opt_fn = partial(optim.Adam, betas=(0.95,0.99))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"scheds = [OneCycleScheduler(learn, 4e-3, 30, div_factor=10, pct_end=0.1), TrueWD(learn, 0.1)]\n",
"learn.fit(30, 2e-3, wd=1e-4, callbacks=scheds)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"show_image_batch(data.train_dl, classes, rows=4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| {
"pile_set_name": "Github"
} |
span.vm-detail { font-size: 0.9em !important }
| {
"pile_set_name": "Github"
} |
User-agent: *
Allow: /
| {
"pile_set_name": "Github"
} |
<?php
namespace Oro\Bundle\InventoryBundle\ImportExport\Strategy;
use Oro\Bundle\ImportExportBundle\Field\DatabaseHelper;
use Symfony\Contracts\Translation\TranslatorInterface;
abstract class AbstractInventoryLevelStrategyHelper implements InventoryLevelStrategyHelperInterface
{
/** @var DatabaseHelper $databaseHelper */
protected $databaseHelper;
/** @var TranslatorInterface */
protected $translator;
/** @var InventoryLevelStrategyHelperInterface $successor */
protected $successor;
/** @var array $errors */
protected $errors = [];
/**
* @param DatabaseHelper $databaseHelper
* @param TranslatorInterface $translator
*/
public function __construct(DatabaseHelper $databaseHelper, TranslatorInterface $translator)
{
$this->databaseHelper = $databaseHelper;
$this->translator = $translator;
}
/**
* Using DatabaseHelper we search for an entity using its class name and
* a criteria composed of a field from this entity and its value.
* If entity is not found then add a validation error on the context.
*
* @param string $class
* @param array $criteria
* @param null|string $alternaiveClassName
* @return null|object
*/
protected function checkAndRetrieveEntity($class, array $criteria = [], $alternaiveClassName = null)
{
$existingEntity = $this->databaseHelper->findOneBy($class, $criteria);
if (!$existingEntity) {
$classNamespace = explode('\\', $class);
$shortClassName = end($classNamespace);
$this->addError(
'oro.inventory.import.error.not_found_entity',
['%entity%' => $alternaiveClassName ?: $shortClassName]
);
}
return $existingEntity;
}
/**
* Translates the received error and adds it to the list of errors
*
* @param string $error
* @param array $translationParams
* @param null|string $prefix
*/
protected function addError($error, array $translationParams = [], $prefix = null)
{
$errorMessage = $this->translator->trans($error, $translationParams);
if ($prefix) {
$prefix = $this->translator->trans($prefix);
}
$this->errors[$errorMessage] = $prefix;
}
/**
* {@inheritdoc}
*/
public function getErrors($deep = false)
{
$successorErrors = $this->successor ? $this->successor->getErrors(true) : [];
return array_merge($this->errors, $successorErrors);
}
/**
* {@inheritdoc}
*/
public function setSuccessor(InventoryLevelStrategyHelperInterface $successor)
{
$this->successor = $successor;
}
/**
* Helper function which extracts an entity from an array based on a key.
* @param array $entities
* @param string $name
* @return null
*/
protected function getProcessedEntity($entities, $name)
{
return isset($entities[$name]) ? $entities[$name] : null;
}
/**
* {@inheritdoc}
*/
public function clearCache($deep = false)
{
$this->errors = [];
if ($deep && $this->successor) {
$this->successor->clearCache($deep);
}
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/** Unit test case for the function explain_filename(). */
#include "my_config.h"
#include <gtest/gtest.h>
#include "mysqld_error.h"
#include "sql/derror.h"
#include "sql/sql_class.h"
#include "sql/sql_locale.h"
#include "sql/sql_table.h"
namespace explain_filename_unittest {
const int BUFLEN = 1000;
char to[BUFLEN];
char from[BUFLEN];
class PartitionTest : public ::testing::Test {
protected:
virtual void SetUp() {
// Save global settings.
m_charset = system_charset_info;
m_locale = my_default_lc_messages;
system_charset_info = &my_charset_utf8_bin;
my_default_lc_messages = &my_locale_en_US;
/* Populate the necessary error messages */
MY_LOCALE_ERRMSGS *errmsgs = my_default_lc_messages->errmsgs;
EXPECT_FALSE(errmsgs->replace_msg(ER_DATABASE_NAME, "Database"));
EXPECT_FALSE(errmsgs->replace_msg(ER_TABLE_NAME, "Table"));
EXPECT_FALSE(errmsgs->replace_msg(ER_PARTITION_NAME, "Partition"));
EXPECT_FALSE(errmsgs->replace_msg(ER_SUBPARTITION_NAME, "Subpartition"));
EXPECT_FALSE(errmsgs->replace_msg(ER_TEMPORARY_NAME, "Temporary"));
EXPECT_FALSE(errmsgs->replace_msg(ER_RENAMED_NAME, "Renamed"));
}
virtual void TearDown() {
// Restore global settings.
system_charset_info = m_charset;
my_default_lc_messages = m_locale;
}
private:
CHARSET_INFO *m_charset;
MY_LOCALE *m_locale;
};
void test_1(const char *in, const char *exp, enum_explain_filename_mode mode) {
char out[BUFLEN];
size_t len1 = explain_filename(nullptr, in, out, BUFLEN, mode);
/* expected output and actual output must be same */
bool pass = (strcmp(exp, out) == 0);
/* length returned by explain_filename is fine */
bool length = (len1 == strlen(exp));
EXPECT_EQ((pass && length), true);
if (pass && length) {
// pass
} else {
ADD_FAILURE() << "input file name: '" << in << "' explain output: '" << out
<< "'" << std::endl;
}
}
TEST_F(PartitionTest, ExplainFilename) {
test_1("test/t1.ibd", "Database `test`, Table `t1.ibd`", EXPLAIN_ALL_VERBOSE);
test_1("test/t1.ibd", "`test`.`t1.ibd`", EXPLAIN_PARTITIONS_VERBOSE);
test_1("test/t1.ibd", "`test`.`t1.ibd`", EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/t1#TMP#", "Database `test`, Table `t1#TMP#`",
EXPLAIN_ALL_VERBOSE);
test_1("test/#sql-2882.ibd", "Database `test`, Table `#sql-2882.ibd`",
EXPLAIN_ALL_VERBOSE);
test_1("test/t1#REN#", "Database `test`, Table `t1#REN#`",
EXPLAIN_ALL_VERBOSE);
test_1("test/t1@0023REN@0023", "Database `test`, Table `t1#REN#`",
EXPLAIN_ALL_VERBOSE);
test_1("test/t1#p#p1", "Database `test`, Table `t1`, Partition `p1`",
EXPLAIN_ALL_VERBOSE);
test_1("test/t1#P#p1", "`test`.`t1` /* Partition `p1` */",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/t1#P#p1@00231", "`test`.`t1` /* Partition `p1#1` */",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/t1#P#p1#SP#sp1",
"`test`.`t1` /* Partition `p1`, Subpartition `sp1` */",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/t1#p1#SP#sp1", "`test`.`t1#p1#SP#sp1`",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/t1#p#p1@00232#SP#sp1@00231#REN#",
"`test`.`t1` /* Renamed Partition `p1#2`, Subpartition `sp1#1` */",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/t1#p#p1#SP#sp1#TMP#",
"`test`.`t1` /* Temporary Partition `p1`, Subpartition `sp1` */",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/#sql-t1#P#p1#SP#sp1#TMP#",
"`test`.`#sql-t1#P#p1#SP#sp1#TMP#` /* Temporary Partition `p1`, "
"Subpartition `sp1` */",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1(
"test/#sql-t1#P#p1#SP#sp1",
"`test`.`#sql-t1#P#p1#SP#sp1` /* Partition `p1`, Subpartition `sp1` */",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/#sqlx-33", "`test`.`#sqlx-33`", EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/#mysql50#t", "`test`.`#mysql50#t`",
EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("#mysql50#t", "`#mysql50#t`", EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("@0023t", "`#t`", EXPLAIN_PARTITIONS_AS_COMMENT);
test_1("test/t@0023", "`test`.`t#`", EXPLAIN_PARTITIONS_AS_COMMENT);
/*
If a character not allowed in my_charset_filename is encountered,
then it will not be converted to system_charset_info!
*/
test_1("test/t@0023#", "`test`.`t@0023#`", EXPLAIN_PARTITIONS_AS_COMMENT);
}
} // namespace explain_filename_unittest
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="Extension Component" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_recorded_property_dict</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAI=</string> </persistent>
</value>
</item>
<item>
<key> <string>default_reference</string> </key>
<value> <string>joblibUseCaseExamples</string> </value>
</item>
<item>
<key> <string>description</string> </key>
<value>
<none/>
</value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>extension.erp5.joblibUseCaseExamples</string> </value>
</item>
<item>
<key> <string>portal_type</string> </key>
<value> <string>Extension Component</string> </value>
</item>
<item>
<key> <string>sid</string> </key>
<value>
<none/>
</value>
</item>
<item>
<key> <string>text_content_error_message</string> </key>
<value>
<tuple/>
</value>
</item>
<item>
<key> <string>text_content_warning_message</string> </key>
<value>
<tuple/>
</value>
</item>
<item>
<key> <string>version</string> </key>
<value> <string>erp5</string> </value>
</item>
<item>
<key> <string>workflow_history</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAM=</string> </persistent>
</value>
</item>
</dictionary>
</pickle>
</record>
<record id="2" aka="AAAAAAAAAAI=">
<pickle>
<global name="PersistentMapping" module="Persistence.mapping"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>data</string> </key>
<value>
<dictionary/>
</value>
</item>
</dictionary>
</pickle>
</record>
<record id="3" aka="AAAAAAAAAAM=">
<pickle>
<global name="PersistentMapping" module="Persistence.mapping"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>data</string> </key>
<value>
<dictionary>
<item>
<key> <string>component_validation_workflow</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAQ=</string> </persistent>
</value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</pickle>
</record>
<record id="4" aka="AAAAAAAAAAQ=">
<pickle>
<global name="WorkflowHistoryList" module="Products.ERP5Type.Workflow"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_log</string> </key>
<value>
<list>
<dictionary>
<item>
<key> <string>action</string> </key>
<value> <string>validate</string> </value>
</item>
<item>
<key> <string>validation_state</string> </key>
<value> <string>validated</string> </value>
</item>
</dictionary>
</list>
</value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.context.properties.source;
import java.util.function.BiPredicate;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SystemEnvironmentPropertyMapper}.
*
* @author Phillip Webb
* @author Madhura Bhave
*/
class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapperTests {
@Override
protected PropertyMapper getMapper() {
return SystemEnvironmentPropertyMapper.INSTANCE;
}
@Test
void mapFromStringShouldReturnBestGuess() {
assertThat(mapPropertySourceName("SERVER")).isEqualTo("server");
assertThat(mapPropertySourceName("SERVER_PORT")).isEqualTo("server.port");
assertThat(mapPropertySourceName("HOST_0")).isEqualTo("host[0]");
assertThat(mapPropertySourceName("HOST_0_1")).isEqualTo("host[0][1]");
assertThat(mapPropertySourceName("HOST_0_NAME")).isEqualTo("host[0].name");
assertThat(mapPropertySourceName("HOST_F00_NAME")).isEqualTo("host.f00.name");
assertThat(mapPropertySourceName("S-ERVER")).isEqualTo("s-erver");
}
@Test
void mapFromConfigurationShouldReturnBestGuess() {
assertThat(mapConfigurationPropertyName("server")).containsExactly("SERVER");
assertThat(mapConfigurationPropertyName("server.port")).containsExactly("SERVER_PORT");
assertThat(mapConfigurationPropertyName("host[0]")).containsExactly("HOST_0");
assertThat(mapConfigurationPropertyName("host[0][1]")).containsExactly("HOST_0_1");
assertThat(mapConfigurationPropertyName("host[0].name")).containsExactly("HOST_0_NAME");
assertThat(mapConfigurationPropertyName("host.f00.name")).containsExactly("HOST_F00_NAME");
assertThat(mapConfigurationPropertyName("foo.the-bar")).containsExactly("FOO_THEBAR", "FOO_THE_BAR");
}
@Test
void underscoreShouldMapToEmptyString() {
ConfigurationPropertyName mapped = getMapper().map("_");
assertThat(mapped.isEmpty()).isTrue();
}
@Test
void underscoreWithWhitespaceShouldMapToEmptyString() {
ConfigurationPropertyName mapped = getMapper().map(" _");
assertThat(mapped.isEmpty()).isTrue();
}
@Test
void isAncestorOfConsidersLegacyNames() {
ConfigurationPropertyName name = ConfigurationPropertyName.of("my.spring-boot");
BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> check = getMapper().getAncestorOfCheck();
assertThat(check.test(name, ConfigurationPropertyName.adapt("MY_SPRING_BOOT_PROPERTY", '_'))).isTrue();
assertThat(check.test(name, ConfigurationPropertyName.adapt("MY_SPRINGBOOT_PROPERTY", '_'))).isTrue();
assertThat(check.test(name, ConfigurationPropertyName.adapt("MY_BOOT_PROPERTY", '_'))).isFalse();
}
@Test
void isAncestorOfWhenNonCanonicalSource() {
ConfigurationPropertyName name = ConfigurationPropertyName.adapt("my.springBoot", '.');
BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> check = getMapper().getAncestorOfCheck();
assertThat(check.test(name, ConfigurationPropertyName.of("my.spring-boot.property"))).isTrue();
assertThat(check.test(name, ConfigurationPropertyName.of("my.springboot.property"))).isTrue();
assertThat(check.test(name, ConfigurationPropertyName.of("my.boot.property"))).isFalse();
}
@Test
void isAncestorOfWhenNonCanonicalAndDashedSource() {
ConfigurationPropertyName name = ConfigurationPropertyName.adapt("my.springBoot.input-value", '.');
BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> check = getMapper().getAncestorOfCheck();
assertThat(check.test(name, ConfigurationPropertyName.of("my.spring-boot.input-value.property"))).isTrue();
assertThat(check.test(name, ConfigurationPropertyName.of("my.springboot.inputvalue.property"))).isTrue();
assertThat(check.test(name, ConfigurationPropertyName.of("my.boot.property"))).isFalse();
}
}
| {
"pile_set_name": "Github"
} |
[](https://www.android.com)
[](https://android-arsenal.com/api?level=14)
[](https://www.apache.org/licenses/LICENSE-2.0.html)
[](https://jitpack.io/#varunest/TheGlowingLoader)
# TheGlowingLoader
Android Library which is the implementation of [The Glowing Loader](https://www.uplabs.com/posts/loader-fe7378f9-894d-4e6e-8340-968f41da9fa8) created by [Shashank Sahay](https://www.uplabs.com/shashanksahay).
I have made it so that it can be easily customized. You can change line stroke width, line colors, particle colors, disable several effects etc.
Library supports OS on API 14 and above.
**[Download Demo Apk](demo/app-debug.apk)**
**[Demo Video](https://www.youtube.com/watch?v=lSBTyfGWYAU)**
#### Here is how the loader looks by default:

#### But you can also tweak it according to your need:
| Example A | Example B|
| ------------- | ------------- |
|  |  |
## Dependency
Add it in your root build.gradle at the end of repositories:
```groovy
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
```
and then add dependency
```groovy
dependencies {
implementation 'com.github.varunest:TheGlowingLoader:1.0.5'
}
```
## Usage
```xml
<com.varunest.loader.TheGlowingLoader
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
```
### Attributes
```xml
<attr name="theglowingloader_line_1_color" format="reference" />
<attr name="theglowingloader_line_2_color" format="reference" />
<attr name="theglowingloader_line_stroke_width" format="integer" />
<attr name="theglowingloader_ripple_color" format="reference" />
<attr name="theglowingloader_particle_1_color" format="reference" />
<attr name="theglowingloader_particle_2_color" format="reference" />
<attr name="theglowingloader_particle_3_color" format="reference" />
<attr name="theglowingloader_disable_shadows" format="boolean" />
<attr name="theglowingloader_disable_ripple" format="boolean" />
<attr name="theglowingloader_shadow_opacity" format="float" />
```
You can also access and modify all these attributes at runtime by getting the reference of `TheGlowingLoader` and calling its `setConfiguration` method.
## Inspiration
This library was a result of challenge hosted by [Uplabs](https://www.uplabs.com/)
## Contribution
Any contributions, large or small,features, bug fixes are welcomed and appreciated. Use pull requests, they will be thoroughly reviewed and discussed.
## License
Library falls under [Apache 2.0](LICENSE.md)
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C) 2016 Oleksij Rempel <[email protected]>
*/
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/rtc.h>
/* Miscellaneous registers */
/* Interrupt Location Register */
#define HW_ILR 0x00
#define BM_RTCALF BIT(1)
#define BM_RTCCIF BIT(0)
/* Clock Control Register */
#define HW_CCR 0x08
/* Calibration counter disable */
#define BM_CCALOFF BIT(4)
/* Reset internal oscillator divider */
#define BM_CTCRST BIT(1)
/* Clock Enable */
#define BM_CLKEN BIT(0)
/* Counter Increment Interrupt Register */
#define HW_CIIR 0x0C
#define BM_CIIR_IMYEAR BIT(7)
#define BM_CIIR_IMMON BIT(6)
#define BM_CIIR_IMDOY BIT(5)
#define BM_CIIR_IMDOW BIT(4)
#define BM_CIIR_IMDOM BIT(3)
#define BM_CIIR_IMHOUR BIT(2)
#define BM_CIIR_IMMIN BIT(1)
#define BM_CIIR_IMSEC BIT(0)
/* Alarm Mask Register */
#define HW_AMR 0x10
#define BM_AMR_IMYEAR BIT(7)
#define BM_AMR_IMMON BIT(6)
#define BM_AMR_IMDOY BIT(5)
#define BM_AMR_IMDOW BIT(4)
#define BM_AMR_IMDOM BIT(3)
#define BM_AMR_IMHOUR BIT(2)
#define BM_AMR_IMMIN BIT(1)
#define BM_AMR_IMSEC BIT(0)
#define BM_AMR_OFF 0xff
/* Consolidated time registers */
#define HW_CTIME0 0x14
#define BM_CTIME0_DOW_S 24
#define BM_CTIME0_DOW_M 0x7
#define BM_CTIME0_HOUR_S 16
#define BM_CTIME0_HOUR_M 0x1f
#define BM_CTIME0_MIN_S 8
#define BM_CTIME0_MIN_M 0x3f
#define BM_CTIME0_SEC_S 0
#define BM_CTIME0_SEC_M 0x3f
#define HW_CTIME1 0x18
#define BM_CTIME1_YEAR_S 16
#define BM_CTIME1_YEAR_M 0xfff
#define BM_CTIME1_MON_S 8
#define BM_CTIME1_MON_M 0xf
#define BM_CTIME1_DOM_S 0
#define BM_CTIME1_DOM_M 0x1f
#define HW_CTIME2 0x1C
#define BM_CTIME2_DOY_S 0
#define BM_CTIME2_DOY_M 0xfff
/* Time counter registers */
#define HW_SEC 0x20
#define HW_MIN 0x24
#define HW_HOUR 0x28
#define HW_DOM 0x2C
#define HW_DOW 0x30
#define HW_DOY 0x34
#define HW_MONTH 0x38
#define HW_YEAR 0x3C
#define HW_CALIBRATION 0x40
#define BM_CALDIR_BACK BIT(17)
#define BM_CALVAL_M 0x1ffff
/* General purpose registers */
#define HW_GPREG0 0x44
#define HW_GPREG1 0x48
#define HW_GPREG2 0x4C
#define HW_GPREG3 0x50
#define HW_GPREG4 0x54
/* Alarm register group */
#define HW_ALSEC 0x60
#define HW_ALMIN 0x64
#define HW_ALHOUR 0x68
#define HW_ALDOM 0x6C
#define HW_ALDOW 0x70
#define HW_ALDOY 0x74
#define HW_ALMON 0x78
#define HW_ALYEAR 0x7C
struct asm9260_rtc_priv {
struct device *dev;
void __iomem *iobase;
struct rtc_device *rtc;
struct clk *clk;
};
static irqreturn_t asm9260_rtc_irq(int irq, void *dev_id)
{
struct asm9260_rtc_priv *priv = dev_id;
u32 isr;
unsigned long events = 0;
mutex_lock(&priv->rtc->ops_lock);
isr = ioread32(priv->iobase + HW_CIIR);
if (!isr) {
mutex_unlock(&priv->rtc->ops_lock);
return IRQ_NONE;
}
iowrite32(0, priv->iobase + HW_CIIR);
mutex_unlock(&priv->rtc->ops_lock);
events |= RTC_AF | RTC_IRQF;
rtc_update_irq(priv->rtc, 1, events);
return IRQ_HANDLED;
}
static int asm9260_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct asm9260_rtc_priv *priv = dev_get_drvdata(dev);
u32 ctime0, ctime1, ctime2;
ctime0 = ioread32(priv->iobase + HW_CTIME0);
ctime1 = ioread32(priv->iobase + HW_CTIME1);
ctime2 = ioread32(priv->iobase + HW_CTIME2);
if (ctime1 != ioread32(priv->iobase + HW_CTIME1)) {
/*
* woops, counter flipped right now. Now we are safe
* to reread.
*/
ctime0 = ioread32(priv->iobase + HW_CTIME0);
ctime1 = ioread32(priv->iobase + HW_CTIME1);
ctime2 = ioread32(priv->iobase + HW_CTIME2);
}
tm->tm_sec = (ctime0 >> BM_CTIME0_SEC_S) & BM_CTIME0_SEC_M;
tm->tm_min = (ctime0 >> BM_CTIME0_MIN_S) & BM_CTIME0_MIN_M;
tm->tm_hour = (ctime0 >> BM_CTIME0_HOUR_S) & BM_CTIME0_HOUR_M;
tm->tm_wday = (ctime0 >> BM_CTIME0_DOW_S) & BM_CTIME0_DOW_M;
tm->tm_mday = (ctime1 >> BM_CTIME1_DOM_S) & BM_CTIME1_DOM_M;
tm->tm_mon = (ctime1 >> BM_CTIME1_MON_S) & BM_CTIME1_MON_M;
tm->tm_year = (ctime1 >> BM_CTIME1_YEAR_S) & BM_CTIME1_YEAR_M;
tm->tm_yday = (ctime2 >> BM_CTIME2_DOY_S) & BM_CTIME2_DOY_M;
return 0;
}
static int asm9260_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
struct asm9260_rtc_priv *priv = dev_get_drvdata(dev);
/*
* make sure SEC counter will not flip other counter on write time,
* real value will be written at the enf of sequence.
*/
iowrite32(0, priv->iobase + HW_SEC);
iowrite32(tm->tm_year, priv->iobase + HW_YEAR);
iowrite32(tm->tm_mon, priv->iobase + HW_MONTH);
iowrite32(tm->tm_mday, priv->iobase + HW_DOM);
iowrite32(tm->tm_wday, priv->iobase + HW_DOW);
iowrite32(tm->tm_yday, priv->iobase + HW_DOY);
iowrite32(tm->tm_hour, priv->iobase + HW_HOUR);
iowrite32(tm->tm_min, priv->iobase + HW_MIN);
iowrite32(tm->tm_sec, priv->iobase + HW_SEC);
return 0;
}
static int asm9260_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct asm9260_rtc_priv *priv = dev_get_drvdata(dev);
alrm->time.tm_year = ioread32(priv->iobase + HW_ALYEAR);
alrm->time.tm_mon = ioread32(priv->iobase + HW_ALMON);
alrm->time.tm_mday = ioread32(priv->iobase + HW_ALDOM);
alrm->time.tm_wday = ioread32(priv->iobase + HW_ALDOW);
alrm->time.tm_yday = ioread32(priv->iobase + HW_ALDOY);
alrm->time.tm_hour = ioread32(priv->iobase + HW_ALHOUR);
alrm->time.tm_min = ioread32(priv->iobase + HW_ALMIN);
alrm->time.tm_sec = ioread32(priv->iobase + HW_ALSEC);
alrm->enabled = ioread32(priv->iobase + HW_AMR) ? 1 : 0;
alrm->pending = ioread32(priv->iobase + HW_CIIR) ? 1 : 0;
return rtc_valid_tm(&alrm->time);
}
static int asm9260_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct asm9260_rtc_priv *priv = dev_get_drvdata(dev);
iowrite32(alrm->time.tm_year, priv->iobase + HW_ALYEAR);
iowrite32(alrm->time.tm_mon, priv->iobase + HW_ALMON);
iowrite32(alrm->time.tm_mday, priv->iobase + HW_ALDOM);
iowrite32(alrm->time.tm_wday, priv->iobase + HW_ALDOW);
iowrite32(alrm->time.tm_yday, priv->iobase + HW_ALDOY);
iowrite32(alrm->time.tm_hour, priv->iobase + HW_ALHOUR);
iowrite32(alrm->time.tm_min, priv->iobase + HW_ALMIN);
iowrite32(alrm->time.tm_sec, priv->iobase + HW_ALSEC);
iowrite32(alrm->enabled ? 0 : BM_AMR_OFF, priv->iobase + HW_AMR);
return 0;
}
static int asm9260_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct asm9260_rtc_priv *priv = dev_get_drvdata(dev);
iowrite32(enabled ? 0 : BM_AMR_OFF, priv->iobase + HW_AMR);
return 0;
}
static const struct rtc_class_ops asm9260_rtc_ops = {
.read_time = asm9260_rtc_read_time,
.set_time = asm9260_rtc_set_time,
.read_alarm = asm9260_rtc_read_alarm,
.set_alarm = asm9260_rtc_set_alarm,
.alarm_irq_enable = asm9260_alarm_irq_enable,
};
static int asm9260_rtc_probe(struct platform_device *pdev)
{
struct asm9260_rtc_priv *priv;
struct device *dev = &pdev->dev;
int irq_alarm, ret;
u32 ccr;
priv = devm_kzalloc(dev, sizeof(struct asm9260_rtc_priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->dev = &pdev->dev;
platform_set_drvdata(pdev, priv);
irq_alarm = platform_get_irq(pdev, 0);
if (irq_alarm < 0)
return irq_alarm;
priv->iobase = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(priv->iobase))
return PTR_ERR(priv->iobase);
priv->clk = devm_clk_get(dev, "ahb");
if (IS_ERR(priv->clk))
return PTR_ERR(priv->clk);
ret = clk_prepare_enable(priv->clk);
if (ret) {
dev_err(dev, "Failed to enable clk!\n");
return ret;
}
ccr = ioread32(priv->iobase + HW_CCR);
/* if dev is not enabled, reset it */
if ((ccr & (BM_CLKEN | BM_CTCRST)) != BM_CLKEN) {
iowrite32(BM_CTCRST, priv->iobase + HW_CCR);
ccr = 0;
}
iowrite32(BM_CLKEN | ccr, priv->iobase + HW_CCR);
iowrite32(0, priv->iobase + HW_CIIR);
iowrite32(BM_AMR_OFF, priv->iobase + HW_AMR);
priv->rtc = devm_rtc_device_register(dev, dev_name(dev),
&asm9260_rtc_ops, THIS_MODULE);
if (IS_ERR(priv->rtc)) {
ret = PTR_ERR(priv->rtc);
dev_err(dev, "Failed to register RTC device: %d\n", ret);
goto err_return;
}
ret = devm_request_threaded_irq(dev, irq_alarm, NULL,
asm9260_rtc_irq, IRQF_ONESHOT,
dev_name(dev), priv);
if (ret < 0) {
dev_err(dev, "can't get irq %i, err %d\n",
irq_alarm, ret);
goto err_return;
}
return 0;
err_return:
clk_disable_unprepare(priv->clk);
return ret;
}
static int asm9260_rtc_remove(struct platform_device *pdev)
{
struct asm9260_rtc_priv *priv = platform_get_drvdata(pdev);
/* Disable alarm matching */
iowrite32(BM_AMR_OFF, priv->iobase + HW_AMR);
clk_disable_unprepare(priv->clk);
return 0;
}
static const struct of_device_id asm9260_dt_ids[] = {
{ .compatible = "alphascale,asm9260-rtc", },
{}
};
MODULE_DEVICE_TABLE(of, asm9260_dt_ids);
static struct platform_driver asm9260_rtc_driver = {
.probe = asm9260_rtc_probe,
.remove = asm9260_rtc_remove,
.driver = {
.name = "asm9260-rtc",
.of_match_table = asm9260_dt_ids,
},
};
module_platform_driver(asm9260_rtc_driver);
MODULE_AUTHOR("Oleksij Rempel <[email protected]>");
MODULE_DESCRIPTION("Alphascale asm9260 SoC Realtime Clock Driver (RTC)");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
[
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/299",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/299/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/299/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/299/events",
"html_url": "https://github.com/hub4j/github-api/pull/299",
"id": 184520196,
"node_id": "MDExOlB1bGxSZXF1ZXN0OTA0MDg2MDc=",
"number": 299,
"title": "url encode hashes in ref names",
"user": {
"login": "bsheats",
"id": 515385,
"node_id": "MDQ6VXNlcjUxNTM4NQ==",
"avatar_url": "https://avatars0.githubusercontent.com/u/515385?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bsheats",
"html_url": "https://github.com/bsheats",
"followers_url": "https://api.github.com/users/bsheats/followers",
"following_url": "https://api.github.com/users/bsheats/following{/other_user}",
"gists_url": "https://api.github.com/users/bsheats/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bsheats/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bsheats/subscriptions",
"organizations_url": "https://api.github.com/users/bsheats/orgs",
"repos_url": "https://api.github.com/users/bsheats/repos",
"events_url": "https://api.github.com/users/bsheats/events{/privacy}",
"received_events_url": "https://api.github.com/users/bsheats/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 3,
"created_at": "2016-10-21T15:52:39Z",
"updated_at": "2016-10-25T02:15:54Z",
"closed_at": "2016-10-25T02:15:54Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/299",
"html_url": "https://github.com/hub4j/github-api/pull/299",
"diff_url": "https://github.com/hub4j/github-api/pull/299.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/299.patch"
},
"body": "Without this fix, the following code:\n\n```\nGHRepository repo = gh.getRepository(\"iown/test\");\nString branch = \"heads/bsheats/#107-test-branch\";\nref = repo.getRef(branch);\n```\n\nwill fail with this exception:\n\n```\nException in thread \"main\" org.kohsuke.github.HttpException: Server returned HTTP response code: 200, message: 'OK' for URL: https://api.github.com/repos/iown/test/git/refs/heads/bsheats/#107-test-branch\n at org.kohsuke.github.Requester.parse(Requester.java:540)\n at org.kohsuke.github.Requester._to(Requester.java:251)\n at org.kohsuke.github.Requester.to(Requester.java:213)\n at org.kohsuke.github.GHRepository.getRef(GHRepository.java:770)\n at Foo.main(Foo.java:22)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:498)\n at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)\nCaused by: java.io.IOException: Failed to deserialize [{\"ref\":\"refs/heads/bsheats/test\",\"url\":\"https://api.github.com/repos/iown/test/git/refs/heads/bsheats/test\",\"object\":{\"sha\":\"7c4a0777bdbd76442ee98e54daee808a5ca0e211\",\"type\":\"commit\",\"url\":\"https://api.github.com/repos/iown/test/git/commits/7c4a0777bdbd76442ee98e54daee808a5ca0e211\"}},{\"ref\":\"refs/heads/bsheats/#107-test-branch\",\"url\":\"https://api.github.com/repos/iown/test/git/refs/heads/bsheats/%23107-test-branch\",\"object\":{\"sha\":\"fca609f46dbbee95170e8a1dc283329ea1c768f6\",\"type\":\"commit\",\"url\":\"https://api.github.com/repos/iown/test/git/commits/fca609f46dbbee95170e8a1dc283329ea1c768f6\"}}]\n at org.kohsuke.github.Requester.parse(Requester.java:530)\n ... 9 more\nCaused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of org.kohsuke.github.GHRef out of START_ARRAY token\n at [Source: java.io.StringReader@e50a6f6; line: 1, column: 1]\n at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)\n at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:575)\n at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:569)\n at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1121)\n at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:148)\n at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:123)\n at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)\n at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)\n at org.kohsuke.github.Requester.parse(Requester.java:528)\n ... 9 more\n```\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/298",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/298/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/298/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/298/events",
"html_url": "https://github.com/hub4j/github-api/issues/298",
"id": 183381257,
"node_id": "MDU6SXNzdWUxODMzODEyNTc=",
"number": 298,
"title": "How to find a pull request using the Search API and get its details?",
"user": {
"login": "adamsiemion",
"id": 898997,
"node_id": "MDQ6VXNlcjg5ODk5Nw==",
"avatar_url": "https://avatars2.githubusercontent.com/u/898997?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/adamsiemion",
"html_url": "https://github.com/adamsiemion",
"followers_url": "https://api.github.com/users/adamsiemion/followers",
"following_url": "https://api.github.com/users/adamsiemion/following{/other_user}",
"gists_url": "https://api.github.com/users/adamsiemion/gists{/gist_id}",
"starred_url": "https://api.github.com/users/adamsiemion/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/adamsiemion/subscriptions",
"organizations_url": "https://api.github.com/users/adamsiemion/orgs",
"repos_url": "https://api.github.com/users/adamsiemion/repos",
"events_url": "https://api.github.com/users/adamsiemion/events{/privacy}",
"received_events_url": "https://api.github.com/users/adamsiemion/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-10-17T10:35:35Z",
"updated_at": "2016-11-17T03:11:31Z",
"closed_at": "2016-11-17T03:11:31Z",
"author_association": "NONE",
"body": "Is there a quicker/better way to get a `GHPullRequest` instance from `searchIssues()` results?\n\nI have got`String sha1` and `GHRepository repository` instances and the following code:\n\n```\nfinal PagedSearchIterable<GHIssue> list = githubClient.searchIssues().q(sha1).list();\nfinal GHIssue issue = list.iterator().next();\nfinal String pullRequestUrl = issue.getPullRequest().getUrl().toString();\nfinal int pullRequestNumber = Integer.valueOf(pullRequestUrl.substring(pullRequestUrl.lastIndexOf('/')+1));\nfinal GHPullRequest pullRequest = repository.getPullRequest(pullRequestNumber);\n```\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/297",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/297/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/297/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/297/events",
"html_url": "https://github.com/hub4j/github-api/issues/297",
"id": 180104399,
"node_id": "MDU6SXNzdWUxODAxMDQzOTk=",
"number": 297,
"title": "Allow edit for maintainer support",
"user": {
"login": "qinfchen",
"id": 8294715,
"node_id": "MDQ6VXNlcjgyOTQ3MTU=",
"avatar_url": "https://avatars1.githubusercontent.com/u/8294715?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/qinfchen",
"html_url": "https://github.com/qinfchen",
"followers_url": "https://api.github.com/users/qinfchen/followers",
"following_url": "https://api.github.com/users/qinfchen/following{/other_user}",
"gists_url": "https://api.github.com/users/qinfchen/gists{/gist_id}",
"starred_url": "https://api.github.com/users/qinfchen/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/qinfchen/subscriptions",
"organizations_url": "https://api.github.com/users/qinfchen/orgs",
"repos_url": "https://api.github.com/users/qinfchen/repos",
"events_url": "https://api.github.com/users/qinfchen/events{/privacy}",
"received_events_url": "https://api.github.com/users/qinfchen/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 2,
"created_at": "2016-09-29T16:52:19Z",
"updated_at": "2016-10-03T15:01:31Z",
"closed_at": "2016-10-03T15:01:31Z",
"author_association": "NONE",
"body": "Is this supported? see details [here](https://github.com/blog/2247-improving-collaboration-with-forks)\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/296",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/296/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/296/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/296/events",
"html_url": "https://github.com/hub4j/github-api/issues/296",
"id": 179131708,
"node_id": "MDU6SXNzdWUxNzkxMzE3MDg=",
"number": 296,
"title": "run mvn install fail! Failure to find org.jenkins-ci:jenkins:pom:1.26 ??",
"user": {
"login": "nj-mqzhang",
"id": 10613380,
"node_id": "MDQ6VXNlcjEwNjEzMzgw",
"avatar_url": "https://avatars0.githubusercontent.com/u/10613380?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/nj-mqzhang",
"html_url": "https://github.com/nj-mqzhang",
"followers_url": "https://api.github.com/users/nj-mqzhang/followers",
"following_url": "https://api.github.com/users/nj-mqzhang/following{/other_user}",
"gists_url": "https://api.github.com/users/nj-mqzhang/gists{/gist_id}",
"starred_url": "https://api.github.com/users/nj-mqzhang/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/nj-mqzhang/subscriptions",
"organizations_url": "https://api.github.com/users/nj-mqzhang/orgs",
"repos_url": "https://api.github.com/users/nj-mqzhang/repos",
"events_url": "https://api.github.com/users/nj-mqzhang/events{/privacy}",
"received_events_url": "https://api.github.com/users/nj-mqzhang/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-09-26T03:22:25Z",
"updated_at": "2016-09-26T06:31:52Z",
"closed_at": "2016-09-26T06:30:14Z",
"author_association": "NONE",
"body": "Caused by: org.eclipse.aether.transfer.ArtifactNotFoundException: Failure to find org.jenkins-ci:jenkins:pom:1.26 in http://192.168.1.117:8081/nexus/content/groups/public was cached in the local repository, resolution will not be reattempted until the update interval of nexus has elapsed or updates are forced\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/295",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/295/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/295/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/295/events",
"html_url": "https://github.com/hub4j/github-api/pull/295",
"id": 177837024,
"node_id": "MDExOlB1bGxSZXF1ZXN0ODU4Mjk0NTY=",
"number": 295,
"title": "Use maximum permitted page size",
"user": {
"login": "jglick",
"id": 154109,
"node_id": "MDQ6VXNlcjE1NDEwOQ==",
"avatar_url": "https://avatars1.githubusercontent.com/u/154109?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jglick",
"html_url": "https://github.com/jglick",
"followers_url": "https://api.github.com/users/jglick/followers",
"following_url": "https://api.github.com/users/jglick/following{/other_user}",
"gists_url": "https://api.github.com/users/jglick/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jglick/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jglick/subscriptions",
"organizations_url": "https://api.github.com/users/jglick/orgs",
"repos_url": "https://api.github.com/users/jglick/repos",
"events_url": "https://api.github.com/users/jglick/events{/privacy}",
"received_events_url": "https://api.github.com/users/jglick/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 7,
"created_at": "2016-09-19T16:49:56Z",
"updated_at": "2016-10-24T21:04:05Z",
"closed_at": "2016-10-24T21:04:05Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/295",
"html_url": "https://github.com/hub4j/github-api/pull/295",
"diff_url": "https://github.com/hub4j/github-api/pull/295.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/295.patch"
},
"body": "Pending GraphQL, performance is going to be bad, but do what we can.\n\n@reviewbybees\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/294",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/294/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/294/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/294/events",
"html_url": "https://github.com/hub4j/github-api/issues/294",
"id": 175312885,
"node_id": "MDU6SXNzdWUxNzUzMTI4ODU=",
"number": 294,
"title": "Multiple assignee support",
"user": {
"login": "wsorenson",
"id": 281687,
"node_id": "MDQ6VXNlcjI4MTY4Nw==",
"avatar_url": "https://avatars3.githubusercontent.com/u/281687?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/wsorenson",
"html_url": "https://github.com/wsorenson",
"followers_url": "https://api.github.com/users/wsorenson/followers",
"following_url": "https://api.github.com/users/wsorenson/following{/other_user}",
"gists_url": "https://api.github.com/users/wsorenson/gists{/gist_id}",
"starred_url": "https://api.github.com/users/wsorenson/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/wsorenson/subscriptions",
"organizations_url": "https://api.github.com/users/wsorenson/orgs",
"repos_url": "https://api.github.com/users/wsorenson/repos",
"events_url": "https://api.github.com/users/wsorenson/events{/privacy}",
"received_events_url": "https://api.github.com/users/wsorenson/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-09-06T18:08:20Z",
"updated_at": "2016-11-19T22:51:23Z",
"closed_at": "2016-11-19T22:51:23Z",
"author_association": "NONE",
"body": "Issue should return a list of assignees;\n\nhttps://developer.github.com/changes/2016-5-27-multiple-assignees/\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/293",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/293/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/293/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/293/events",
"html_url": "https://github.com/hub4j/github-api/issues/293",
"id": 175306527,
"node_id": "MDU6SXNzdWUxNzUzMDY1Mjc=",
"number": 293,
"title": "Missing support for determining if authenticated user is organization owner",
"user": {
"login": "WesleyTrescott",
"id": 10776580,
"node_id": "MDQ6VXNlcjEwNzc2NTgw",
"avatar_url": "https://avatars2.githubusercontent.com/u/10776580?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/WesleyTrescott",
"html_url": "https://github.com/WesleyTrescott",
"followers_url": "https://api.github.com/users/WesleyTrescott/followers",
"following_url": "https://api.github.com/users/WesleyTrescott/following{/other_user}",
"gists_url": "https://api.github.com/users/WesleyTrescott/gists{/gist_id}",
"starred_url": "https://api.github.com/users/WesleyTrescott/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/WesleyTrescott/subscriptions",
"organizations_url": "https://api.github.com/users/WesleyTrescott/orgs",
"repos_url": "https://api.github.com/users/WesleyTrescott/repos",
"events_url": "https://api.github.com/users/WesleyTrescott/events{/privacy}",
"received_events_url": "https://api.github.com/users/WesleyTrescott/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 3,
"created_at": "2016-09-06T17:38:38Z",
"updated_at": "2016-11-19T23:26:14Z",
"closed_at": "2016-11-19T23:26:14Z",
"author_association": "NONE",
"body": "Some operations involving teams within organizations require the authenticated user to be an organization owner. As far as I can tell, there is no way to get this information in the current implementation. The following stackoverflow answer illustrates the the information I am trying to retrieve: [http://stackoverflow.com/a/28190753](http://stackoverflow.com/a/28190753)\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/291",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/291/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/291/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/291/events",
"html_url": "https://github.com/hub4j/github-api/issues/291",
"id": 169602557,
"node_id": "MDU6SXNzdWUxNjk2MDI1NTc=",
"number": 291,
"title": "weird format for get list of organizations",
"user": {
"login": "marti1125",
"id": 223240,
"node_id": "MDQ6VXNlcjIyMzI0MA==",
"avatar_url": "https://avatars0.githubusercontent.com/u/223240?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/marti1125",
"html_url": "https://github.com/marti1125",
"followers_url": "https://api.github.com/users/marti1125/followers",
"following_url": "https://api.github.com/users/marti1125/following{/other_user}",
"gists_url": "https://api.github.com/users/marti1125/gists{/gist_id}",
"starred_url": "https://api.github.com/users/marti1125/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/marti1125/subscriptions",
"organizations_url": "https://api.github.com/users/marti1125/orgs",
"repos_url": "https://api.github.com/users/marti1125/repos",
"events_url": "https://api.github.com/users/marti1125/events{/privacy}",
"received_events_url": "https://api.github.com/users/marti1125/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 4,
"created_at": "2016-08-05T13:03:54Z",
"updated_at": "2016-08-06T15:20:23Z",
"closed_at": "2016-08-06T03:58:07Z",
"author_association": "NONE",
"body": "GitHub gh = GitHub.connect(\"login\", \"token\");\nSystem.out.println(gh.getMyOrganizations());\n\nHow to I can parse this? =/\n\n{mozillaperu=GHOrganization@29ba4338[login=mozillaperu,location=<null>,blog=<null>,email=<null>,name=<null>,company=<null>,followers=0,following=0,url=https://api.github.com/orgs/mozillaperu,id=1221419], qillu=GHOrganization@57d5872c[login=qillu,location=<null>,blog=<null>,email=<null>,name=<null>,company=<null>,followers=0,following=0,url=https://api.github.com/orgs/qillu,id=16871604], eknowit=GHOrganization@667a738[login=eknowit,location=<null>,blog=<null>,email=<null>,name=<null>,company=<null>,followers=0,following=0,url=https://api.github.com/orgs/eknowit,id=1102009], VulpesTools=GHOrganization@36f0f1be[login=VulpesTools,location=<null>,blog=<null>,email=<null>,name=<null>,company=<null>,followers=0,following=0,url=https://api.github.com/orgs/VulpesTools,id=8617634], GenerationOpen=GHOrganization@157632c9[login=GenerationOpen,location=<null>,blog=<null>,email=<null>,name=<null>,company=<null>,followers=0,following=0,url=https://api.github.com/orgs/GenerationOpen,id=4251591], mozillahispano=GHOrganization@6ee12bac[login=mozillahispano,location=<null>,blog=<null>,email=<null>,name=<null>,company=<null>,followers=0,following=0,url=https://api.github.com/orgs/mozillahispano,id=1511160], mozilla-appmaker=GHOrganization@55040f2f[login=mozilla-appmaker,location=<null>,blog=<null>,email=<null>,name=<null>,company=<null>,followers=0,following=0,url=https://api.github.com/orgs/mozilla-appmaker,id=5852021]}\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/290",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/290/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/290/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/290/events",
"html_url": "https://github.com/hub4j/github-api/issues/290",
"id": 166946455,
"node_id": "MDU6SXNzdWUxNjY5NDY0NTU=",
"number": 290,
"title": "OkHttp is out of date",
"user": {
"login": "mh-park",
"id": 10649298,
"node_id": "MDQ6VXNlcjEwNjQ5Mjk4",
"avatar_url": "https://avatars3.githubusercontent.com/u/10649298?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mh-park",
"html_url": "https://github.com/mh-park",
"followers_url": "https://api.github.com/users/mh-park/followers",
"following_url": "https://api.github.com/users/mh-park/following{/other_user}",
"gists_url": "https://api.github.com/users/mh-park/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mh-park/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mh-park/subscriptions",
"organizations_url": "https://api.github.com/users/mh-park/orgs",
"repos_url": "https://api.github.com/users/mh-park/repos",
"events_url": "https://api.github.com/users/mh-park/events{/privacy}",
"received_events_url": "https://api.github.com/users/mh-park/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 4,
"created_at": "2016-07-22T00:24:00Z",
"updated_at": "2016-08-06T04:04:37Z",
"closed_at": "2016-08-06T04:04:37Z",
"author_association": "NONE",
"body": "OkUrlFactory is deprecated, so using the Cache is not the same as described on homepage. \n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/289",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/289/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/289/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/289/events",
"html_url": "https://github.com/hub4j/github-api/pull/289",
"id": 166917048,
"node_id": "MDExOlB1bGxSZXF1ZXN0NzgzODY4NjM=",
"number": 289,
"title": "Implement an abuse handler",
"user": {
"login": "mmitche",
"id": 8725170,
"node_id": "MDQ6VXNlcjg3MjUxNzA=",
"avatar_url": "https://avatars1.githubusercontent.com/u/8725170?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mmitche",
"html_url": "https://github.com/mmitche",
"followers_url": "https://api.github.com/users/mmitche/followers",
"following_url": "https://api.github.com/users/mmitche/following{/other_user}",
"gists_url": "https://api.github.com/users/mmitche/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mmitche/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mmitche/subscriptions",
"organizations_url": "https://api.github.com/users/mmitche/orgs",
"repos_url": "https://api.github.com/users/mmitche/repos",
"events_url": "https://api.github.com/users/mmitche/events{/privacy}",
"received_events_url": "https://api.github.com/users/mmitche/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-07-21T21:02:19Z",
"updated_at": "2016-08-06T02:59:02Z",
"closed_at": "2016-08-06T02:59:02Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/289",
"html_url": "https://github.com/hub4j/github-api/pull/289",
"diff_url": "https://github.com/hub4j/github-api/pull/289.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/289.patch"
},
"body": "If too many requests are made within X amount of time (not the traditional hourly rate limit), github may begin returning 403. Then we should wait for a bit to attempt to access the API again. In this case, we parse out the Retry-After field returned and sleep until that (it's usually 60 seconds)\n\nFixes #285 \n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/288",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/288/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/288/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/288/events",
"html_url": "https://github.com/hub4j/github-api/issues/288",
"id": 165158992,
"node_id": "MDU6SXNzdWUxNjUxNTg5OTI=",
"number": 288,
"title": "400 from OKHttp getInputStream",
"user": {
"login": "sbhaktha",
"id": 5631150,
"node_id": "MDQ6VXNlcjU2MzExNTA=",
"avatar_url": "https://avatars2.githubusercontent.com/u/5631150?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/sbhaktha",
"html_url": "https://github.com/sbhaktha",
"followers_url": "https://api.github.com/users/sbhaktha/followers",
"following_url": "https://api.github.com/users/sbhaktha/following{/other_user}",
"gists_url": "https://api.github.com/users/sbhaktha/gists{/gist_id}",
"starred_url": "https://api.github.com/users/sbhaktha/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/sbhaktha/subscriptions",
"organizations_url": "https://api.github.com/users/sbhaktha/orgs",
"repos_url": "https://api.github.com/users/sbhaktha/repos",
"events_url": "https://api.github.com/users/sbhaktha/events{/privacy}",
"received_events_url": "https://api.github.com/users/sbhaktha/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 10,
"created_at": "2016-07-12T19:23:10Z",
"updated_at": "2016-07-19T21:44:19Z",
"closed_at": "2016-07-19T15:00:30Z",
"author_association": "NONE",
"body": "Hello,\n\nI have built a tool using your API, which has been working for many months now, but suddenly fails due to a `FileNotFoundException` thrown by `getInputStrem` in OKHttp. When I paste the url it is trying to download, into my browser, it works perfectly fine. I can see the file contents. This is very strange. Do you have any clue about this?\n\nStack trace:\n\n```\ntables [ERROR] [07/12/2016 12:15:41.086] [TableService-akka.actor.default-dispatcher-8] [akka://TableService/user/simple-service-actor] Error during processing of request HttpRequest(POST,http://localhost:8084/api/metadata/list,List(Host: localhost:8084, Connection: keep-alive, Content-Length: 59, Origin: http://localhost:8084, X-Requested-With: XMLHttpRequest, User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41, Content-Type: application/json, Referer: http://localhost:8084/, Accept-Encoding: gzip, deflate, lzma, Accept-Language: en-US, en;q=0.8, Cookie: tablestore-data-git=eyJhY2Nlc3NUb2tlbiI6ImYyZDI1OTViNGQ4OTMwMjIwMGI2YjE2MjNhNzQ3ZjQ3MzI1ZWJkOWMifQ==; tablestore-data-git2=eyJhY2Nlc3NUb2tlbiI6ImZlYmMxYTRlYjA1MmI4OWJlNDQwOWFmODk3OGNkYWFhYWY1OWZlNWEifQ==),HttpEntity(application/json,{\"repo\":\"aristo-tables\",\"fork\":\"allenai\",\"branch\":\"master\"}),HTTP/1.1)\ntables java.io.FileNotFoundException: 400: Invalid request\ntables \ntables at org.kohsuke.github.Requester.handleApiError(Requester.java:527)\ntables at org.kohsuke.github.Requester.asStream(Requester.java:293)\ntables at org.kohsuke.github.GHContent.read(GHContent.java:118)\ntables at org.allenai.ari.tables.GitHubUtil$$anonfun$getCsvFileLocal$1.apply(GitHubUtil.scala:420)\ntables at org.allenai.ari.tables.GitHubUtil$$anonfun$getCsvFileLocal$1.apply(GitHubUtil.scala:417)\ntables at scala.Option.foreach(Option.scala:257)\ntables at org.allenai.ari.tables.GitHubUtil.getCsvFileLocal(GitHubUtil.scala:417)\ntables at org.allenai.ari.tables.GitHubUtil$$anonfun$7.apply(GitHubUtil.scala:239)\ntables at org.allenai.ari.tables.GitHubUtil$$anonfun$7.apply(GitHubUtil.scala:236)\ntables at scala.collection.parallel.mutable.ParArray$ParArrayIterator.flatmap2combiner(ParArray.scala:417)\ntables at scala.collection.parallel.ParIterableLike$FlatMap.leaf(ParIterableLike.scala:1072)\ntables at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply$mcV$sp(Tasks.scala:49)\ntables at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply(Tasks.scala:48)\ntables at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply(Tasks.scala:48)\ntables at scala.collection.parallel.Task$class.tryLeaf(Tasks.scala:51)\ntables at scala.collection.parallel.ParIterableLike$FlatMap.tryLeaf(ParIterableLike.scala:1068)\ntables at scala.collection.parallel.AdaptiveWorkStealingTasks$WrappedTask$class.internal(Tasks.scala:159)\ntables at scala.collection.parallel.AdaptiveWorkStealingForkJoinTasks$WrappedTask.internal(Tasks.scala:443)\ntables at scala.collection.parallel.AdaptiveWorkStealingTasks$WrappedTask$class.compute(Tasks.scala:149)\ntables at scala.collection.parallel.AdaptiveWorkStealingForkJoinTasks$WrappedTask.compute(Tasks.scala:443)\ntables at scala.concurrent.forkjoin.RecursiveAction.exec(RecursiveAction.java:160)\ntables at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)\ntables at scala.concurrent.forkjoin.ForkJoinTask.doJoin(ForkJoinTask.java:341)\ntables at scala.concurrent.forkjoin.ForkJoinTask.join(ForkJoinTask.java:673)\ntables at scala.collection.parallel.ForkJoinTasks$WrappedTask$class.sync(Tasks.scala:378)\ntables at scala.collection.parallel.AdaptiveWorkStealingForkJoinTasks$WrappedTask.sync(Tasks.scala:443)\ntables at scala.collection.parallel.ForkJoinTasks$class.executeAndWaitResult(Tasks.scala:426)\ntables at scala.collection.parallel.ForkJoinTaskSupport.executeAndWaitResult(TaskSupport.scala:56)\ntables at scala.collection.parallel.ExecutionContextTasks$class.executeAndWaitResult(Tasks.scala:558)\ntables at scala.collection.parallel.ExecutionContextTaskSupport.executeAndWaitResult(TaskSupport.scala:80)\ntables at scala.collection.parallel.ParIterableLike$ResultMapping.leaf(ParIterableLike.scala:958)\ntables at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply$mcV$sp(Tasks.scala:49)\ntables at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply(Tasks.scala:48)\ntables at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply(Tasks.scala:48)\ntables at scala.collection.parallel.Task$class.tryLeaf(Tasks.scala:51)\ntables at scala.collection.parallel.ParIterableLike$ResultMapping.tryLeaf(ParIterableLike.scala:953)\ntables at scala.collection.parallel.AdaptiveWorkStealingTasks$WrappedTask$class.compute(Tasks.scala:152)\ntables at scala.collection.parallel.AdaptiveWorkStealingForkJoinTasks$WrappedTask.compute(Tasks.scala:443)\ntables at scala.concurrent.forkjoin.RecursiveAction.exec(RecursiveAction.java:160)\ntables at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)\ntables at scala.concurrent.forkjoin.ForkJoinTask.doJoin(ForkJoinTask.java:341)\ntables at scala.concurrent.forkjoin.ForkJoinTask.join(ForkJoinTask.java:673)\ntables at scala.collection.parallel.ForkJoinTasks$WrappedTask$class.sync(Tasks.scala:378)\ntables at scala.collection.parallel.AdaptiveWorkStealingForkJoinTasks$WrappedTask.sync(Tasks.scala:443)\ntables at scala.collection.parallel.ForkJoinTasks$class.executeAndWaitResult(Tasks.scala:426)\ntables at scala.collection.parallel.ForkJoinTaskSupport.executeAndWaitResult(TaskSupport.scala:56)\ntables at scala.collection.parallel.ExecutionContextTasks$class.executeAndWaitResult(Tasks.scala:558)\ntables at scala.collection.parallel.ExecutionContextTaskSupport.executeAndWaitResult(TaskSupport.scala:80)\ntables at scala.collection.parallel.ParIterableLike$class.flatMap(ParIterableLike.scala:513)\ntables at scala.collection.parallel.mutable.ParArray.flatMap(ParArray.scala:56)\ntables at org.allenai.ari.tables.GitHubUtil.org$allenai$ari$tables$GitHubUtil$$getTableMetadata(GitHubUtil.scala:236)\ntables at org.allenai.ari.tables.GitHubUtil$$anonfun$getTableMetadata$2.apply(GitHubUtil.scala:229)\ntables at org.allenai.ari.tables.GitHubUtil$$anonfun$getTableMetadata$2.apply(GitHubUtil.scala:229)\ntables at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)\ntables at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:249)\ntables at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)\ntables at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)\ntables at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply$mcV$sp(BatchingExecutor.scala:91)\ntables at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91)\ntables at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91)\ntables at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:72)\ntables at akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:90)\ntables at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:39)\ntables at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:399)\ntables at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)\ntables at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)\ntables at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)\ntables at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)\ntables Caused by: java.io.FileNotFoundException: https://raw.githubusercontent.com/allenai/aristo-tables/master/tables/abstract_concrete/abstract_concrete.csv?token=AFXsrivOTIoDru9Htw9aNTJbprmE5m0Gks5XhUHfwA%3D%3D\ntables at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:228)\ntables at com.squareup.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)\ntables at com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)\ntables at org.kohsuke.github.Requester.asStream(Requester.java:291)\ntables ... 66 more\n```\n\nYour help is greatly appreciated,\nSumithra\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/287",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/287/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/287/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/287/events",
"html_url": "https://github.com/hub4j/github-api/issues/287",
"id": 163039212,
"node_id": "MDU6SXNzdWUxNjMwMzkyMTI=",
"number": 287,
"title": "pagination support search APIs",
"user": {
"login": "qinfchen",
"id": 8294715,
"node_id": "MDQ6VXNlcjgyOTQ3MTU=",
"avatar_url": "https://avatars1.githubusercontent.com/u/8294715?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/qinfchen",
"html_url": "https://github.com/qinfchen",
"followers_url": "https://api.github.com/users/qinfchen/followers",
"following_url": "https://api.github.com/users/qinfchen/following{/other_user}",
"gists_url": "https://api.github.com/users/qinfchen/gists{/gist_id}",
"starred_url": "https://api.github.com/users/qinfchen/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/qinfchen/subscriptions",
"organizations_url": "https://api.github.com/users/qinfchen/orgs",
"repos_url": "https://api.github.com/users/qinfchen/repos",
"events_url": "https://api.github.com/users/qinfchen/events{/privacy}",
"received_events_url": "https://api.github.com/users/qinfchen/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-06-29T22:14:18Z",
"updated_at": "2016-06-30T14:25:20Z",
"closed_at": "2016-06-30T14:25:20Z",
"author_association": "NONE",
"body": "It doesn't seem like there is a support pagination for search APIs. \n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/286",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/286/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/286/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/286/events",
"html_url": "https://github.com/hub4j/github-api/issues/286",
"id": 162839227,
"node_id": "MDU6SXNzdWUxNjI4MzkyMjc=",
"number": 286,
"title": "significant more API calls for same code",
"user": {
"login": "aspyker",
"id": 260750,
"node_id": "MDQ6VXNlcjI2MDc1MA==",
"avatar_url": "https://avatars1.githubusercontent.com/u/260750?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/aspyker",
"html_url": "https://github.com/aspyker",
"followers_url": "https://api.github.com/users/aspyker/followers",
"following_url": "https://api.github.com/users/aspyker/following{/other_user}",
"gists_url": "https://api.github.com/users/aspyker/gists{/gist_id}",
"starred_url": "https://api.github.com/users/aspyker/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/aspyker/subscriptions",
"organizations_url": "https://api.github.com/users/aspyker/orgs",
"repos_url": "https://api.github.com/users/aspyker/repos",
"events_url": "https://api.github.com/users/aspyker/events{/privacy}",
"received_events_url": "https://api.github.com/users/aspyker/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 6,
"created_at": "2016-06-29T04:36:45Z",
"updated_at": "2016-08-09T01:25:00Z",
"closed_at": "2016-08-06T04:10:32Z",
"author_association": "NONE",
"body": "I'm researching deeper, but with 1.72 I get:\n\nremaining calls 4364\nabout to look up repo EVCache\n2016-06-28 21:28:20 INFO GithubAccess:53 - repo = EVCache, forks = 82, stars = 314\n2016-06-28 21:28:20 DEBUG GithubAccess:56 - openIssues = 0, openPullRequests = 0\n2016-06-28 21:28:22 DEBUG GithubAccess:107 - daysSinceLastCommit = 0\n2016-06-28 21:28:23 DEBUG GithubAccess:111 - numContribitors = 16, contributorEmails = ArrayBuffer(smadappa, senugula, jkschneider, vuzilla, ScottMansfield, rspieldenner, elandau, gitter-badger, rdegnan, nadavc, aspyker, trigan-d, pauloricardomg, kedargsm, quidryan, Randgalt)\n2016-06-28 21:28:24 DEBUG GithubAccess:146 - avg days to close 14 issues = 357 days\n2016-06-28 21:28:24 DEBUG GithubAccess:128 - avg days to close 13 pull requests = 185 days\n2016-06-28 21:28:24 DEBUG GithubAccess:96 - repo json = {\"asOfISO\":\"2016-06-29T04:27:43Z\",\"asOfYYYYMMDD\":\"2016-06-29\",\"repo_name\":\"EVCache\",\"public\":true,\"osslifecycle\":\"UNKNOWN\",\"forks\":82,\"stars\":314,\"numContributors\":16,\"issues\":{\"openCount\":0,\"closedCount\":14,\"avgTimeToCloseInDays\":357},\"pullRequests\":{\"openCount\":0,\"closedCount\":13,\"avgTimeToCloseInDays\":185},\"commits\":{\"daysSinceLastCommit\":0},\"contributors\":[\"smadappa\",\"senugula\",\"jkschneider\",\"vuzilla\",\"ScottMansfield\",\"rspieldenner\",\"elandau\",\"gitter-badger\",\"rdegnan\",\"nadavc\",\"aspyker\",\"trigan-d\",\"pauloricardomg\",\"kedargsm\",\"quidryan\",\"Randgalt\"]}\nremaining calls 4341\n\nresulting in 23 API calls\n\nwith 1.76, I get:\n\nremaining calls 4640\nabout to look up repo EVCache\n2016-06-28 21:22:22 INFO GithubAccess:53 - repo = EVCache, forks = 82, stars = 314\n2016-06-28 21:22:22 DEBUG GithubAccess:56 - openIssues = 0, openPullRequests = 0\n2016-06-28 21:23:01 DEBUG GithubAccess:107 - daysSinceLastCommit = 0\n2016-06-28 21:23:03 DEBUG GithubAccess:111 - numContribitors = 16, contributorEmails = ArrayBuffer(smadappa, senugula, jkschneider, vuzilla, ScottMansfield, rspieldenner, elandau, gitter-badger, rdegnan, nadavc, aspyker, trigan-d, pauloricardomg, kedargsm, quidryan, Randgalt)\n2016-06-28 21:23:04 DEBUG GithubAccess:146 - avg days to close 14 issues = 357 days\n2016-06-28 21:23:04 DEBUG GithubAccess:128 - avg days to close 13 pull requests = 185 days\n2016-06-28 21:23:04 DEBUG GithubAccess:96 - repo json = {\"asOfISO\":\"2016-06-29T04:20:26Z\",\"asOfYYYYMMDD\":\"2016-06-29\",\"repo_name\":\"EVCache\",\"public\":true,\"osslifecycle\":\"UNKNOWN\",\"forks\":82,\"stars\":314,\"numContributors\":16,\"issues\":{\"openCount\":0,\"closedCount\":14,\"avgTimeToCloseInDays\":357},\"pullRequests\":{\"openCount\":0,\"closedCount\":13,\"avgTimeToCloseInDays\":185},\"commits\":{\"daysSinceLastCommit\":0},\"contributors\":[\"smadappa\",\"senugula\",\"jkschneider\",\"vuzilla\",\"ScottMansfield\",\"rspieldenner\",\"elandau\",\"gitter-badger\",\"rdegnan\",\"nadavc\",\"aspyker\",\"trigan-d\",\"pauloricardomg\",\"kedargsm\",\"quidryan\",\"Randgalt\"]}\nremaining calls 4409\n\nresulting in 231 API calls\n\nThis is running this code:\n\nhttps://github.com/Netflix/osstracker/blob/master/osstracker-scraper/src/main/scala/com/netflix/oss/tools/osstrackerscraper/GithubAccess.scala#L52\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/285",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/285/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/285/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/285/events",
"html_url": "https://github.com/hub4j/github-api/issues/285",
"id": 161777707,
"node_id": "MDU6SXNzdWUxNjE3Nzc3MDc=",
"number": 285,
"title": "Excessive concurrent request rate limit not handled",
"user": {
"login": "mmitche",
"id": 8725170,
"node_id": "MDQ6VXNlcjg3MjUxNzA=",
"avatar_url": "https://avatars1.githubusercontent.com/u/8725170?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mmitche",
"html_url": "https://github.com/mmitche",
"followers_url": "https://api.github.com/users/mmitche/followers",
"following_url": "https://api.github.com/users/mmitche/following{/other_user}",
"gists_url": "https://api.github.com/users/mmitche/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mmitche/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mmitche/subscriptions",
"organizations_url": "https://api.github.com/users/mmitche/orgs",
"repos_url": "https://api.github.com/users/mmitche/repos",
"events_url": "https://api.github.com/users/mmitche/events{/privacy}",
"received_events_url": "https://api.github.com/users/mmitche/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2016-06-22T20:27:32Z",
"updated_at": "2016-08-06T02:59:02Z",
"closed_at": "2016-08-06T02:59:02Z",
"author_association": "CONTRIBUTOR",
"body": "If the hourly rate limit is not hit, but the API abuse mechanism is triggered, the API won't handle this gracefully. Instead, it bails. I think the ideal case here would be to wait for a small random amount of time (< 5 seconds perhaps, with some backoff) and retry\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/284",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/284/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/284/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/284/events",
"html_url": "https://github.com/hub4j/github-api/pull/284",
"id": 161052879,
"node_id": "MDExOlB1bGxSZXF1ZXN0NzQzNTI2NjA=",
"number": 284,
"title": "Addition of License API elements",
"user": {
"login": "dedickinson",
"id": 702835,
"node_id": "MDQ6VXNlcjcwMjgzNQ==",
"avatar_url": "https://avatars2.githubusercontent.com/u/702835?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dedickinson",
"html_url": "https://github.com/dedickinson",
"followers_url": "https://api.github.com/users/dedickinson/followers",
"following_url": "https://api.github.com/users/dedickinson/following{/other_user}",
"gists_url": "https://api.github.com/users/dedickinson/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dedickinson/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dedickinson/subscriptions",
"organizations_url": "https://api.github.com/users/dedickinson/orgs",
"repos_url": "https://api.github.com/users/dedickinson/repos",
"events_url": "https://api.github.com/users/dedickinson/events{/privacy}",
"received_events_url": "https://api.github.com/users/dedickinson/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-06-19T02:18:23Z",
"updated_at": "2016-08-06T03:56:00Z",
"closed_at": "2016-08-06T03:56:00Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/284",
"html_url": "https://github.com/hub4j/github-api/pull/284",
"diff_url": "https://github.com/hub4j/github-api/pull/284.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/284.patch"
},
"body": "I've added in functionality to provide license information from https://developer.github.com/v3/licenses/:\n- Get list of GitHub licenses using `GitHub#listLicenses()`\n- Get the details for a specific license using `GitHub#getLicense(String key)`\n- For a `GHRepository`:\n - The basic license details are loaded with the repo information (`GHRepository#getLicense`)\n - `GHRepository#getFullLicense` will get the full license information (ala `GitHub#getLicense(String key)`)\n - `GHRepository#getLicenseContent()` will get the license content information for the repository\n\nAs this uses a preview API, access to the information requires the use of `application/vnd.github.drax-preview+json` in the HTTP connection's ACCEPT header. This is provided in `PreviewHttpConnector.java`.\n\nAll existing functionality appears to continue working with the normal connector - `PreviewHttpConnector` just opens up the extra data from the Licenses API.\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/283",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/283/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/283/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/283/events",
"html_url": "https://github.com/hub4j/github-api/pull/283",
"id": 155117490,
"node_id": "MDExOlB1bGxSZXF1ZXN0NzAyNTgwNjA=",
"number": 283,
"title": "Add some level of synchronization to the root of the API",
"user": {
"login": "mmitche",
"id": 8725170,
"node_id": "MDQ6VXNlcjg3MjUxNzA=",
"avatar_url": "https://avatars1.githubusercontent.com/u/8725170?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mmitche",
"html_url": "https://github.com/mmitche",
"followers_url": "https://api.github.com/users/mmitche/followers",
"following_url": "https://api.github.com/users/mmitche/following{/other_user}",
"gists_url": "https://api.github.com/users/mmitche/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mmitche/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mmitche/subscriptions",
"organizations_url": "https://api.github.com/users/mmitche/orgs",
"repos_url": "https://api.github.com/users/mmitche/repos",
"events_url": "https://api.github.com/users/mmitche/events{/privacy}",
"received_events_url": "https://api.github.com/users/mmitche/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 6,
"created_at": "2016-05-16T20:43:48Z",
"updated_at": "2017-09-09T19:48:16Z",
"closed_at": "2017-09-09T19:48:15Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/283",
"html_url": "https://github.com/hub4j/github-api/pull/283",
"diff_url": "https://github.com/hub4j/github-api/pull/283.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/283.patch"
},
"body": "This adds some synchronization to the maps at the root of the API to avoid duplicated calls to the actual GH REST API. Specifically this is targeted around the two maps, orgs and users. This fix makes the GHPRB jenkins plugin behave much better when there are lots of projects that could build for a specific repo (even if only a few are actually triggered)\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/282",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/282/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/282/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/282/events",
"html_url": "https://github.com/hub4j/github-api/pull/282",
"id": 154882236,
"node_id": "MDExOlB1bGxSZXF1ZXN0NzAxMDc3NTg=",
"number": 282,
"title": "related to JENKINS-34834. updating test for similar condition",
"user": {
"login": "apemberton",
"id": 86439,
"node_id": "MDQ6VXNlcjg2NDM5",
"avatar_url": "https://avatars1.githubusercontent.com/u/86439?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/apemberton",
"html_url": "https://github.com/apemberton",
"followers_url": "https://api.github.com/users/apemberton/followers",
"following_url": "https://api.github.com/users/apemberton/following{/other_user}",
"gists_url": "https://api.github.com/users/apemberton/gists{/gist_id}",
"starred_url": "https://api.github.com/users/apemberton/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/apemberton/subscriptions",
"organizations_url": "https://api.github.com/users/apemberton/orgs",
"repos_url": "https://api.github.com/users/apemberton/repos",
"events_url": "https://api.github.com/users/apemberton/events{/privacy}",
"received_events_url": "https://api.github.com/users/apemberton/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2016-05-15T00:08:46Z",
"updated_at": "2016-06-03T04:52:26Z",
"closed_at": "2016-06-03T04:52:26Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/282",
"html_url": "https://github.com/hub4j/github-api/pull/282",
"diff_url": "https://github.com/hub4j/github-api/pull/282.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/282.patch"
},
"body": "Since GitHub no longer creates a default team per organization (ie: no more default 'Owners' team), this test needs to be updated. \n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/281",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/281/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/281/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/281/events",
"html_url": "https://github.com/hub4j/github-api/pull/281",
"id": 154852610,
"node_id": "MDExOlB1bGxSZXF1ZXN0NzAwOTE1MDg=",
"number": 281,
"title": "Add Slug to GHTeam per v3 API: https://developer.github.com/v3/orgs/t…",
"user": {
"login": "apemberton",
"id": 86439,
"node_id": "MDQ6VXNlcjg2NDM5",
"avatar_url": "https://avatars1.githubusercontent.com/u/86439?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/apemberton",
"html_url": "https://github.com/apemberton",
"followers_url": "https://api.github.com/users/apemberton/followers",
"following_url": "https://api.github.com/users/apemberton/following{/other_user}",
"gists_url": "https://api.github.com/users/apemberton/gists{/gist_id}",
"starred_url": "https://api.github.com/users/apemberton/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/apemberton/subscriptions",
"organizations_url": "https://api.github.com/users/apemberton/orgs",
"repos_url": "https://api.github.com/users/apemberton/repos",
"events_url": "https://api.github.com/users/apemberton/events{/privacy}",
"received_events_url": "https://api.github.com/users/apemberton/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 7,
"created_at": "2016-05-14T13:00:55Z",
"updated_at": "2016-06-15T14:35:12Z",
"closed_at": "2016-06-03T04:51:47Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/281",
"html_url": "https://github.com/hub4j/github-api/pull/281",
"diff_url": "https://github.com/hub4j/github-api/pull/281.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/281.patch"
},
"body": "https://developer.github.com/v3/orgs/teams/ has a slug property for teams. This property is similar to the login property for users and organizations - a URL path friendly tokenized string (as opposed to free text in the name field). \n\nSlug is better suited for use in automated / scripting cases when dealing with the Team API.\n\nAdmittedly, I wrote a test but could not test as the project's test harness requires super powers which I do not possess.\n\n@reviewbybees\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/279",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/279/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/279/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/279/events",
"html_url": "https://github.com/hub4j/github-api/issues/279",
"id": 153510442,
"node_id": "MDU6SXNzdWUxNTM1MTA0NDI=",
"number": 279,
"title": "team.add(repo) should accept permission flag",
"user": {
"login": "tomerd",
"id": 147247,
"node_id": "MDQ6VXNlcjE0NzI0Nw==",
"avatar_url": "https://avatars3.githubusercontent.com/u/147247?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/tomerd",
"html_url": "https://github.com/tomerd",
"followers_url": "https://api.github.com/users/tomerd/followers",
"following_url": "https://api.github.com/users/tomerd/following{/other_user}",
"gists_url": "https://api.github.com/users/tomerd/gists{/gist_id}",
"starred_url": "https://api.github.com/users/tomerd/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/tomerd/subscriptions",
"organizations_url": "https://api.github.com/users/tomerd/orgs",
"repos_url": "https://api.github.com/users/tomerd/repos",
"events_url": "https://api.github.com/users/tomerd/events{/privacy}",
"received_events_url": "https://api.github.com/users/tomerd/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2016-05-06T18:26:15Z",
"updated_at": "2016-06-04T03:56:12Z",
"closed_at": "2016-06-04T03:56:12Z",
"author_association": "NONE",
"body": "https://developer.github.com/v3/orgs/teams/#add-or-update-team-repository\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/278",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/278/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/278/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/278/events",
"html_url": "https://github.com/hub4j/github-api/pull/278",
"id": 152887705,
"node_id": "MDExOlB1bGxSZXF1ZXN0Njg3ODQ3ODc=",
"number": 278,
"title": "Fixed broken link",
"user": {
"login": "jglick",
"id": 154109,
"node_id": "MDQ6VXNlcjE1NDEwOQ==",
"avatar_url": "https://avatars1.githubusercontent.com/u/154109?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jglick",
"html_url": "https://github.com/jglick",
"followers_url": "https://api.github.com/users/jglick/followers",
"following_url": "https://api.github.com/users/jglick/following{/other_user}",
"gists_url": "https://api.github.com/users/jglick/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jglick/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jglick/subscriptions",
"organizations_url": "https://api.github.com/users/jglick/orgs",
"repos_url": "https://api.github.com/users/jglick/repos",
"events_url": "https://api.github.com/users/jglick/events{/privacy}",
"received_events_url": "https://api.github.com/users/jglick/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 3,
"created_at": "2016-05-03T22:20:31Z",
"updated_at": "2016-06-03T04:50:38Z",
"closed_at": "2016-06-03T04:50:37Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/278",
"html_url": "https://github.com/hub4j/github-api/pull/278",
"diff_url": "https://github.com/hub4j/github-api/pull/278.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/278.patch"
},
"body": "@reviewbybees\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/277",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/277/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/277/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/277/events",
"html_url": "https://github.com/hub4j/github-api/pull/277",
"id": 152044790,
"node_id": "MDExOlB1bGxSZXF1ZXN0Njg0NzUwMDM=",
"number": 277,
"title": "Updated Date was wrong",
"user": {
"login": "KondaReddyR",
"id": 841750,
"node_id": "MDQ6VXNlcjg0MTc1MA==",
"avatar_url": "https://avatars0.githubusercontent.com/u/841750?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/KondaReddyR",
"html_url": "https://github.com/KondaReddyR",
"followers_url": "https://api.github.com/users/KondaReddyR/followers",
"following_url": "https://api.github.com/users/KondaReddyR/following{/other_user}",
"gists_url": "https://api.github.com/users/KondaReddyR/gists{/gist_id}",
"starred_url": "https://api.github.com/users/KondaReddyR/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/KondaReddyR/subscriptions",
"organizations_url": "https://api.github.com/users/KondaReddyR/orgs",
"repos_url": "https://api.github.com/users/KondaReddyR/repos",
"events_url": "https://api.github.com/users/KondaReddyR/events{/privacy}",
"received_events_url": "https://api.github.com/users/KondaReddyR/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2016-04-30T18:20:58Z",
"updated_at": "2016-06-03T04:50:22Z",
"closed_at": "2016-06-03T04:50:22Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/277",
"html_url": "https://github.com/hub4j/github-api/pull/277",
"diff_url": "https://github.com/hub4j/github-api/pull/277.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/277.patch"
},
"body": ""
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/276",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/276/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/276/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/276/events",
"html_url": "https://github.com/hub4j/github-api/pull/276",
"id": 151828897,
"node_id": "MDExOlB1bGxSZXF1ZXN0NjgzNDY2MTQ=",
"number": 276,
"title": "Add support to delete a team",
"user": {
"login": "thug-gamer",
"id": 15268260,
"node_id": "MDQ6VXNlcjE1MjY4MjYw",
"avatar_url": "https://avatars3.githubusercontent.com/u/15268260?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/thug-gamer",
"html_url": "https://github.com/thug-gamer",
"followers_url": "https://api.github.com/users/thug-gamer/followers",
"following_url": "https://api.github.com/users/thug-gamer/following{/other_user}",
"gists_url": "https://api.github.com/users/thug-gamer/gists{/gist_id}",
"starred_url": "https://api.github.com/users/thug-gamer/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/thug-gamer/subscriptions",
"organizations_url": "https://api.github.com/users/thug-gamer/orgs",
"repos_url": "https://api.github.com/users/thug-gamer/repos",
"events_url": "https://api.github.com/users/thug-gamer/events{/privacy}",
"received_events_url": "https://api.github.com/users/thug-gamer/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2016-04-29T09:42:45Z",
"updated_at": "2016-06-03T04:50:11Z",
"closed_at": "2016-06-03T04:50:11Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/276",
"html_url": "https://github.com/hub4j/github-api/pull/276",
"diff_url": "https://github.com/hub4j/github-api/pull/276.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/276.patch"
},
"body": "Add a method to delete a team.\n\n@kohsuke @oleg-nenashev Could you please review this pull request?\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/275",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/275/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/275/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/275/events",
"html_url": "https://github.com/hub4j/github-api/issues/275",
"id": 151167688,
"node_id": "MDU6SXNzdWUxNTExNjc2ODg=",
"number": 275,
"title": "Pull request mergeability is boolean but should be trinary",
"user": {
"login": "PerilousApricot",
"id": 93354,
"node_id": "MDQ6VXNlcjkzMzU0",
"avatar_url": "https://avatars0.githubusercontent.com/u/93354?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/PerilousApricot",
"html_url": "https://github.com/PerilousApricot",
"followers_url": "https://api.github.com/users/PerilousApricot/followers",
"following_url": "https://api.github.com/users/PerilousApricot/following{/other_user}",
"gists_url": "https://api.github.com/users/PerilousApricot/gists{/gist_id}",
"starred_url": "https://api.github.com/users/PerilousApricot/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/PerilousApricot/subscriptions",
"organizations_url": "https://api.github.com/users/PerilousApricot/orgs",
"repos_url": "https://api.github.com/users/PerilousApricot/repos",
"events_url": "https://api.github.com/users/PerilousApricot/events{/privacy}",
"received_events_url": "https://api.github.com/users/PerilousApricot/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 6,
"created_at": "2016-04-26T15:36:39Z",
"updated_at": "2016-06-04T04:48:43Z",
"closed_at": "2016-06-04T03:52:27Z",
"author_association": "NONE",
"body": "According to the API docs: \n\n\"The value of the mergeable attribute can be true, false, or null. If the value is null, this means that the mergeability hasn't been computed yet, and a background job was started to compute it. Give the job a few moments to complete, and then submit the request again. When the job is complete, the response will include a non-null value for the mergeable attribute.\"\n\nThis casting currently treats \"null\" as \"can not merge\", which cascades down to other plugins. Should the returned type be expanded?\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/274",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/274/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/274/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/274/events",
"html_url": "https://github.com/hub4j/github-api/issues/274",
"id": 150572526,
"node_id": "MDU6SXNzdWUxNTA1NzI1MjY=",
"number": 274,
"title": "Webhook with content type \"application/json\"",
"user": {
"login": "mlabouardy",
"id": 10320205,
"node_id": "MDQ6VXNlcjEwMzIwMjA1",
"avatar_url": "https://avatars3.githubusercontent.com/u/10320205?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mlabouardy",
"html_url": "https://github.com/mlabouardy",
"followers_url": "https://api.github.com/users/mlabouardy/followers",
"following_url": "https://api.github.com/users/mlabouardy/following{/other_user}",
"gists_url": "https://api.github.com/users/mlabouardy/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mlabouardy/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mlabouardy/subscriptions",
"organizations_url": "https://api.github.com/users/mlabouardy/orgs",
"repos_url": "https://api.github.com/users/mlabouardy/repos",
"events_url": "https://api.github.com/users/mlabouardy/events{/privacy}",
"received_events_url": "https://api.github.com/users/mlabouardy/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-04-23T16:36:02Z",
"updated_at": "2016-06-04T03:34:32Z",
"closed_at": "2016-06-04T03:34:32Z",
"author_association": "NONE",
"body": "How can I create a webhook with content type \"application/json\" ?\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/273",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/273/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/273/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/273/events",
"html_url": "https://github.com/hub4j/github-api/issues/273",
"id": 149306560,
"node_id": "MDU6SXNzdWUxNDkzMDY1NjA=",
"number": 273,
"title": "Disable rate_limit check on GitHub Enterprise completely",
"user": {
"login": "djdefi",
"id": 3662109,
"node_id": "MDQ6VXNlcjM2NjIxMDk=",
"avatar_url": "https://avatars3.githubusercontent.com/u/3662109?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/djdefi",
"html_url": "https://github.com/djdefi",
"followers_url": "https://api.github.com/users/djdefi/followers",
"following_url": "https://api.github.com/users/djdefi/following{/other_user}",
"gists_url": "https://api.github.com/users/djdefi/gists{/gist_id}",
"starred_url": "https://api.github.com/users/djdefi/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/djdefi/subscriptions",
"organizations_url": "https://api.github.com/users/djdefi/orgs",
"repos_url": "https://api.github.com/users/djdefi/repos",
"events_url": "https://api.github.com/users/djdefi/events{/privacy}",
"received_events_url": "https://api.github.com/users/djdefi/received_events",
"type": "User",
"site_admin": true
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 8,
"created_at": "2016-04-19T00:06:06Z",
"updated_at": "2017-07-18T19:35:31Z",
"closed_at": "2016-08-06T04:12:56Z",
"author_association": "NONE",
"body": " GitHub Enterprise prior to 2.10 does not have rate limiting, requests to `https://hostname/api/v3/rate_limit` will return a 404 Not Found status code. in 2.10+ rate limiting can be enabled, but is disabled by default.\r\n\r\n~~Based on the change in #78 there is a check for `rate_limit`, and then the rate limit is set to an arbitrary high number. On very busy systems this results in tens of thousands of requests per hour to the GitHub Enterprise appliance. Although returning a 404 is a relatively simple operation, there are other things such as logging that are impacted by the volume of requests.~~\r\n\r\n~~A better method would be to look for **/api/v3/** within the configured API URL, and then simply skip the rate limit check altogether. **/api/v3/** is unique to GitHub Enterprise, so this will not have any impact on the GitHub.com rate_limit endpoint of https://api.github.com/rate_limit~~\r\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/272",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/272/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/272/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/272/events",
"html_url": "https://github.com/hub4j/github-api/pull/272",
"id": 148253949,
"node_id": "MDExOlB1bGxSZXF1ZXN0NjY0Mjk4Mjg=",
"number": 272,
"title": "Added support for the extended stargazers API in Github V3 API",
"user": {
"login": "noctarius",
"id": 1142801,
"node_id": "MDQ6VXNlcjExNDI4MDE=",
"avatar_url": "https://avatars3.githubusercontent.com/u/1142801?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/noctarius",
"html_url": "https://github.com/noctarius",
"followers_url": "https://api.github.com/users/noctarius/followers",
"following_url": "https://api.github.com/users/noctarius/following{/other_user}",
"gists_url": "https://api.github.com/users/noctarius/gists{/gist_id}",
"starred_url": "https://api.github.com/users/noctarius/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/noctarius/subscriptions",
"organizations_url": "https://api.github.com/users/noctarius/orgs",
"repos_url": "https://api.github.com/users/noctarius/repos",
"events_url": "https://api.github.com/users/noctarius/events{/privacy}",
"received_events_url": "https://api.github.com/users/noctarius/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2016-04-14T05:10:20Z",
"updated_at": "2016-06-03T05:04:24Z",
"closed_at": "2016-06-03T05:04:24Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/272",
"html_url": "https://github.com/hub4j/github-api/pull/272",
"diff_url": "https://github.com/hub4j/github-api/pull/272.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/272.patch"
},
"body": "Github has added starred_at date to stargazers when stargazers are requested with a special (new) version on the REST API. Added support for the version and a type representing the additional information.\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/271",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/271/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/271/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/271/events",
"html_url": "https://github.com/hub4j/github-api/issues/271",
"id": 147374094,
"node_id": "MDU6SXNzdWUxNDczNzQwOTQ=",
"number": 271,
"title": "GitHub.getRateLimit hangs inside SocketInputStream.socketRead0",
"user": {
"login": "kiselev-dv",
"id": 674665,
"node_id": "MDQ6VXNlcjY3NDY2NQ==",
"avatar_url": "https://avatars0.githubusercontent.com/u/674665?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/kiselev-dv",
"html_url": "https://github.com/kiselev-dv",
"followers_url": "https://api.github.com/users/kiselev-dv/followers",
"following_url": "https://api.github.com/users/kiselev-dv/following{/other_user}",
"gists_url": "https://api.github.com/users/kiselev-dv/gists{/gist_id}",
"starred_url": "https://api.github.com/users/kiselev-dv/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/kiselev-dv/subscriptions",
"organizations_url": "https://api.github.com/users/kiselev-dv/orgs",
"repos_url": "https://api.github.com/users/kiselev-dv/repos",
"events_url": "https://api.github.com/users/kiselev-dv/events{/privacy}",
"received_events_url": "https://api.github.com/users/kiselev-dv/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-04-11T09:50:02Z",
"updated_at": "2016-06-03T05:08:19Z",
"closed_at": "2016-06-03T05:08:19Z",
"author_association": "NONE",
"body": "We've run into an issue when GitHub.getRateLimit hangs the thread.\nHere is the thread stack trace:\n\n```\n\"jenkins.util.Timer [#4]\" Id=48 Group=main RUNNABLE (in native)\n at java.net.SocketInputStream.socketRead0(Native Method)\n at java.net.SocketInputStream.read(SocketInputStream.java:152)\n at java.net.SocketInputStream.read(SocketInputStream.java:122)\n at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)\n at sun.security.ssl.InputRecord.read(InputRecord.java:480)\n at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:946)\n - locked java.lang.Object@4be77f76\n at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:903)\n at sun.security.ssl.AppInputStream.read(AppInputStream.java:102)\n - locked sun.security.ssl.AppInputStream@5e6fb401\n at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)\n at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)\n at java.io.BufferedInputStream.read(BufferedInputStream.java:334)\n - locked java.io.BufferedInputStream@7792de16\n at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:690)\n at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)\n at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1325)\n - locked sun.net.www.protocol.https.DelegateHttpsURLConnection@6db28b13\n at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)\n at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)\n at org.kohsuke.github.Requester.parse(Requester.java:454)\n at org.kohsuke.github.Requester._to(Requester.java:227)\n at org.kohsuke.github.Requester.to(Requester.java:194)\n at org.kohsuke.github.GitHub.getRateLimit(GitHub.java:245)\n at org.jenkinsci.plugins.ghprb.GhprbRepository.initGhRepository(GhprbRepository.java:66)\n at org.jenkinsci.plugins.ghprb.GhprbRepository.check(GhprbRepository.java:88)\n at org.jenkinsci.plugins.ghprb.Ghprb.run(Ghprb.java:119)\n at org.jenkinsci.plugins.ghprb.GhprbTrigger.run(GhprbTrigger.java:219)\n at hudson.triggers.Trigger.checkTriggers(Trigger.java:272)\n at hudson.triggers.Trigger$Cron.doRun(Trigger.java:221)\n at hudson.triggers.SafeTimerTask.run(SafeTimerTask.java:50)\n at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)\n at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)\n at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)\n at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\n at java.lang.Thread.run(Thread.java:745)\n\n Number of locked synchronizers = 1\n - java.util.concurrent.ThreadPoolExecutor$Worker@6b1824c6\n```\n\nThere is a possibility that https://github.com/kohsuke/github-api/blob/master/src/main/java/org/kohsuke/github/Requester.java#L486 will never return an aswer.\n\nI think, `uc.setTimeout(60 * 1000);` here https://github.com/kohsuke/github-api/blob/master/src/main/java/org/kohsuke/github/Requester.java#L453 should fix the problem.\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/270",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/270/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/270/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/270/events",
"html_url": "https://github.com/hub4j/github-api/pull/270",
"id": 145719545,
"node_id": "MDExOlB1bGxSZXF1ZXN0NjUxNjQ4ODY=",
"number": 270,
"title": "[#269] Add reopen method on GHMilestone",
"user": {
"login": "szpak",
"id": 148013,
"node_id": "MDQ6VXNlcjE0ODAxMw==",
"avatar_url": "https://avatars1.githubusercontent.com/u/148013?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/szpak",
"html_url": "https://github.com/szpak",
"followers_url": "https://api.github.com/users/szpak/followers",
"following_url": "https://api.github.com/users/szpak/following{/other_user}",
"gists_url": "https://api.github.com/users/szpak/gists{/gist_id}",
"starred_url": "https://api.github.com/users/szpak/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/szpak/subscriptions",
"organizations_url": "https://api.github.com/users/szpak/orgs",
"repos_url": "https://api.github.com/users/szpak/repos",
"events_url": "https://api.github.com/users/szpak/events{/privacy}",
"received_events_url": "https://api.github.com/users/szpak/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-04-04T15:31:55Z",
"updated_at": "2016-04-13T23:15:39Z",
"closed_at": "2016-04-13T23:15:39Z",
"author_association": "CONTRIBUTOR",
"pull_request": {
"url": "https://api.github.com/repos/hub4j/github-api/pulls/270",
"html_url": "https://github.com/hub4j/github-api/pull/270",
"diff_url": "https://github.com/hub4j/github-api/pull/270.diff",
"patch_url": "https://github.com/hub4j/github-api/pull/270.patch"
},
"body": "Fixes #269.\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/269",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/269/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/269/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/269/events",
"html_url": "https://github.com/hub4j/github-api/issues/269",
"id": 145718053,
"node_id": "MDU6SXNzdWUxNDU3MTgwNTM=",
"number": 269,
"title": "(re)open method on GHMilestone",
"user": {
"login": "szpak",
"id": 148013,
"node_id": "MDQ6VXNlcjE0ODAxMw==",
"avatar_url": "https://avatars1.githubusercontent.com/u/148013?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/szpak",
"html_url": "https://github.com/szpak",
"followers_url": "https://api.github.com/users/szpak/followers",
"following_url": "https://api.github.com/users/szpak/following{/other_user}",
"gists_url": "https://api.github.com/users/szpak/gists{/gist_id}",
"starred_url": "https://api.github.com/users/szpak/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/szpak/subscriptions",
"organizations_url": "https://api.github.com/users/szpak/orgs",
"repos_url": "https://api.github.com/users/szpak/repos",
"events_url": "https://api.github.com/users/szpak/events{/privacy}",
"received_events_url": "https://api.github.com/users/szpak/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2016-04-04T15:27:13Z",
"updated_at": "2016-04-13T23:15:39Z",
"closed_at": "2016-04-13T23:15:39Z",
"author_association": "CONTRIBUTOR",
"body": "In some cases (e.g. restoring state for functional tests with sanboxed GitHub project) it could be needed to reopen already closed milestone. Unfortunately currently there is only a `close()` method on `GHMilestone` and as a workaround a private method `edit()` has to be used.\n"
},
{
"url": "https://api.github.com/repos/hub4j/github-api/issues/268",
"repository_url": "https://api.github.com/repos/hub4j/github-api",
"labels_url": "https://api.github.com/repos/hub4j/github-api/issues/268/labels{/name}",
"comments_url": "https://api.github.com/repos/hub4j/github-api/issues/268/comments",
"events_url": "https://api.github.com/repos/hub4j/github-api/issues/268/events",
"html_url": "https://github.com/hub4j/github-api/issues/268",
"id": 145666091,
"node_id": "MDU6SXNzdWUxNDU2NjYwOTE=",
"number": 268,
"title": "More meaning toString implementations",
"user": {
"login": "szpak",
"id": 148013,
"node_id": "MDQ6VXNlcjE0ODAxMw==",
"avatar_url": "https://avatars1.githubusercontent.com/u/148013?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/szpak",
"html_url": "https://github.com/szpak",
"followers_url": "https://api.github.com/users/szpak/followers",
"following_url": "https://api.github.com/users/szpak/following{/other_user}",
"gists_url": "https://api.github.com/users/szpak/gists{/gist_id}",
"starred_url": "https://api.github.com/users/szpak/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/szpak/subscriptions",
"organizations_url": "https://api.github.com/users/szpak/orgs",
"repos_url": "https://api.github.com/users/szpak/repos",
"events_url": "https://api.github.com/users/szpak/events{/privacy}",
"received_events_url": "https://api.github.com/users/szpak/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "closed",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 1,
"created_at": "2016-04-04T12:11:11Z",
"updated_at": "2016-06-03T05:38:32Z",
"closed_at": "2016-06-03T05:38:32Z",
"author_association": "CONTRIBUTOR",
"body": "Currently many of the GH\\* objects don't have meaninful `toString()` implementation. As details seem to be already initialized in most cases it would be useful to see something like:\n\n```\nGHMIlestone: title=0.1.3, state=CLOSED, number=34\n```\n\ninstead of\n\n```\norg.kohsuke.github.GHMilestone@72d6b3ba\n```\n"
}
] | {
"pile_set_name": "Github"
} |
form=词
tags=
绿绮琴中心事,
齐纨扇上时光。
五陵年少浑薄倖,
轻如曲水飘香。
夜夜魂消梦峡,
年年泪尽啼湘。
归雁行边远字,
惊鸾舞处离肠。
蕙楼多少铅华在,
从来错倚红妆。
可羡邻姬十五,
金钗早嫁王昌。
| {
"pile_set_name": "Github"
} |
version https://git-lfs.github.com/spec/v1
oid sha256:7b14e3183f9e75876f0c91cedb19f810b5bcb9ad90122909b1c97fb890fe69e8
size 15955
| {
"pile_set_name": "Github"
} |
{
"@metadata": {
"authors": [
"Hromoslav",
"KuboF",
"Kusavica",
"Luky001",
"Sudo77(new)",
"Vlad5250"
]
},
"config-desc": "Inštalátor pre MediaWiki",
"config-title": "Inštalácia MediaWiki $1",
"config-information": "Informácie",
"config-localsettings-key": "Aktualizačný kľúč:",
"config-localsettings-badkey": "Zadaný aktualizačný kľúč je nesprávny.",
"config-your-language": "Váš jazyk:",
"config-your-language-help": "Vyberte jazyk, ktorý chcete použiť počas inštalácie.",
"config-wiki-language": "Wiki jazyk:",
"config-wiki-language-help": "Vyberte jazyk, v ktorom bude wiki napísaná.",
"config-back": "← Späť",
"config-continue": "Pokračovať →",
"config-page-language": "Jazyk",
"config-page-welcome": "Vitajte na MediaWiki!",
"config-page-dbconnect": "Pripojiť sa k databáze",
"config-page-upgrade": "Aktualizovať existujúcu inštaláciu",
"config-page-dbsettings": "Nastavenie databázy",
"config-page-name": "Názov",
"config-page-options": "Možnosti",
"config-page-install": "Inštalovať",
"config-page-complete": "Dokončené",
"config-page-restart": "Reštartovať inštaláciu",
"config-page-releasenotes": "Poznámky k vydaniu",
"config-page-copying": "Licencia",
"config-page-upgradedoc": "Aktualizácia",
"config-page-existingwiki": "Existujúca wiki",
"config-help-restart": "Chcete vymazať všetky uložené dáta, ktoré ste zadali a reštartovať proces inštalácie?",
"config-restart": "Áno, reštartovať",
"config-sidebar-relnotes": "Poznámky k vydaniu",
"config-sidebar-license": "Licencia",
"config-sidebar-upgrade": "Aktualizácia",
"config-env-good": "Prostredie bolo skontrolované.\nMôžete nainštalovať MediaWiki.",
"config-env-bad": "Prostredie bolo skontrolované.\nNemôžete nainštalovať MediaWiki.",
"config-env-php": "PHP $1 je nainštalované.",
"config-db-type": "Typ databázy:",
"config-db-host": "Databázový server:",
"config-db-wiki-settings": "Identifikácia tejto wiki",
"config-db-name": "Názov databázy (bez spojovníkov):",
"config-db-install-account": "Používateľský účet pre inštaláciu",
"config-db-username": "Databázové používateľské meno:",
"config-db-password": "Databázové heslo:",
"config-missing-db-name": "Musíte zadať hodnotu pre \"{{int:config-db-name}}\".",
"config-missing-db-host": "Musíte zadať hodnotu pre \"{{int:config-db-host}}\".",
"config-site-name": "Názov wiki:",
"config-site-name-blank": "Zadajte názov stránky.",
"config-ns-generic": "Projekt",
"config-admin-box": "Účet správcu",
"config-admin-name": "Vaše používateľské meno:",
"config-admin-password": "Heslo:",
"config-admin-password-confirm": "Zopakujte heslo:",
"config-admin-name-blank": "Zadajte používateľské meno správcu.",
"config-admin-name-invalid": "Zadané používateľské meno \"<nowiki>$1</nowiki>\" je neplatné. \nZadajte iné meno.",
"config-admin-password-blank": "Zadajte heslo ku správcovskému účtu.",
"config-admin-password-mismatch": "Zadané heslá sa nezhodujú.",
"config-admin-email": "Emailová adresa:",
"config-admin-error-bademail": "Zadali ste neplatnú emailovú adresu.",
"config-optional-continue": "Opýtaj sa ma ďalšie otázky.",
"config-optional-skip": "Už ma to nudí, proste nainštaluj wiki.",
"config-profile-wiki": "Otvorená wiki",
"config-profile-private": "Súkromná wiki",
"config-license-pd": "Voľné dielo",
"config-email-settings": "Nastavenia e-mailu",
"config-extensions": "Rozšírenia",
"config-skins": "Témy vzhľadu",
"config-install-step-done": "hotovo",
"config-install-step-failed": "zlyhalo",
"config-install-extensions": "Inštalujú sa rozšírenia",
"config-install-user-alreadyexists": "Používateľ \"$1\" už existuje",
"config-install-tables-failed": "<strong>Chyba:</strong> Vytvorenie tabuľky zlyhalo s nasledujúcou chybou: $1",
"config-download-localsettings": "Stiahnuť <code>LocalSettings.php</code>",
"config-help": "nápoveda",
"config-nofile": "Súbor \"$1\" sa nenašiel. Bol zmazaný?",
"config-extension-link": "Vedeli ste, že vaša wiki podporuje [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Extensions rozšírenia]?\n\nRozšírenia môžete hľadať [https://www.mediawiki.org/wiki/Special:MyLanguage/Category:Extensions_by_category podľa kategórie].",
"mainpagetext": "'''Softvér MediaWiki bol úspešne nainštalovaný.'''",
"mainpagedocfooter": "Informácie ako používať wiki softvér nájdete v [https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Contents Používateľskej príručke].\n\n== Začíname ==\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Configuration_settings Zoznam konfiguračných nastavení]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:FAQ Časté otázky o MediaWiki]\n* [https://lists.wikimedia.org/mailman/listinfo/mediawiki-announce E-poštová konferencia oznámení o MediaWiki]\n* [https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation#Translation_resources Preklad MediaWiki do vášho jazyka]"
}
| {
"pile_set_name": "Github"
} |
<?php
class Fileref extends \Eloquent {
protected $table = 'file_ref';
protected $softDelete = true;
} | {
"pile_set_name": "Github"
} |
/******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2012 - 2014, 2018 - 2020 Intel Corporation. All rights reserved.
* Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH
* Copyright(c) 2016 - 2017 Intel Deutschland GmbH
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full GNU General Public License is included in this distribution
* in the file called COPYING.
*
* Contact Information:
* Intel Linux Wireless <[email protected]>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2012 - 2014, 2018 - 2020 Intel Corporation. All rights reserved.
* Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH
* Copyright(c) 2016 - 2017 Intel Deutschland GmbH
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <net/mac80211.h>
#include "fw/notif-wait.h"
#include "iwl-trans.h"
#include "iwl-op-mode.h"
#include "fw/img.h"
#include "iwl-debug.h"
#include "iwl-drv.h"
#include "iwl-modparams.h"
#include "mvm.h"
#include "iwl-phy-db.h"
#include "iwl-eeprom-parse.h"
#include "iwl-csr.h"
#include "iwl-io.h"
#include "iwl-prph.h"
#include "rs.h"
#include "fw/api/scan.h"
#include "time-event.h"
#include "fw-api.h"
#include "fw/acpi.h"
#define DRV_DESCRIPTION "The new Intel(R) wireless AGN driver for Linux"
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR(DRV_AUTHOR);
MODULE_LICENSE("GPL");
static const struct iwl_op_mode_ops iwl_mvm_ops;
static const struct iwl_op_mode_ops iwl_mvm_ops_mq;
struct iwl_mvm_mod_params iwlmvm_mod_params = {
.power_scheme = IWL_POWER_SCHEME_BPS,
/* rest of fields are 0 by default */
};
module_param_named(init_dbg, iwlmvm_mod_params.init_dbg, bool, 0444);
MODULE_PARM_DESC(init_dbg,
"set to true to debug an ASSERT in INIT fw (default: false");
module_param_named(power_scheme, iwlmvm_mod_params.power_scheme, int, 0444);
MODULE_PARM_DESC(power_scheme,
"power management scheme: 1-active, 2-balanced, 3-low power, default: 2");
/*
* module init and exit functions
*/
static int __init iwl_mvm_init(void)
{
int ret;
ret = iwl_mvm_rate_control_register();
if (ret) {
pr_err("Unable to register rate control algorithm: %d\n", ret);
return ret;
}
ret = iwl_opmode_register("iwlmvm", &iwl_mvm_ops);
if (ret)
pr_err("Unable to register MVM op_mode: %d\n", ret);
return ret;
}
module_init(iwl_mvm_init);
static void __exit iwl_mvm_exit(void)
{
iwl_opmode_deregister("iwlmvm");
iwl_mvm_rate_control_unregister();
}
module_exit(iwl_mvm_exit);
static void iwl_mvm_nic_config(struct iwl_op_mode *op_mode)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
u8 radio_cfg_type, radio_cfg_step, radio_cfg_dash;
u32 reg_val = 0;
u32 phy_config = iwl_mvm_get_phy_config(mvm);
radio_cfg_type = (phy_config & FW_PHY_CFG_RADIO_TYPE) >>
FW_PHY_CFG_RADIO_TYPE_POS;
radio_cfg_step = (phy_config & FW_PHY_CFG_RADIO_STEP) >>
FW_PHY_CFG_RADIO_STEP_POS;
radio_cfg_dash = (phy_config & FW_PHY_CFG_RADIO_DASH) >>
FW_PHY_CFG_RADIO_DASH_POS;
/* SKU control */
reg_val |= CSR_HW_REV_STEP(mvm->trans->hw_rev) <<
CSR_HW_IF_CONFIG_REG_POS_MAC_STEP;
reg_val |= CSR_HW_REV_DASH(mvm->trans->hw_rev) <<
CSR_HW_IF_CONFIG_REG_POS_MAC_DASH;
/* radio configuration */
reg_val |= radio_cfg_type << CSR_HW_IF_CONFIG_REG_POS_PHY_TYPE;
reg_val |= radio_cfg_step << CSR_HW_IF_CONFIG_REG_POS_PHY_STEP;
reg_val |= radio_cfg_dash << CSR_HW_IF_CONFIG_REG_POS_PHY_DASH;
WARN_ON((radio_cfg_type << CSR_HW_IF_CONFIG_REG_POS_PHY_TYPE) &
~CSR_HW_IF_CONFIG_REG_MSK_PHY_TYPE);
/*
* TODO: Bits 7-8 of CSR in 8000 HW family and higher set the ADC
* sampling, and shouldn't be set to any non-zero value.
* The same is supposed to be true of the other HW, but unsetting
* them (such as the 7260) causes automatic tests to fail on seemingly
* unrelated errors. Need to further investigate this, but for now
* we'll separate cases.
*/
if (mvm->trans->trans_cfg->device_family < IWL_DEVICE_FAMILY_8000)
reg_val |= CSR_HW_IF_CONFIG_REG_BIT_RADIO_SI;
if (iwl_fw_dbg_is_d3_debug_enabled(&mvm->fwrt))
reg_val |= CSR_HW_IF_CONFIG_REG_D3_DEBUG;
iwl_trans_set_bits_mask(mvm->trans, CSR_HW_IF_CONFIG_REG,
CSR_HW_IF_CONFIG_REG_MSK_MAC_DASH |
CSR_HW_IF_CONFIG_REG_MSK_MAC_STEP |
CSR_HW_IF_CONFIG_REG_MSK_PHY_TYPE |
CSR_HW_IF_CONFIG_REG_MSK_PHY_STEP |
CSR_HW_IF_CONFIG_REG_MSK_PHY_DASH |
CSR_HW_IF_CONFIG_REG_BIT_RADIO_SI |
CSR_HW_IF_CONFIG_REG_BIT_MAC_SI |
CSR_HW_IF_CONFIG_REG_D3_DEBUG,
reg_val);
IWL_DEBUG_INFO(mvm, "Radio type=0x%x-0x%x-0x%x\n", radio_cfg_type,
radio_cfg_step, radio_cfg_dash);
/*
* W/A : NIC is stuck in a reset state after Early PCIe power off
* (PCIe power is lost before PERST# is asserted), causing ME FW
* to lose ownership and not being able to obtain it back.
*/
if (!mvm->trans->cfg->apmg_not_supported)
iwl_set_bits_mask_prph(mvm->trans, APMG_PS_CTRL_REG,
APMG_PS_CTRL_EARLY_PWR_OFF_RESET_DIS,
~APMG_PS_CTRL_EARLY_PWR_OFF_RESET_DIS);
}
/**
* enum iwl_rx_handler_context context for Rx handler
* @RX_HANDLER_SYNC : this means that it will be called in the Rx path
* which can't acquire mvm->mutex.
* @RX_HANDLER_ASYNC_LOCKED : If the handler needs to hold mvm->mutex
* (and only in this case!), it should be set as ASYNC. In that case,
* it will be called from a worker with mvm->mutex held.
* @RX_HANDLER_ASYNC_UNLOCKED : in case the handler needs to lock the
* mutex itself, it will be called from a worker without mvm->mutex held.
*/
enum iwl_rx_handler_context {
RX_HANDLER_SYNC,
RX_HANDLER_ASYNC_LOCKED,
RX_HANDLER_ASYNC_UNLOCKED,
};
/**
* struct iwl_rx_handlers handler for FW notification
* @cmd_id: command id
* @context: see &iwl_rx_handler_context
* @fn: the function is called when notification is received
*/
struct iwl_rx_handlers {
u16 cmd_id;
enum iwl_rx_handler_context context;
void (*fn)(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb);
};
#define RX_HANDLER(_cmd_id, _fn, _context) \
{ .cmd_id = _cmd_id, .fn = _fn, .context = _context }
#define RX_HANDLER_GRP(_grp, _cmd, _fn, _context) \
{ .cmd_id = WIDE_ID(_grp, _cmd), .fn = _fn, .context = _context }
/*
* Handlers for fw notifications
* Convention: RX_HANDLER(CMD_NAME, iwl_mvm_rx_CMD_NAME
* This list should be in order of frequency for performance purposes.
*
* The handler can be one from three contexts, see &iwl_rx_handler_context
*/
static const struct iwl_rx_handlers iwl_mvm_rx_handlers[] = {
RX_HANDLER(TX_CMD, iwl_mvm_rx_tx_cmd, RX_HANDLER_SYNC),
RX_HANDLER(BA_NOTIF, iwl_mvm_rx_ba_notif, RX_HANDLER_SYNC),
RX_HANDLER_GRP(DATA_PATH_GROUP, TLC_MNG_UPDATE_NOTIF,
iwl_mvm_tlc_update_notif, RX_HANDLER_SYNC),
RX_HANDLER(BT_PROFILE_NOTIFICATION, iwl_mvm_rx_bt_coex_notif,
RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER(BEACON_NOTIFICATION, iwl_mvm_rx_beacon_notif,
RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER(STATISTICS_NOTIFICATION, iwl_mvm_rx_statistics,
RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER(BA_WINDOW_STATUS_NOTIFICATION_ID,
iwl_mvm_window_status_notif, RX_HANDLER_SYNC),
RX_HANDLER(TIME_EVENT_NOTIFICATION, iwl_mvm_rx_time_event_notif,
RX_HANDLER_SYNC),
RX_HANDLER_GRP(MAC_CONF_GROUP, SESSION_PROTECTION_NOTIF,
iwl_mvm_rx_session_protect_notif, RX_HANDLER_SYNC),
RX_HANDLER(MCC_CHUB_UPDATE_CMD, iwl_mvm_rx_chub_update_mcc,
RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER(EOSP_NOTIFICATION, iwl_mvm_rx_eosp_notif, RX_HANDLER_SYNC),
RX_HANDLER(SCAN_ITERATION_COMPLETE,
iwl_mvm_rx_lmac_scan_iter_complete_notif, RX_HANDLER_SYNC),
RX_HANDLER(SCAN_OFFLOAD_COMPLETE,
iwl_mvm_rx_lmac_scan_complete_notif,
RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER(MATCH_FOUND_NOTIFICATION, iwl_mvm_rx_scan_match_found,
RX_HANDLER_SYNC),
RX_HANDLER(SCAN_COMPLETE_UMAC, iwl_mvm_rx_umac_scan_complete_notif,
RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER(SCAN_ITERATION_COMPLETE_UMAC,
iwl_mvm_rx_umac_scan_iter_complete_notif, RX_HANDLER_SYNC),
RX_HANDLER(CARD_STATE_NOTIFICATION, iwl_mvm_rx_card_state_notif,
RX_HANDLER_SYNC),
RX_HANDLER(MISSED_BEACONS_NOTIFICATION, iwl_mvm_rx_missed_beacons_notif,
RX_HANDLER_SYNC),
RX_HANDLER(REPLY_ERROR, iwl_mvm_rx_fw_error, RX_HANDLER_SYNC),
RX_HANDLER(PSM_UAPSD_AP_MISBEHAVING_NOTIFICATION,
iwl_mvm_power_uapsd_misbehaving_ap_notif, RX_HANDLER_SYNC),
RX_HANDLER(DTS_MEASUREMENT_NOTIFICATION, iwl_mvm_temp_notif,
RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER_GRP(PHY_OPS_GROUP, DTS_MEASUREMENT_NOTIF_WIDE,
iwl_mvm_temp_notif, RX_HANDLER_ASYNC_UNLOCKED),
RX_HANDLER_GRP(PHY_OPS_GROUP, CT_KILL_NOTIFICATION,
iwl_mvm_ct_kill_notif, RX_HANDLER_SYNC),
RX_HANDLER(TDLS_CHANNEL_SWITCH_NOTIFICATION, iwl_mvm_rx_tdls_notif,
RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER(MFUART_LOAD_NOTIFICATION, iwl_mvm_rx_mfuart_notif,
RX_HANDLER_SYNC),
RX_HANDLER_GRP(LOCATION_GROUP, TOF_RESPONDER_STATS,
iwl_mvm_ftm_responder_stats, RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER_GRP(LOCATION_GROUP, TOF_RANGE_RESPONSE_NOTIF,
iwl_mvm_ftm_range_resp, RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER_GRP(LOCATION_GROUP, TOF_LC_NOTIF,
iwl_mvm_ftm_lc_notif, RX_HANDLER_ASYNC_LOCKED),
RX_HANDLER_GRP(DEBUG_GROUP, MFU_ASSERT_DUMP_NTF,
iwl_mvm_mfu_assert_dump_notif, RX_HANDLER_SYNC),
RX_HANDLER_GRP(PROT_OFFLOAD_GROUP, STORED_BEACON_NTF,
iwl_mvm_rx_stored_beacon_notif, RX_HANDLER_SYNC),
RX_HANDLER_GRP(DATA_PATH_GROUP, MU_GROUP_MGMT_NOTIF,
iwl_mvm_mu_mimo_grp_notif, RX_HANDLER_SYNC),
RX_HANDLER_GRP(DATA_PATH_GROUP, STA_PM_NOTIF,
iwl_mvm_sta_pm_notif, RX_HANDLER_SYNC),
};
#undef RX_HANDLER
#undef RX_HANDLER_GRP
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_legacy_names[] = {
HCMD_NAME(MVM_ALIVE),
HCMD_NAME(REPLY_ERROR),
HCMD_NAME(ECHO_CMD),
HCMD_NAME(INIT_COMPLETE_NOTIF),
HCMD_NAME(PHY_CONTEXT_CMD),
HCMD_NAME(DBG_CFG),
HCMD_NAME(SCAN_CFG_CMD),
HCMD_NAME(SCAN_REQ_UMAC),
HCMD_NAME(SCAN_ABORT_UMAC),
HCMD_NAME(SCAN_COMPLETE_UMAC),
HCMD_NAME(BA_WINDOW_STATUS_NOTIFICATION_ID),
HCMD_NAME(ADD_STA_KEY),
HCMD_NAME(ADD_STA),
HCMD_NAME(REMOVE_STA),
HCMD_NAME(FW_GET_ITEM_CMD),
HCMD_NAME(TX_CMD),
HCMD_NAME(SCD_QUEUE_CFG),
HCMD_NAME(TXPATH_FLUSH),
HCMD_NAME(MGMT_MCAST_KEY),
HCMD_NAME(WEP_KEY),
HCMD_NAME(SHARED_MEM_CFG),
HCMD_NAME(TDLS_CHANNEL_SWITCH_CMD),
HCMD_NAME(MAC_CONTEXT_CMD),
HCMD_NAME(TIME_EVENT_CMD),
HCMD_NAME(TIME_EVENT_NOTIFICATION),
HCMD_NAME(BINDING_CONTEXT_CMD),
HCMD_NAME(TIME_QUOTA_CMD),
HCMD_NAME(NON_QOS_TX_COUNTER_CMD),
HCMD_NAME(LEDS_CMD),
HCMD_NAME(LQ_CMD),
HCMD_NAME(FW_PAGING_BLOCK_CMD),
HCMD_NAME(SCAN_OFFLOAD_REQUEST_CMD),
HCMD_NAME(SCAN_OFFLOAD_ABORT_CMD),
HCMD_NAME(HOT_SPOT_CMD),
HCMD_NAME(SCAN_OFFLOAD_PROFILES_QUERY_CMD),
HCMD_NAME(BT_COEX_UPDATE_REDUCED_TXP),
HCMD_NAME(BT_COEX_CI),
HCMD_NAME(PHY_CONFIGURATION_CMD),
HCMD_NAME(CALIB_RES_NOTIF_PHY_DB),
HCMD_NAME(PHY_DB_CMD),
HCMD_NAME(SCAN_OFFLOAD_COMPLETE),
HCMD_NAME(SCAN_OFFLOAD_UPDATE_PROFILES_CMD),
HCMD_NAME(POWER_TABLE_CMD),
HCMD_NAME(PSM_UAPSD_AP_MISBEHAVING_NOTIFICATION),
HCMD_NAME(REPLY_THERMAL_MNG_BACKOFF),
HCMD_NAME(DC2DC_CONFIG_CMD),
HCMD_NAME(NVM_ACCESS_CMD),
HCMD_NAME(BEACON_NOTIFICATION),
HCMD_NAME(BEACON_TEMPLATE_CMD),
HCMD_NAME(TX_ANT_CONFIGURATION_CMD),
HCMD_NAME(BT_CONFIG),
HCMD_NAME(STATISTICS_CMD),
HCMD_NAME(STATISTICS_NOTIFICATION),
HCMD_NAME(EOSP_NOTIFICATION),
HCMD_NAME(REDUCE_TX_POWER_CMD),
HCMD_NAME(CARD_STATE_NOTIFICATION),
HCMD_NAME(MISSED_BEACONS_NOTIFICATION),
HCMD_NAME(TDLS_CONFIG_CMD),
HCMD_NAME(MAC_PM_POWER_TABLE),
HCMD_NAME(TDLS_CHANNEL_SWITCH_NOTIFICATION),
HCMD_NAME(MFUART_LOAD_NOTIFICATION),
HCMD_NAME(RSS_CONFIG_CMD),
HCMD_NAME(SCAN_ITERATION_COMPLETE_UMAC),
HCMD_NAME(REPLY_RX_PHY_CMD),
HCMD_NAME(REPLY_RX_MPDU_CMD),
HCMD_NAME(BAR_FRAME_RELEASE),
HCMD_NAME(FRAME_RELEASE),
HCMD_NAME(BA_NOTIF),
HCMD_NAME(MCC_UPDATE_CMD),
HCMD_NAME(MCC_CHUB_UPDATE_CMD),
HCMD_NAME(MARKER_CMD),
HCMD_NAME(BT_PROFILE_NOTIFICATION),
HCMD_NAME(BCAST_FILTER_CMD),
HCMD_NAME(MCAST_FILTER_CMD),
HCMD_NAME(REPLY_SF_CFG_CMD),
HCMD_NAME(REPLY_BEACON_FILTERING_CMD),
HCMD_NAME(D3_CONFIG_CMD),
HCMD_NAME(PROT_OFFLOAD_CONFIG_CMD),
HCMD_NAME(OFFLOADS_QUERY_CMD),
HCMD_NAME(REMOTE_WAKE_CONFIG_CMD),
HCMD_NAME(MATCH_FOUND_NOTIFICATION),
HCMD_NAME(DTS_MEASUREMENT_NOTIFICATION),
HCMD_NAME(WOWLAN_PATTERNS),
HCMD_NAME(WOWLAN_CONFIGURATION),
HCMD_NAME(WOWLAN_TSC_RSC_PARAM),
HCMD_NAME(WOWLAN_TKIP_PARAM),
HCMD_NAME(WOWLAN_KEK_KCK_MATERIAL),
HCMD_NAME(WOWLAN_GET_STATUSES),
HCMD_NAME(SCAN_ITERATION_COMPLETE),
HCMD_NAME(D0I3_END_CMD),
HCMD_NAME(LTR_CONFIG),
HCMD_NAME(LDBG_CONFIG_CMD),
};
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_system_names[] = {
HCMD_NAME(SHARED_MEM_CFG_CMD),
HCMD_NAME(INIT_EXTENDED_CFG_CMD),
HCMD_NAME(FW_ERROR_RECOVERY_CMD),
};
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_mac_conf_names[] = {
HCMD_NAME(CHANNEL_SWITCH_TIME_EVENT_CMD),
HCMD_NAME(SESSION_PROTECTION_CMD),
HCMD_NAME(SESSION_PROTECTION_NOTIF),
HCMD_NAME(CHANNEL_SWITCH_NOA_NOTIF),
};
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_phy_names[] = {
HCMD_NAME(CMD_DTS_MEASUREMENT_TRIGGER_WIDE),
HCMD_NAME(CTDP_CONFIG_CMD),
HCMD_NAME(TEMP_REPORTING_THRESHOLDS_CMD),
HCMD_NAME(GEO_TX_POWER_LIMIT),
HCMD_NAME(CT_KILL_NOTIFICATION),
HCMD_NAME(DTS_MEASUREMENT_NOTIF_WIDE),
};
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_data_path_names[] = {
HCMD_NAME(DQA_ENABLE_CMD),
HCMD_NAME(UPDATE_MU_GROUPS_CMD),
HCMD_NAME(TRIGGER_RX_QUEUES_NOTIF_CMD),
HCMD_NAME(STA_HE_CTXT_CMD),
HCMD_NAME(RFH_QUEUE_CONFIG_CMD),
HCMD_NAME(TLC_MNG_CONFIG_CMD),
HCMD_NAME(CHEST_COLLECTOR_FILTER_CONFIG_CMD),
HCMD_NAME(STA_PM_NOTIF),
HCMD_NAME(MU_GROUP_MGMT_NOTIF),
HCMD_NAME(RX_QUEUES_NOTIFICATION),
};
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_debug_names[] = {
HCMD_NAME(DBGC_SUSPEND_RESUME),
HCMD_NAME(BUFFER_ALLOCATION),
HCMD_NAME(MFU_ASSERT_DUMP_NTF),
};
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_location_names[] = {
HCMD_NAME(TOF_RANGE_REQ_CMD),
HCMD_NAME(TOF_CONFIG_CMD),
HCMD_NAME(TOF_RANGE_ABORT_CMD),
HCMD_NAME(TOF_RANGE_REQ_EXT_CMD),
HCMD_NAME(TOF_RESPONDER_CONFIG_CMD),
HCMD_NAME(TOF_RESPONDER_DYN_CONFIG_CMD),
HCMD_NAME(TOF_LC_NOTIF),
HCMD_NAME(TOF_RESPONDER_STATS),
HCMD_NAME(TOF_MCSI_DEBUG_NOTIF),
HCMD_NAME(TOF_RANGE_RESPONSE_NOTIF),
};
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_prot_offload_names[] = {
HCMD_NAME(STORED_BEACON_NTF),
};
/* Please keep this array *SORTED* by hex value.
* Access is done through binary search
*/
static const struct iwl_hcmd_names iwl_mvm_regulatory_and_nvm_names[] = {
HCMD_NAME(NVM_ACCESS_COMPLETE),
HCMD_NAME(NVM_GET_INFO),
HCMD_NAME(TAS_CONFIG),
};
static const struct iwl_hcmd_arr iwl_mvm_groups[] = {
[LEGACY_GROUP] = HCMD_ARR(iwl_mvm_legacy_names),
[LONG_GROUP] = HCMD_ARR(iwl_mvm_legacy_names),
[SYSTEM_GROUP] = HCMD_ARR(iwl_mvm_system_names),
[MAC_CONF_GROUP] = HCMD_ARR(iwl_mvm_mac_conf_names),
[PHY_OPS_GROUP] = HCMD_ARR(iwl_mvm_phy_names),
[DATA_PATH_GROUP] = HCMD_ARR(iwl_mvm_data_path_names),
[LOCATION_GROUP] = HCMD_ARR(iwl_mvm_location_names),
[PROT_OFFLOAD_GROUP] = HCMD_ARR(iwl_mvm_prot_offload_names),
[REGULATORY_AND_NVM_GROUP] =
HCMD_ARR(iwl_mvm_regulatory_and_nvm_names),
};
/* this forward declaration can avoid to export the function */
static void iwl_mvm_async_handlers_wk(struct work_struct *wk);
static u32 iwl_mvm_min_backoff(struct iwl_mvm *mvm)
{
const struct iwl_pwr_tx_backoff *backoff = mvm->cfg->pwr_tx_backoffs;
u64 dflt_pwr_limit;
if (!backoff)
return 0;
dflt_pwr_limit = iwl_acpi_get_pwr_limit(mvm->dev);
while (backoff->pwr) {
if (dflt_pwr_limit >= backoff->pwr)
return backoff->backoff;
backoff++;
}
return 0;
}
static void iwl_mvm_tx_unblock_dwork(struct work_struct *work)
{
struct iwl_mvm *mvm =
container_of(work, struct iwl_mvm, cs_tx_unblock_dwork.work);
struct ieee80211_vif *tx_blocked_vif;
struct iwl_mvm_vif *mvmvif;
mutex_lock(&mvm->mutex);
tx_blocked_vif =
rcu_dereference_protected(mvm->csa_tx_blocked_vif,
lockdep_is_held(&mvm->mutex));
if (!tx_blocked_vif)
goto unlock;
mvmvif = iwl_mvm_vif_from_mac80211(tx_blocked_vif);
iwl_mvm_modify_all_sta_disable_tx(mvm, mvmvif, false);
RCU_INIT_POINTER(mvm->csa_tx_blocked_vif, NULL);
unlock:
mutex_unlock(&mvm->mutex);
}
static int iwl_mvm_fwrt_dump_start(void *ctx)
{
struct iwl_mvm *mvm = ctx;
mutex_lock(&mvm->mutex);
return 0;
}
static void iwl_mvm_fwrt_dump_end(void *ctx)
{
struct iwl_mvm *mvm = ctx;
mutex_unlock(&mvm->mutex);
}
static bool iwl_mvm_fwrt_fw_running(void *ctx)
{
return iwl_mvm_firmware_running(ctx);
}
static int iwl_mvm_fwrt_send_hcmd(void *ctx, struct iwl_host_cmd *host_cmd)
{
struct iwl_mvm *mvm = (struct iwl_mvm *)ctx;
int ret;
mutex_lock(&mvm->mutex);
ret = iwl_mvm_send_cmd(mvm, host_cmd);
mutex_unlock(&mvm->mutex);
return ret;
}
static bool iwl_mvm_d3_debug_enable(void *ctx)
{
return IWL_MVM_D3_DEBUG;
}
static const struct iwl_fw_runtime_ops iwl_mvm_fwrt_ops = {
.dump_start = iwl_mvm_fwrt_dump_start,
.dump_end = iwl_mvm_fwrt_dump_end,
.fw_running = iwl_mvm_fwrt_fw_running,
.send_hcmd = iwl_mvm_fwrt_send_hcmd,
.d3_debug_enable = iwl_mvm_d3_debug_enable,
};
static struct iwl_op_mode *
iwl_op_mode_mvm_start(struct iwl_trans *trans, const struct iwl_cfg *cfg,
const struct iwl_fw *fw, struct dentry *dbgfs_dir)
{
struct ieee80211_hw *hw;
struct iwl_op_mode *op_mode;
struct iwl_mvm *mvm;
struct iwl_trans_config trans_cfg = {};
static const u8 no_reclaim_cmds[] = {
TX_CMD,
};
int err, scan_size;
u32 min_backoff;
enum iwl_amsdu_size rb_size_default;
/*
* We use IWL_MVM_STATION_COUNT to check the validity of the station
* index all over the driver - check that its value corresponds to the
* array size.
*/
BUILD_BUG_ON(ARRAY_SIZE(mvm->fw_id_to_mac_id) != IWL_MVM_STATION_COUNT);
/********************************
* 1. Allocating and configuring HW data
********************************/
hw = ieee80211_alloc_hw(sizeof(struct iwl_op_mode) +
sizeof(struct iwl_mvm),
&iwl_mvm_hw_ops);
if (!hw)
return NULL;
hw->max_rx_aggregation_subframes = IEEE80211_MAX_AMPDU_BUF;
if (cfg->max_tx_agg_size)
hw->max_tx_aggregation_subframes = cfg->max_tx_agg_size;
else
hw->max_tx_aggregation_subframes = IEEE80211_MAX_AMPDU_BUF;
op_mode = hw->priv;
mvm = IWL_OP_MODE_GET_MVM(op_mode);
mvm->dev = trans->dev;
mvm->trans = trans;
mvm->cfg = cfg;
mvm->fw = fw;
mvm->hw = hw;
iwl_fw_runtime_init(&mvm->fwrt, trans, fw, &iwl_mvm_fwrt_ops, mvm,
dbgfs_dir);
mvm->init_status = 0;
if (iwl_mvm_has_new_rx_api(mvm)) {
op_mode->ops = &iwl_mvm_ops_mq;
trans->rx_mpdu_cmd_hdr_size =
(trans->trans_cfg->device_family >=
IWL_DEVICE_FAMILY_AX210) ?
sizeof(struct iwl_rx_mpdu_desc) :
IWL_RX_DESC_SIZE_V1;
} else {
op_mode->ops = &iwl_mvm_ops;
trans->rx_mpdu_cmd_hdr_size =
sizeof(struct iwl_rx_mpdu_res_start);
if (WARN_ON(trans->num_rx_queues > 1))
goto out_free;
}
mvm->fw_restart = iwlwifi_mod_params.fw_restart ? -1 : 0;
mvm->aux_queue = IWL_MVM_DQA_AUX_QUEUE;
mvm->snif_queue = IWL_MVM_DQA_INJECT_MONITOR_QUEUE;
mvm->probe_queue = IWL_MVM_DQA_AP_PROBE_RESP_QUEUE;
mvm->p2p_dev_queue = IWL_MVM_DQA_P2P_DEVICE_QUEUE;
mvm->sf_state = SF_UNINIT;
if (iwl_mvm_has_unified_ucode(mvm))
iwl_fw_set_current_image(&mvm->fwrt, IWL_UCODE_REGULAR);
else
iwl_fw_set_current_image(&mvm->fwrt, IWL_UCODE_INIT);
mvm->drop_bcn_ap_mode = true;
mutex_init(&mvm->mutex);
spin_lock_init(&mvm->async_handlers_lock);
INIT_LIST_HEAD(&mvm->time_event_list);
INIT_LIST_HEAD(&mvm->aux_roc_te_list);
INIT_LIST_HEAD(&mvm->async_handlers_list);
spin_lock_init(&mvm->time_event_lock);
INIT_LIST_HEAD(&mvm->ftm_initiator.loc_list);
INIT_WORK(&mvm->async_handlers_wk, iwl_mvm_async_handlers_wk);
INIT_WORK(&mvm->roc_done_wk, iwl_mvm_roc_done_wk);
INIT_DELAYED_WORK(&mvm->tdls_cs.dwork, iwl_mvm_tdls_ch_switch_work);
INIT_DELAYED_WORK(&mvm->scan_timeout_dwork, iwl_mvm_scan_timeout_wk);
INIT_WORK(&mvm->add_stream_wk, iwl_mvm_add_new_dqa_stream_wk);
INIT_LIST_HEAD(&mvm->add_stream_txqs);
init_waitqueue_head(&mvm->rx_sync_waitq);
atomic_set(&mvm->queue_sync_counter, 0);
SET_IEEE80211_DEV(mvm->hw, mvm->trans->dev);
spin_lock_init(&mvm->tcm.lock);
INIT_DELAYED_WORK(&mvm->tcm.work, iwl_mvm_tcm_work);
mvm->tcm.ts = jiffies;
mvm->tcm.ll_ts = jiffies;
mvm->tcm.uapsd_nonagg_ts = jiffies;
INIT_DELAYED_WORK(&mvm->cs_tx_unblock_dwork, iwl_mvm_tx_unblock_dwork);
mvm->cmd_ver.d0i3_resp =
iwl_fw_lookup_notif_ver(mvm->fw, LEGACY_GROUP, D0I3_END_CMD,
0);
/* we only support version 1 */
if (WARN_ON_ONCE(mvm->cmd_ver.d0i3_resp > 1))
goto out_free;
/*
* Populate the state variables that the transport layer needs
* to know about.
*/
trans_cfg.op_mode = op_mode;
trans_cfg.no_reclaim_cmds = no_reclaim_cmds;
trans_cfg.n_no_reclaim_cmds = ARRAY_SIZE(no_reclaim_cmds);
if (mvm->trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210)
rb_size_default = IWL_AMSDU_2K;
else
rb_size_default = IWL_AMSDU_4K;
switch (iwlwifi_mod_params.amsdu_size) {
case IWL_AMSDU_DEF:
trans_cfg.rx_buf_size = rb_size_default;
break;
case IWL_AMSDU_4K:
trans_cfg.rx_buf_size = IWL_AMSDU_4K;
break;
case IWL_AMSDU_8K:
trans_cfg.rx_buf_size = IWL_AMSDU_8K;
break;
case IWL_AMSDU_12K:
trans_cfg.rx_buf_size = IWL_AMSDU_12K;
break;
default:
pr_err("%s: Unsupported amsdu_size: %d\n", KBUILD_MODNAME,
iwlwifi_mod_params.amsdu_size);
trans_cfg.rx_buf_size = rb_size_default;
}
trans->wide_cmd_header = true;
trans_cfg.bc_table_dword =
mvm->trans->trans_cfg->device_family < IWL_DEVICE_FAMILY_AX210;
trans_cfg.command_groups = iwl_mvm_groups;
trans_cfg.command_groups_size = ARRAY_SIZE(iwl_mvm_groups);
trans_cfg.cmd_queue = IWL_MVM_DQA_CMD_QUEUE;
trans_cfg.cmd_fifo = IWL_MVM_TX_FIFO_CMD;
trans_cfg.scd_set_active = true;
trans_cfg.cb_data_offs = offsetof(struct ieee80211_tx_info,
driver_data[2]);
trans_cfg.sw_csum_tx = IWL_MVM_SW_TX_CSUM_OFFLOAD;
/* Set a short watchdog for the command queue */
trans_cfg.cmd_q_wdg_timeout =
iwl_mvm_get_wd_timeout(mvm, NULL, false, true);
snprintf(mvm->hw->wiphy->fw_version,
sizeof(mvm->hw->wiphy->fw_version),
"%s", fw->fw_version);
/* Configure transport layer */
iwl_trans_configure(mvm->trans, &trans_cfg);
trans->rx_mpdu_cmd = REPLY_RX_MPDU_CMD;
trans->dbg.dest_tlv = mvm->fw->dbg.dest_tlv;
trans->dbg.n_dest_reg = mvm->fw->dbg.n_dest_reg;
memcpy(trans->dbg.conf_tlv, mvm->fw->dbg.conf_tlv,
sizeof(trans->dbg.conf_tlv));
trans->dbg.trigger_tlv = mvm->fw->dbg.trigger_tlv;
trans->iml = mvm->fw->iml;
trans->iml_len = mvm->fw->iml_len;
/* set up notification wait support */
iwl_notification_wait_init(&mvm->notif_wait);
/* Init phy db */
mvm->phy_db = iwl_phy_db_init(trans);
if (!mvm->phy_db) {
IWL_ERR(mvm, "Cannot init phy_db\n");
goto out_free;
}
IWL_INFO(mvm, "Detected %s, REV=0x%X\n",
mvm->trans->name, mvm->trans->hw_rev);
if (iwlwifi_mod_params.nvm_file)
mvm->nvm_file_name = iwlwifi_mod_params.nvm_file;
else
IWL_DEBUG_EEPROM(mvm->trans->dev,
"working without external nvm file\n");
err = iwl_trans_start_hw(mvm->trans);
if (err)
goto out_free;
mutex_lock(&mvm->mutex);
err = iwl_run_init_mvm_ucode(mvm, true);
if (err && err != -ERFKILL)
iwl_fw_dbg_error_collect(&mvm->fwrt, FW_DBG_TRIGGER_DRIVER);
if (!iwlmvm_mod_params.init_dbg || !err)
iwl_mvm_stop_device(mvm);
mutex_unlock(&mvm->mutex);
if (err < 0) {
IWL_ERR(mvm, "Failed to run INIT ucode: %d\n", err);
goto out_free;
}
scan_size = iwl_mvm_scan_size(mvm);
mvm->scan_cmd = kmalloc(scan_size, GFP_KERNEL);
if (!mvm->scan_cmd)
goto out_free;
/* Set EBS as successful as long as not stated otherwise by the FW. */
mvm->last_ebs_successful = true;
err = iwl_mvm_mac_setup_register(mvm);
if (err)
goto out_free;
mvm->hw_registered = true;
min_backoff = iwl_mvm_min_backoff(mvm);
iwl_mvm_thermal_initialize(mvm, min_backoff);
iwl_mvm_dbgfs_register(mvm, dbgfs_dir);
if (!iwl_mvm_has_new_rx_stats_api(mvm))
memset(&mvm->rx_stats_v3, 0,
sizeof(struct mvm_statistics_rx_v3));
else
memset(&mvm->rx_stats, 0, sizeof(struct mvm_statistics_rx));
iwl_mvm_toggle_tx_ant(mvm, &mvm->mgmt_last_antenna_idx);
return op_mode;
out_free:
iwl_fw_flush_dumps(&mvm->fwrt);
iwl_fw_runtime_free(&mvm->fwrt);
if (iwlmvm_mod_params.init_dbg)
return op_mode;
iwl_phy_db_free(mvm->phy_db);
kfree(mvm->scan_cmd);
iwl_trans_op_mode_leave(trans);
ieee80211_free_hw(mvm->hw);
return NULL;
}
static void iwl_op_mode_mvm_stop(struct iwl_op_mode *op_mode)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
int i;
iwl_mvm_leds_exit(mvm);
iwl_mvm_thermal_exit(mvm);
ieee80211_unregister_hw(mvm->hw);
kfree(mvm->scan_cmd);
kfree(mvm->mcast_filter_cmd);
mvm->mcast_filter_cmd = NULL;
kfree(mvm->error_recovery_buf);
mvm->error_recovery_buf = NULL;
iwl_trans_op_mode_leave(mvm->trans);
iwl_phy_db_free(mvm->phy_db);
mvm->phy_db = NULL;
kfree(mvm->nvm_data);
for (i = 0; i < NVM_MAX_NUM_SECTIONS; i++)
kfree(mvm->nvm_sections[i].data);
cancel_delayed_work_sync(&mvm->tcm.work);
iwl_fw_runtime_free(&mvm->fwrt);
mutex_destroy(&mvm->mutex);
ieee80211_free_hw(mvm->hw);
}
struct iwl_async_handler_entry {
struct list_head list;
struct iwl_rx_cmd_buffer rxb;
enum iwl_rx_handler_context context;
void (*fn)(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb);
};
void iwl_mvm_async_handlers_purge(struct iwl_mvm *mvm)
{
struct iwl_async_handler_entry *entry, *tmp;
spin_lock_bh(&mvm->async_handlers_lock);
list_for_each_entry_safe(entry, tmp, &mvm->async_handlers_list, list) {
iwl_free_rxb(&entry->rxb);
list_del(&entry->list);
kfree(entry);
}
spin_unlock_bh(&mvm->async_handlers_lock);
}
static void iwl_mvm_async_handlers_wk(struct work_struct *wk)
{
struct iwl_mvm *mvm =
container_of(wk, struct iwl_mvm, async_handlers_wk);
struct iwl_async_handler_entry *entry, *tmp;
LIST_HEAD(local_list);
/* Ensure that we are not in stop flow (check iwl_mvm_mac_stop) */
/*
* Sync with Rx path with a lock. Remove all the entries from this list,
* add them to a local one (lock free), and then handle them.
*/
spin_lock_bh(&mvm->async_handlers_lock);
list_splice_init(&mvm->async_handlers_list, &local_list);
spin_unlock_bh(&mvm->async_handlers_lock);
list_for_each_entry_safe(entry, tmp, &local_list, list) {
if (entry->context == RX_HANDLER_ASYNC_LOCKED)
mutex_lock(&mvm->mutex);
entry->fn(mvm, &entry->rxb);
iwl_free_rxb(&entry->rxb);
list_del(&entry->list);
if (entry->context == RX_HANDLER_ASYNC_LOCKED)
mutex_unlock(&mvm->mutex);
kfree(entry);
}
}
static inline void iwl_mvm_rx_check_trigger(struct iwl_mvm *mvm,
struct iwl_rx_packet *pkt)
{
struct iwl_fw_dbg_trigger_tlv *trig;
struct iwl_fw_dbg_trigger_cmd *cmds_trig;
int i;
trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, NULL,
FW_DBG_TRIGGER_FW_NOTIF);
if (!trig)
return;
cmds_trig = (void *)trig->data;
for (i = 0; i < ARRAY_SIZE(cmds_trig->cmds); i++) {
/* don't collect on CMD 0 */
if (!cmds_trig->cmds[i].cmd_id)
break;
if (cmds_trig->cmds[i].cmd_id != pkt->hdr.cmd ||
cmds_trig->cmds[i].group_id != pkt->hdr.group_id)
continue;
iwl_fw_dbg_collect_trig(&mvm->fwrt, trig,
"CMD 0x%02x.%02x received",
pkt->hdr.group_id, pkt->hdr.cmd);
break;
}
}
static void iwl_mvm_rx_common(struct iwl_mvm *mvm,
struct iwl_rx_cmd_buffer *rxb,
struct iwl_rx_packet *pkt)
{
int i;
union iwl_dbg_tlv_tp_data tp_data = { .fw_pkt = pkt };
iwl_dbg_tlv_time_point(&mvm->fwrt,
IWL_FW_INI_TIME_POINT_FW_RSP_OR_NOTIF, &tp_data);
iwl_mvm_rx_check_trigger(mvm, pkt);
/*
* Do the notification wait before RX handlers so
* even if the RX handler consumes the RXB we have
* access to it in the notification wait entry.
*/
iwl_notification_wait_notify(&mvm->notif_wait, pkt);
for (i = 0; i < ARRAY_SIZE(iwl_mvm_rx_handlers); i++) {
const struct iwl_rx_handlers *rx_h = &iwl_mvm_rx_handlers[i];
struct iwl_async_handler_entry *entry;
if (rx_h->cmd_id != WIDE_ID(pkt->hdr.group_id, pkt->hdr.cmd))
continue;
if (rx_h->context == RX_HANDLER_SYNC) {
rx_h->fn(mvm, rxb);
return;
}
entry = kzalloc(sizeof(*entry), GFP_ATOMIC);
/* we can't do much... */
if (!entry)
return;
entry->rxb._page = rxb_steal_page(rxb);
entry->rxb._offset = rxb->_offset;
entry->rxb._rx_page_order = rxb->_rx_page_order;
entry->fn = rx_h->fn;
entry->context = rx_h->context;
spin_lock(&mvm->async_handlers_lock);
list_add_tail(&entry->list, &mvm->async_handlers_list);
spin_unlock(&mvm->async_handlers_lock);
schedule_work(&mvm->async_handlers_wk);
break;
}
}
static void iwl_mvm_rx(struct iwl_op_mode *op_mode,
struct napi_struct *napi,
struct iwl_rx_cmd_buffer *rxb)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
u16 cmd = WIDE_ID(pkt->hdr.group_id, pkt->hdr.cmd);
if (likely(cmd == WIDE_ID(LEGACY_GROUP, REPLY_RX_MPDU_CMD)))
iwl_mvm_rx_rx_mpdu(mvm, napi, rxb);
else if (cmd == WIDE_ID(LEGACY_GROUP, REPLY_RX_PHY_CMD))
iwl_mvm_rx_rx_phy_cmd(mvm, rxb);
else
iwl_mvm_rx_common(mvm, rxb, pkt);
}
static void iwl_mvm_rx_mq(struct iwl_op_mode *op_mode,
struct napi_struct *napi,
struct iwl_rx_cmd_buffer *rxb)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
u16 cmd = WIDE_ID(pkt->hdr.group_id, pkt->hdr.cmd);
if (likely(cmd == WIDE_ID(LEGACY_GROUP, REPLY_RX_MPDU_CMD)))
iwl_mvm_rx_mpdu_mq(mvm, napi, rxb, 0);
else if (unlikely(cmd == WIDE_ID(DATA_PATH_GROUP,
RX_QUEUES_NOTIFICATION)))
iwl_mvm_rx_queue_notif(mvm, napi, rxb, 0);
else if (cmd == WIDE_ID(LEGACY_GROUP, FRAME_RELEASE))
iwl_mvm_rx_frame_release(mvm, napi, rxb, 0);
else if (cmd == WIDE_ID(LEGACY_GROUP, BAR_FRAME_RELEASE))
iwl_mvm_rx_bar_frame_release(mvm, napi, rxb, 0);
else if (cmd == WIDE_ID(DATA_PATH_GROUP, RX_NO_DATA_NOTIF))
iwl_mvm_rx_monitor_no_data(mvm, napi, rxb, 0);
else
iwl_mvm_rx_common(mvm, rxb, pkt);
}
static void iwl_mvm_async_cb(struct iwl_op_mode *op_mode,
const struct iwl_device_cmd *cmd)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
/*
* For now, we only set the CMD_WANT_ASYNC_CALLBACK for ADD_STA
* commands that need to block the Tx queues.
*/
iwl_trans_block_txq_ptrs(mvm->trans, false);
}
static int iwl_mvm_is_static_queue(struct iwl_mvm *mvm, int queue)
{
return queue == mvm->aux_queue || queue == mvm->probe_queue ||
queue == mvm->p2p_dev_queue || queue == mvm->snif_queue;
}
static void iwl_mvm_queue_state_change(struct iwl_op_mode *op_mode,
int hw_queue, bool start)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
struct ieee80211_sta *sta;
struct ieee80211_txq *txq;
struct iwl_mvm_txq *mvmtxq;
int i;
unsigned long tid_bitmap;
struct iwl_mvm_sta *mvmsta;
u8 sta_id;
sta_id = iwl_mvm_has_new_tx_api(mvm) ?
mvm->tvqm_info[hw_queue].sta_id :
mvm->queue_info[hw_queue].ra_sta_id;
if (WARN_ON_ONCE(sta_id >= ARRAY_SIZE(mvm->fw_id_to_mac_id)))
return;
rcu_read_lock();
sta = rcu_dereference(mvm->fw_id_to_mac_id[sta_id]);
if (IS_ERR_OR_NULL(sta))
goto out;
mvmsta = iwl_mvm_sta_from_mac80211(sta);
if (iwl_mvm_is_static_queue(mvm, hw_queue)) {
if (!start)
ieee80211_stop_queues(mvm->hw);
else if (mvmsta->sta_state != IEEE80211_STA_NOTEXIST)
ieee80211_wake_queues(mvm->hw);
goto out;
}
if (iwl_mvm_has_new_tx_api(mvm)) {
int tid = mvm->tvqm_info[hw_queue].txq_tid;
tid_bitmap = BIT(tid);
} else {
tid_bitmap = mvm->queue_info[hw_queue].tid_bitmap;
}
for_each_set_bit(i, &tid_bitmap, IWL_MAX_TID_COUNT + 1) {
int tid = i;
if (tid == IWL_MAX_TID_COUNT)
tid = IEEE80211_NUM_TIDS;
txq = sta->txq[tid];
mvmtxq = iwl_mvm_txq_from_mac80211(txq);
mvmtxq->stopped = !start;
if (start && mvmsta->sta_state != IEEE80211_STA_NOTEXIST)
iwl_mvm_mac_itxq_xmit(mvm->hw, txq);
}
out:
rcu_read_unlock();
}
static void iwl_mvm_stop_sw_queue(struct iwl_op_mode *op_mode, int hw_queue)
{
iwl_mvm_queue_state_change(op_mode, hw_queue, false);
}
static void iwl_mvm_wake_sw_queue(struct iwl_op_mode *op_mode, int hw_queue)
{
iwl_mvm_queue_state_change(op_mode, hw_queue, true);
}
static void iwl_mvm_set_rfkill_state(struct iwl_mvm *mvm)
{
bool state = iwl_mvm_is_radio_killed(mvm);
if (state)
wake_up(&mvm->rx_sync_waitq);
wiphy_rfkill_set_hw_state(mvm->hw->wiphy, state);
}
void iwl_mvm_set_hw_ctkill_state(struct iwl_mvm *mvm, bool state)
{
if (state)
set_bit(IWL_MVM_STATUS_HW_CTKILL, &mvm->status);
else
clear_bit(IWL_MVM_STATUS_HW_CTKILL, &mvm->status);
iwl_mvm_set_rfkill_state(mvm);
}
static bool iwl_mvm_set_hw_rfkill_state(struct iwl_op_mode *op_mode, bool state)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
bool rfkill_safe_init_done = READ_ONCE(mvm->rfkill_safe_init_done);
bool unified = iwl_mvm_has_unified_ucode(mvm);
if (state)
set_bit(IWL_MVM_STATUS_HW_RFKILL, &mvm->status);
else
clear_bit(IWL_MVM_STATUS_HW_RFKILL, &mvm->status);
iwl_mvm_set_rfkill_state(mvm);
/* iwl_run_init_mvm_ucode is waiting for results, abort it. */
if (rfkill_safe_init_done)
iwl_abort_notification_waits(&mvm->notif_wait);
/*
* Don't ask the transport to stop the firmware. We'll do it
* after cfg80211 takes us down.
*/
if (unified)
return false;
/*
* Stop the device if we run OPERATIONAL firmware or if we are in the
* middle of the calibrations.
*/
return state && rfkill_safe_init_done;
}
static void iwl_mvm_free_skb(struct iwl_op_mode *op_mode, struct sk_buff *skb)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
struct ieee80211_tx_info *info;
info = IEEE80211_SKB_CB(skb);
iwl_trans_free_tx_cmd(mvm->trans, info->driver_data[1]);
ieee80211_free_txskb(mvm->hw, skb);
}
struct iwl_mvm_reprobe {
struct device *dev;
struct work_struct work;
};
static void iwl_mvm_reprobe_wk(struct work_struct *wk)
{
struct iwl_mvm_reprobe *reprobe;
reprobe = container_of(wk, struct iwl_mvm_reprobe, work);
if (device_reprobe(reprobe->dev))
dev_err(reprobe->dev, "reprobe failed!\n");
kfree(reprobe);
module_put(THIS_MODULE);
}
void iwl_mvm_nic_restart(struct iwl_mvm *mvm, bool fw_error)
{
iwl_abort_notification_waits(&mvm->notif_wait);
iwl_dbg_tlv_del_timers(mvm->trans);
/*
* This is a bit racy, but worst case we tell mac80211 about
* a stopped/aborted scan when that was already done which
* is not a problem. It is necessary to abort any os scan
* here because mac80211 requires having the scan cleared
* before restarting.
* We'll reset the scan_status to NONE in restart cleanup in
* the next start() call from mac80211. If restart isn't called
* (no fw restart) scan status will stay busy.
*/
iwl_mvm_report_scan_aborted(mvm);
/*
* If we're restarting already, don't cycle restarts.
* If INIT fw asserted, it will likely fail again.
* If WoWLAN fw asserted, don't restart either, mac80211
* can't recover this since we're already half suspended.
*/
if (!mvm->fw_restart && fw_error) {
iwl_fw_error_collect(&mvm->fwrt);
} else if (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status)) {
struct iwl_mvm_reprobe *reprobe;
IWL_ERR(mvm,
"Firmware error during reconfiguration - reprobe!\n");
/*
* get a module reference to avoid doing this while unloading
* anyway and to avoid scheduling a work with code that's
* being removed.
*/
if (!try_module_get(THIS_MODULE)) {
IWL_ERR(mvm, "Module is being unloaded - abort\n");
return;
}
reprobe = kzalloc(sizeof(*reprobe), GFP_ATOMIC);
if (!reprobe) {
module_put(THIS_MODULE);
return;
}
reprobe->dev = mvm->trans->dev;
INIT_WORK(&reprobe->work, iwl_mvm_reprobe_wk);
schedule_work(&reprobe->work);
} else if (test_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED,
&mvm->status)) {
IWL_ERR(mvm, "HW restart already requested, but not started\n");
} else if (mvm->fwrt.cur_fw_img == IWL_UCODE_REGULAR &&
mvm->hw_registered &&
!test_bit(STATUS_TRANS_DEAD, &mvm->trans->status)) {
if (mvm->fw->ucode_capa.error_log_size) {
u32 src_size = mvm->fw->ucode_capa.error_log_size;
u32 src_addr = mvm->fw->ucode_capa.error_log_addr;
u8 *recover_buf = kzalloc(src_size, GFP_ATOMIC);
if (recover_buf) {
mvm->error_recovery_buf = recover_buf;
iwl_trans_read_mem_bytes(mvm->trans,
src_addr,
recover_buf,
src_size);
}
}
iwl_fw_error_collect(&mvm->fwrt);
if (fw_error && mvm->fw_restart > 0)
mvm->fw_restart--;
set_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED, &mvm->status);
ieee80211_restart_hw(mvm->hw);
}
}
static void iwl_mvm_nic_error(struct iwl_op_mode *op_mode)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
if (!test_bit(STATUS_TRANS_DEAD, &mvm->trans->status))
iwl_mvm_dump_nic_error_log(mvm);
iwl_mvm_nic_restart(mvm, true);
}
static void iwl_mvm_cmd_queue_full(struct iwl_op_mode *op_mode)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
WARN_ON(1);
iwl_mvm_nic_restart(mvm, true);
}
#define IWL_MVM_COMMON_OPS \
/* these could be differentiated */ \
.async_cb = iwl_mvm_async_cb, \
.queue_full = iwl_mvm_stop_sw_queue, \
.queue_not_full = iwl_mvm_wake_sw_queue, \
.hw_rf_kill = iwl_mvm_set_hw_rfkill_state, \
.free_skb = iwl_mvm_free_skb, \
.nic_error = iwl_mvm_nic_error, \
.cmd_queue_full = iwl_mvm_cmd_queue_full, \
.nic_config = iwl_mvm_nic_config, \
/* as we only register one, these MUST be common! */ \
.start = iwl_op_mode_mvm_start, \
.stop = iwl_op_mode_mvm_stop
static const struct iwl_op_mode_ops iwl_mvm_ops = {
IWL_MVM_COMMON_OPS,
.rx = iwl_mvm_rx,
};
static void iwl_mvm_rx_mq_rss(struct iwl_op_mode *op_mode,
struct napi_struct *napi,
struct iwl_rx_cmd_buffer *rxb,
unsigned int queue)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
struct iwl_rx_packet *pkt = rxb_addr(rxb);
u16 cmd = WIDE_ID(pkt->hdr.group_id, pkt->hdr.cmd);
if (unlikely(cmd == WIDE_ID(LEGACY_GROUP, FRAME_RELEASE)))
iwl_mvm_rx_frame_release(mvm, napi, rxb, queue);
else if (unlikely(cmd == WIDE_ID(DATA_PATH_GROUP,
RX_QUEUES_NOTIFICATION)))
iwl_mvm_rx_queue_notif(mvm, napi, rxb, queue);
else if (likely(cmd == WIDE_ID(LEGACY_GROUP, REPLY_RX_MPDU_CMD)))
iwl_mvm_rx_mpdu_mq(mvm, napi, rxb, queue);
}
static const struct iwl_op_mode_ops iwl_mvm_ops_mq = {
IWL_MVM_COMMON_OPS,
.rx = iwl_mvm_rx_mq,
.rx_rss = iwl_mvm_rx_mq_rss,
};
| {
"pile_set_name": "Github"
} |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import os
from fairseq import options, utils
from fairseq.data import (
ConcatDataset,
data_utils,
indexed_dataset,
LanguagePairDataset,
)
from . import FairseqTask, register_task
def load_langpair_dataset(
data_path, split,
src, src_dict,
tgt, tgt_dict,
combine, dataset_impl, upsample_primary,
left_pad_source, left_pad_target, max_source_positions, max_target_positions,
):
def split_exists(split, src, tgt, lang, data_path):
filename = os.path.join(data_path, '{}.{}-{}.{}'.format(split, src, tgt, lang))
return indexed_dataset.dataset_exists(filename, impl=dataset_impl)
src_datasets = []
tgt_datasets = []
for k in itertools.count():
split_k = split + (str(k) if k > 0 else '')
# infer langcode
if split_exists(split_k, src, tgt, src, data_path):
prefix = os.path.join(data_path, '{}.{}-{}.'.format(split_k, src, tgt))
elif split_exists(split_k, tgt, src, src, data_path):
prefix = os.path.join(data_path, '{}.{}-{}.'.format(split_k, tgt, src))
else:
if k > 0:
break
else:
raise FileNotFoundError('Dataset not found: {} ({})'.format(split, data_path))
src_datasets.append(
data_utils.load_indexed_dataset(prefix + src, src_dict, dataset_impl)
)
tgt_datasets.append(
data_utils.load_indexed_dataset(prefix + tgt, tgt_dict, dataset_impl)
)
print('| {} {} {}-{} {} examples'.format(data_path, split_k, src, tgt, len(src_datasets[-1])))
if not combine:
break
assert len(src_datasets) == len(tgt_datasets)
if len(src_datasets) == 1:
src_dataset, tgt_dataset = src_datasets[0], tgt_datasets[0]
else:
sample_ratios = [1] * len(src_datasets)
sample_ratios[0] = upsample_primary
src_dataset = ConcatDataset(src_datasets, sample_ratios)
tgt_dataset = ConcatDataset(tgt_datasets, sample_ratios)
return LanguagePairDataset(
src_dataset, src_dataset.sizes, src_dict,
tgt_dataset, tgt_dataset.sizes, tgt_dict,
left_pad_source=left_pad_source,
left_pad_target=left_pad_target,
max_source_positions=max_source_positions,
max_target_positions=max_target_positions,
)
@register_task('translation')
class TranslationTask(FairseqTask):
"""
Translate from one (source) language to another (target) language.
Args:
src_dict (~fairseq.data.Dictionary): dictionary for the source language
tgt_dict (~fairseq.data.Dictionary): dictionary for the target language
.. note::
The translation task is compatible with :mod:`fairseq-train`,
:mod:`fairseq-generate` and :mod:`fairseq-interactive`.
The translation task provides the following additional command-line
arguments:
.. argparse::
:ref: fairseq.tasks.translation_parser
:prog:
"""
@staticmethod
def add_args(parser):
"""Add task-specific arguments to the parser."""
# fmt: off
parser.add_argument('--data', help='colon separated path to data directories list, \
will be iterated upon during epochs in round-robin manner')
parser.add_argument('-s', '--source-lang', default=None, metavar='SRC',
help='source language')
parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET',
help='target language')
parser.add_argument('--lazy-load', action='store_true',
help='load the dataset lazily')
parser.add_argument('--raw-text', action='store_true',
help='load raw text dataset')
parser.add_argument('--left-pad-source', default='True', type=str, metavar='BOOL',
help='pad the source on the left')
parser.add_argument('--left-pad-target', default='False', type=str, metavar='BOOL',
help='pad the target on the left')
parser.add_argument('--max-source-positions', default=1024, type=int, metavar='N',
help='max number of tokens in the source sequence')
parser.add_argument('--max-target-positions', default=1024, type=int, metavar='N',
help='max number of tokens in the target sequence')
parser.add_argument('--upsample-primary', default=1, type=int,
help='amount to upsample primary dataset')
# fmt: on
def __init__(self, args, src_dict, tgt_dict):
super().__init__(args)
self.src_dict = src_dict
self.tgt_dict = tgt_dict
@classmethod
def setup_task(cls, args, **kwargs):
"""Setup the task (e.g., load dictionaries).
Args:
args (argparse.Namespace): parsed command-line arguments
"""
args.left_pad_source = options.eval_bool(args.left_pad_source)
args.left_pad_target = options.eval_bool(args.left_pad_target)
if getattr(args, 'raw_text', False):
utils.deprecation_warning('--raw-text is deprecated, please use --dataset-impl=raw')
args.dataset_impl = 'raw'
elif getattr(args, 'lazy_load', False):
utils.deprecation_warning('--lazy-load is deprecated, please use --dataset-impl=lazy')
args.dataset_impl = 'lazy'
paths = args.data.split(':')
assert len(paths) > 0
# find language pair automatically
if args.source_lang is None or args.target_lang is None:
args.source_lang, args.target_lang = data_utils.infer_language_pair(paths[0])
if args.source_lang is None or args.target_lang is None:
raise Exception('Could not infer language pair, please provide it explicitly')
# load dictionaries
src_dict = cls.load_dictionary(os.path.join(paths[0], 'dict.{}.txt'.format(args.source_lang)))
tgt_dict = cls.load_dictionary(os.path.join(paths[0], 'dict.{}.txt'.format(args.target_lang)))
assert src_dict.pad() == tgt_dict.pad()
assert src_dict.eos() == tgt_dict.eos()
assert src_dict.unk() == tgt_dict.unk()
print('| [{}] dictionary: {} types'.format(args.source_lang, len(src_dict)))
print('| [{}] dictionary: {} types'.format(args.target_lang, len(tgt_dict)))
return cls(args, src_dict, tgt_dict)
def load_dataset(self, split, epoch=0, combine=False, **kwargs):
"""Load a given dataset split.
Args:
split (str): name of the split (e.g., train, valid, test)
"""
paths = self.args.data.split(':')
assert len(paths) > 0
data_path = paths[epoch % len(paths)]
# infer langcode
src, tgt = self.args.source_lang, self.args.target_lang
self.datasets[split] = load_langpair_dataset(
data_path, split, src, self.src_dict, tgt, self.tgt_dict,
combine=combine, dataset_impl=self.args.dataset_impl,
upsample_primary=self.args.upsample_primary,
left_pad_source=self.args.left_pad_source,
left_pad_target=self.args.left_pad_target,
max_source_positions=self.args.max_source_positions,
max_target_positions=self.args.max_target_positions,
)
def build_dataset_for_inference(self, src_tokens, src_lengths):
return LanguagePairDataset(src_tokens, src_lengths, self.source_dictionary)
def max_positions(self):
"""Return the max sentence length allowed by the task."""
return (self.args.max_source_positions, self.args.max_target_positions)
@property
def source_dictionary(self):
"""Return the source :class:`~fairseq.data.Dictionary`."""
return self.src_dict
@property
def target_dictionary(self):
"""Return the target :class:`~fairseq.data.Dictionary`."""
return self.tgt_dict
| {
"pile_set_name": "Github"
} |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.ProximityBeacon.Namespaces.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all attachment namespaces owned by your Google Developers Console
-- project. Attachment data associated with a beacon must include a
-- namespaced type, and the namespace must be owned by your project.
-- Authenticate using an [OAuth access
-- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2)
-- from a signed-in user with **viewer**, **Is owner** or **Can edit**
-- permissions in the Google Developers Console project.
--
-- /See:/ <https://developers.google.com/beacons/proximity/ Proximity Beacon API Reference> for @proximitybeacon.namespaces.list@.
module Network.Google.Resource.ProximityBeacon.Namespaces.List
(
-- * REST Resource
NamespacesListResource
-- * Creating a Request
, namespacesList
, NamespacesList
-- * Request Lenses
, nlXgafv
, nlUploadProtocol
, nlAccessToken
, nlUploadType
, nlProjectId
, nlCallback
) where
import Network.Google.Prelude
import Network.Google.ProximityBeacon.Types
-- | A resource alias for @proximitybeacon.namespaces.list@ method which the
-- 'NamespacesList' request conforms to.
type NamespacesListResource =
"v1beta1" :>
"namespaces" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "projectId" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListNamespacesResponse
-- | Lists all attachment namespaces owned by your Google Developers Console
-- project. Attachment data associated with a beacon must include a
-- namespaced type, and the namespace must be owned by your project.
-- Authenticate using an [OAuth access
-- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2)
-- from a signed-in user with **viewer**, **Is owner** or **Can edit**
-- permissions in the Google Developers Console project.
--
-- /See:/ 'namespacesList' smart constructor.
data NamespacesList =
NamespacesList'
{ _nlXgafv :: !(Maybe Xgafv)
, _nlUploadProtocol :: !(Maybe Text)
, _nlAccessToken :: !(Maybe Text)
, _nlUploadType :: !(Maybe Text)
, _nlProjectId :: !(Maybe Text)
, _nlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'NamespacesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'nlXgafv'
--
-- * 'nlUploadProtocol'
--
-- * 'nlAccessToken'
--
-- * 'nlUploadType'
--
-- * 'nlProjectId'
--
-- * 'nlCallback'
namespacesList
:: NamespacesList
namespacesList =
NamespacesList'
{ _nlXgafv = Nothing
, _nlUploadProtocol = Nothing
, _nlAccessToken = Nothing
, _nlUploadType = Nothing
, _nlProjectId = Nothing
, _nlCallback = Nothing
}
-- | V1 error format.
nlXgafv :: Lens' NamespacesList (Maybe Xgafv)
nlXgafv = lens _nlXgafv (\ s a -> s{_nlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
nlUploadProtocol :: Lens' NamespacesList (Maybe Text)
nlUploadProtocol
= lens _nlUploadProtocol
(\ s a -> s{_nlUploadProtocol = a})
-- | OAuth access token.
nlAccessToken :: Lens' NamespacesList (Maybe Text)
nlAccessToken
= lens _nlAccessToken
(\ s a -> s{_nlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
nlUploadType :: Lens' NamespacesList (Maybe Text)
nlUploadType
= lens _nlUploadType (\ s a -> s{_nlUploadType = a})
-- | The project id to list namespaces under. Optional.
nlProjectId :: Lens' NamespacesList (Maybe Text)
nlProjectId
= lens _nlProjectId (\ s a -> s{_nlProjectId = a})
-- | JSONP
nlCallback :: Lens' NamespacesList (Maybe Text)
nlCallback
= lens _nlCallback (\ s a -> s{_nlCallback = a})
instance GoogleRequest NamespacesList where
type Rs NamespacesList = ListNamespacesResponse
type Scopes NamespacesList =
'["https://www.googleapis.com/auth/userlocation.beacon.registry"]
requestClient NamespacesList'{..}
= go _nlXgafv _nlUploadProtocol _nlAccessToken
_nlUploadType
_nlProjectId
_nlCallback
(Just AltJSON)
proximityBeaconService
where go
= buildClient (Proxy :: Proxy NamespacesListResource)
mempty
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2015 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingRight="8dp"
android:paddingEnd="8dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"
>
<LinearLayout
android:id="@+id/line1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:orientation="horizontal"
>
<TextView android:id="@+id/title"
android:textAppearance="@style/TextAppearance.StatusBar.EventContent.Title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:layout_weight="1"
/>
<include
layout="@layout/notification_template_part_time"
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0"
android:visibility="gone"
/>
<include
layout="@layout/notification_template_part_chronometer"
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0"
android:visibility="gone"
/>
</LinearLayout>
<TextView android:id="@+id/text2"
android:textAppearance="@style/TextAppearance.StatusBar.EventContent.Line2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-2dp"
android:layout_marginBottom="-2dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:singleLine="true"
android:fadingEdge="horizontal"
android:ellipsize="marquee"
android:visibility="gone"
/>
<LinearLayout
android:id="@+id/line3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
>
<TextView android:id="@+id/text"
android:textAppearance="@style/TextAppearance.StatusBar.EventContent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:singleLine="true"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
/>
<TextView android:id="@+id/info"
android:textAppearance="@style/TextAppearance.StatusBar.EventContent.Info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0"
android:singleLine="true"
android:gravity="center"
android:paddingLeft="8dp"
android:paddingStart="8dp"
/>
</LinearLayout>
</LinearLayout><!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-sdk-release/frameworks/support/v7/appcompat/res/layout/notification_template_lines.xml --><!-- From: file:/Users/hugo/github/react-native-demo/android/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/layout/notification_template_lines.xml --> | {
"pile_set_name": "Github"
} |
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package policies
import (
"github.com/inklabsfoundation/inkchain/common/policies"
cb "github.com/inklabsfoundation/inkchain/protos/common"
)
// Policy is a mock implementation of the policies.Policy interface
type Policy struct {
// Err is the error returned by Evaluate
Err error
}
// Evaluate returns the Err set in Policy
func (p *Policy) Evaluate(signatureSet []*cb.SignedData) error {
return p.Err
}
// Manager is a mock implementation of the policies.Manager interface
type Manager struct {
// Policy is returned as the output to GetPolicy if a Policy
// for id is not in PolicyMap
Policy *Policy
// BasePathVal is returned as the result of BasePath
BasePathVal string
// PolicyMap is returned is used to look up Policies in
PolicyMap map[string]policies.Policy
// SubManagers is used for the return value of Manager
SubManagersMap map[string]*Manager
}
// PolicyNames panics
func (m *Manager) PolicyNames() []string {
panic("Unimplimented")
}
// BasePath returns BasePathVal
func (m *Manager) BasePath() string {
return m.BasePathVal
}
// Manager returns the Manager from SubManagers for the last component of the path
func (m *Manager) Manager(path []string) (policies.Manager, bool) {
if len(path) == 0 {
return m, true
}
manager, ok := m.SubManagersMap[path[len(path)-1]]
return manager, ok
}
// GetPolicy returns the value of Manager.Policy and whether it was nil or not
func (m *Manager) GetPolicy(id string) (policies.Policy, bool) {
if m.PolicyMap != nil {
policy, ok := m.PolicyMap[id]
if ok {
return policy, true
}
}
return m.Policy, m.Policy != nil
}
| {
"pile_set_name": "Github"
} |
#region Copyright (C) 2009 by Pavel Savara
/*
This file is part of jni4net library - bridge between Java and .NET
http://jni4net.sourceforge.net/
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
namespace MonoJavaBridge
{
partial class JNIEnv
{
#region Nested type: Delegates
internal unsafe struct Delegates
{
#region Nested type: AllocObject
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr AllocObject(IntPtr thiz, IntPtr clazz);
#endregion
#region Nested type: CallBooleanMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte CallBooleanMethod(
IntPtr thiz, IntPtr obj, IntPtr methodIdJavaPtr, params Value[] args);
#endregion
#region Nested type: CallByteMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte CallByteMethod(
IntPtr thiz, IntPtr obj, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallCharMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate ushort CallCharMethod(
IntPtr thiz, IntPtr obj, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallDoubleMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate double CallDoubleMethod(
IntPtr thiz, IntPtr obj, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallFloatMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate float CallFloatMethod(
IntPtr thiz, IntPtr obj, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallIntMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int CallIntMethod(
IntPtr thiz, IntPtr obj, IntPtr methodIdJavaPtr, params Value[] args);
#endregion
#region Nested type: CallLongMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate long CallLongMethod(
IntPtr thiz, IntPtr obj, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualBooleanMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte CallNonvirtualBooleanMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualByteMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte CallNonvirtualByteMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualCharMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate ushort CallNonvirtualCharMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualDoubleMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate double CallNonvirtualDoubleMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualFloatMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate float CallNonvirtualFloatMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualIntMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int CallNonvirtualIntMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualLongMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate long CallNonvirtualLongMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualObjectMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr CallNonvirtualObjectMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args
);
#endregion
#region Nested type: CallNonvirtualShortMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate short CallNonvirtualShortMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallNonvirtualVoidMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void CallNonvirtualVoidMethod(IntPtr thiz,
IntPtr obj, IntPtr clazz,
IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallObjectMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr CallObjectMethod(
IntPtr thiz, IntPtr obj, IntPtr methodIdJavaPtr, params Value[] args);
#endregion
#region Nested type: CallShortMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate short CallShortMethod(
IntPtr thiz, IntPtr obj, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticBooleanMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte CallStaticBooleanMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticByteMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte CallStaticByteMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticCharMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate ushort CallStaticCharMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticDoubleMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate double CallStaticDoubleMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticFloatMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate float CallStaticFloatMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticIntMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int CallStaticIntMethod(
IntPtr thiz, IntPtr obj, IntPtr methodIdJavaPtr, params Value[] args);
#endregion
#region Nested type: CallStaticLongMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate long CallStaticLongMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticObjectMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr CallStaticObjectMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticShortMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate short CallStaticShortMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: CallStaticVoidMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate JNIResult CallStaticVoidMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodIdJavaPtr, params Value[] args);
#endregion
#region Nested type: CallVoidMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate JNIResult CallVoidMethod(
IntPtr thiz, IntPtr obj, IntPtr methodIdJavaPtr, params Value[] args);
#endregion
#region Nested type: DefineClass
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr DefineClass(IntPtr thiz,
IntPtr name /*const char* */, IntPtr loader,
IntPtr buf /*const byte **/, int len);
#endregion
#region Nested type: DeleteGlobalRef
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
[SuppressUnmanagedCodeSecurity]
internal delegate void DeleteGlobalRef(IntPtr thiz, IntPtr gref);
#endregion
#region Nested type: DeleteLocalRef
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
[SuppressUnmanagedCodeSecurity]
internal delegate void DeleteLocalRef(IntPtr thiz, IntPtr lref);
#endregion
#region Nested type: DeleteWeakGlobalRef
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void DeleteWeakGlobalRef(IntPtr thiz, IntPtr wref);
#endregion
#region Nested type: EnsureLocalCapacity
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int EnsureLocalCapacity(IntPtr thiz, int capacity);
#endregion
#region Nested type: ExceptionCheck
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte ExceptionCheck(IntPtr thiz);
#endregion
#region Nested type: ExceptionClear
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ExceptionClear(IntPtr thiz);
#endregion
#region Nested type: ExceptionDescribe
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ExceptionDescribe(IntPtr thiz);
#endregion
#region Nested type: ExceptionOccurred
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr ExceptionOccurred(IntPtr thiz);
#endregion
#region Nested type: FatalError
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void FatalError(IntPtr thiz, IntPtr msg);
#endregion
#region Nested type: FindClass
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr FindClass(IntPtr thiz, [MarshalAs(UnmanagedType.LPStr)] string name);
#endregion
#region Nested type: FromReflectedField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr FromReflectedField(IntPtr thiz, IntPtr field);
#endregion
#region Nested type: FromReflectedMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr FromReflectedMethod(IntPtr thiz, IntPtr method);
#endregion
#region Nested type: GetArrayLength
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int GetArrayLength(
IntPtr thiz, IntPtr array);
#endregion
#region Nested type: GetBooleanArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte* GetBooleanArrayElements(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetBooleanArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetBooleanArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, byte* buf);
#endregion
#region Nested type: GetBooleanField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte GetBooleanField(IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetByteArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte* GetByteArrayElements(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetByteArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetByteArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, byte* buf);
#endregion
#region Nested type: GetByteField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte GetByteField(IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetCharArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate ushort* GetCharArrayElements(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetCharArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetCharArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, char* buf);
#endregion
#region Nested type: GetCharField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate ushort GetCharField(IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetDirectBufferAddress
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetDirectBufferAddress(IntPtr thiz, IntPtr buf);
#endregion
#region Nested type: GetDirectBufferCapacity
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate long GetDirectBufferCapacity(IntPtr thiz, IntPtr buf);
#endregion
#region Nested type: GetDoubleArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate double* GetDoubleArrayElements(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetDoubleArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetDoubleArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, double* buf
/* double* */);
#endregion
#region Nested type: GetDoubleField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate double GetDoubleField(IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetFieldID
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetFieldID(
IntPtr thiz, IntPtr clazz, [MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] string sig);
#endregion
#region Nested type: GetFloatArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate float* GetFloatArrayElements(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetFloatArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetFloatArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, float* buf);
#endregion
#region Nested type: GetFloatField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate float GetFloatField(IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetIntArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int* GetIntArrayElements(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetIntArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetIntArrayRegion(IntPtr thiz, IntPtr array, int start, int len, int* buf);
#endregion
#region Nested type: GetIntField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int GetIntField(IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetJavaVM
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate JNIResult GetJavaVM(IntPtr thiz, out IntPtr vm);
#endregion
#region Nested type: GetLongArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate long* GetLongArrayElements(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetLongArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetLongArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, long* buf);
#endregion
#region Nested type: GetLongField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate long GetLongField(IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetMethodID
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetMethodID(
IntPtr thiz, IntPtr clazz, [MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] string sig);
#endregion
#region Nested type: GetObjectArrayElement
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetObjectArrayElement(
IntPtr thiz, IntPtr array, int index);
#endregion
#region Nested type: GetObjectClass
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetObjectClass(IntPtr thiz, IntPtr obj);
#endregion
#region Nested type: GetObjectField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetObjectField(
IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetPrimitiveArrayCritical
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void* GetPrimitiveArrayCritical(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetShortArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate short* GetShortArrayElements(IntPtr thiz, IntPtr array, byte* isCopy);
#endregion
#region Nested type: GetShortArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetShortArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, short* buf);
#endregion
#region Nested type: GetShortField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate short GetShortField(IntPtr thiz, IntPtr obj, IntPtr fieldID);
#endregion
#region Nested type: GetStaticBooleanField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte GetStaticBooleanField(IntPtr thiz, IntPtr clazz, IntPtr fieldID);
#endregion
#region Nested type: GetStaticByteField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte GetStaticByteField(IntPtr thiz, IntPtr clazz, IntPtr fieldID);
#endregion
#region Nested type: GetStaticCharField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate ushort GetStaticCharField(IntPtr thiz, IntPtr clazz, IntPtr fieldID);
#endregion
#region Nested type: GetStaticDoubleField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate double GetStaticDoubleField(IntPtr thiz, IntPtr clazz, IntPtr fieldID);
#endregion
#region Nested type: GetStaticFieldID
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetStaticFieldID(
IntPtr thiz, IntPtr clazz, [MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] string sig);
#endregion
#region Nested type: GetStaticFloatField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate float GetStaticFloatField(IntPtr thiz, IntPtr clazz, IntPtr fieldID);
#endregion
#region Nested type: GetStaticIntField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int GetStaticIntField(IntPtr thiz, IntPtr clazz, IntPtr fieldID);
#endregion
#region Nested type: GetStaticLongField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate long GetStaticLongField(IntPtr thiz, IntPtr clazz, IntPtr fieldID);
#endregion
#region Nested type: GetStaticMethodID
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetStaticMethodID(
IntPtr thiz, IntPtr clazz, [MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] string sig);
#endregion
#region Nested type: GetStaticObjectField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetStaticObjectField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID
);
#endregion
#region Nested type: GetStaticShortField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate short GetStaticShortField(IntPtr thiz, IntPtr clazz, IntPtr fieldID);
#endregion
#region Nested type: GetStringChars
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetStringChars(IntPtr thiz, IntPtr str, byte* isCopy);
#endregion
#region Nested type: GetStringCritical
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetStringCritical(IntPtr thiz, IntPtr str, byte* isCopy);
#endregion
#region Nested type: GetStringLength
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int GetStringLength(IntPtr thiz, IntPtr str);
#endregion
#region Nested type: GetStringRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetStringRegion(IntPtr thiz, IntPtr str, int start, int len, char* buf);
#endregion
#region Nested type: GetStringUTFChars
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr GetStringUTFChars(IntPtr thiz, IntPtr str, IntPtr isCopy /*byte * */);
#endregion
#region Nested type: GetStringUTFLength
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int GetStringUTFLength(IntPtr thiz, IntPtr str);
#endregion
#region Nested type: GetStringUTFRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void GetStringUTFRegion(IntPtr thiz, IntPtr str, int start, int len, char* buf);
#endregion
#region Nested type: GetVersion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int GetVersion(IntPtr thiz);
#endregion
#region Nested type: IsSameObject
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate byte IsSameObject(
IntPtr thiz, IntPtr o1, IntPtr o2);
#endregion
#region Nested type: MonitorEnter
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int MonitorEnter(IntPtr thiz, IntPtr obj);
#endregion
#region Nested type: MonitorExit
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int MonitorExit(IntPtr thiz, IntPtr obj);
#endregion
#region Nested type: NewBooleanArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewBooleanArray(IntPtr thiz, int len);
#endregion
#region Nested type: NewByteArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewByteArray(IntPtr thiz, int len);
#endregion
#region Nested type: NewCharArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewCharArray(IntPtr thiz, int len);
#endregion
#region Nested type: NewDirectByteBuffer
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewDirectByteBuffer(IntPtr thiz, IntPtr address, long capacity);
#endregion
#region Nested type: NewDoubleArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewDoubleArray(IntPtr thiz, int len);
#endregion
#region Nested type: NewFloatArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewFloatArray(IntPtr thiz, int len);
#endregion
#region Nested type: NewGlobalRef
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
[SuppressUnmanagedCodeSecurity]
internal delegate IntPtr NewGlobalRef(IntPtr thiz, IntPtr lobj);
#endregion
#region Nested type: NewIntArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewIntArray(IntPtr thiz, int len);
#endregion
#region Nested type: NewLocalRef
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewLocalRef(IntPtr thiz, IntPtr reference);
#endregion
#region Nested type: NewLongArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewLongArray(IntPtr thiz, int len);
#endregion
#region Nested type: NewObject
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewObject(
IntPtr thiz, IntPtr clazz, IntPtr methodID, params Value[] args);
#endregion
#region Nested type: NewObjectArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewObjectArray(
IntPtr thiz, int len, IntPtr clazz, IntPtr init);
#endregion
#region Nested type: NewShortArray
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewShortArray(IntPtr thiz, int len);
#endregion
#region Nested type: NewString
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewString(IntPtr thiz, IntPtr unicode, int len);
#endregion
#region Nested type: NewStringUTF
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewStringUTF(IntPtr thiz, IntPtr utf /* const char * */);
#endregion
#region Nested type: NewWeakGlobalRef
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr NewWeakGlobalRef(IntPtr thiz, IntPtr obj);
#endregion
#region Nested type: PopLocalFrame
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr PopLocalFrame(IntPtr thiz, IntPtr result);
#endregion
#region Nested type: PushLocalFrame
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate int PushLocalFrame(IntPtr thiz, int capacity);
#endregion
#region Nested type: RegisterNatives
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate JNIResult RegisterNatives(
IntPtr thiz, IntPtr clazz, JNINativeMethod* methods, int nMethods);
#endregion
#region Nested type: UnregisterNatives
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate JNIResult UnregisterNatives(IntPtr thiz, IntPtr clazz);
#endregion
#region Nested type: ReleaseBooleanArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseBooleanArrayElements(
IntPtr thiz, IntPtr array, byte* elems, int mode);
#endregion
#region Nested type: ReleaseByteArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseByteArrayElements(IntPtr thiz, IntPtr array, byte* elems, int mode);
#endregion
#region Nested type: ReleaseCharArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseCharArrayElements(
IntPtr thiz, IntPtr array, ushort* elems, int mode);
#endregion
#region Nested type: ReleaseDoubleArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseDoubleArrayElements(
IntPtr thiz, IntPtr array, double* elems, int mode);
#endregion
#region Nested type: ReleaseFloatArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseFloatArrayElements(
IntPtr thiz, IntPtr array, float* elems, int mode);
#endregion
#region Nested type: ReleaseIntArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseIntArrayElements(IntPtr thiz, IntPtr array, int* elems, int mode);
#endregion
#region Nested type: ReleaseLongArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseLongArrayElements(IntPtr thiz, IntPtr array, long* elems, int mode);
#endregion
#region Nested type: ReleasePrimitiveArrayCritical
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleasePrimitiveArrayCritical(
IntPtr thiz, IntPtr array, void* carray, int mode);
#endregion
#region Nested type: ReleaseShortArrayElements
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseShortArrayElements(
IntPtr thiz, IntPtr array, short* elems, int mode);
#endregion
#region Nested type: ReleaseStringChars
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseStringChars(IntPtr thiz, IntPtr str, IntPtr chars);
#endregion
#region Nested type: ReleaseStringCritical
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseStringCritical(IntPtr thiz, IntPtr str, IntPtr cstring
/*const char * */);
#endregion
#region Nested type: ReleaseStringUTFChars
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void ReleaseStringUTFChars(IntPtr thiz, IntPtr str, IntPtr chars
/* const char* */);
#endregion
#region Nested type: SetBooleanArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetBooleanArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, byte* buf
/* const byte * */);
#endregion
#region Nested type: SetBooleanField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetBooleanField(
IntPtr thiz, IntPtr obj, IntPtr fieldID, byte val);
#endregion
#region Nested type: SetByteArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetByteArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, byte* buf
/* const byte * */);
#endregion
#region Nested type: SetByteField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetByteField(IntPtr thiz, IntPtr obj, IntPtr fieldID, byte val);
#endregion
#region Nested type: SetCharArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetCharArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, char* buf
/* const ushort * */);
#endregion
#region Nested type: SetCharField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetCharField(IntPtr thiz, IntPtr obj, IntPtr fieldID, ushort val
);
#endregion
#region Nested type: SetDoubleArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetDoubleArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, double* buf
/* const double * */);
#endregion
#region Nested type: SetDoubleField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetDoubleField(
IntPtr thiz, IntPtr obj, IntPtr fieldID, double val);
#endregion
#region Nested type: SetFloatArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetFloatArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, float* buf
/* const float * */);
#endregion
#region Nested type: SetFloatField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetFloatField(IntPtr thiz, IntPtr obj, IntPtr fieldID, float val
);
#endregion
#region Nested type: SetIntArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetIntArrayRegion(IntPtr thiz, IntPtr array, int start, int len, int* buf
/* const int * */);
#endregion
#region Nested type: SetIntField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetIntField(IntPtr thiz, IntPtr obj, IntPtr fieldID, int val);
#endregion
#region Nested type: SetLongArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetLongArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, long* buf
/* const long * */);
#endregion
#region Nested type: SetLongField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetLongField(IntPtr thiz, IntPtr obj, IntPtr fieldID, long val);
#endregion
#region Nested type: SetObjectArrayElement
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetObjectArrayElement(
IntPtr thiz, IntPtr array, int index, IntPtr val);
#endregion
#region Nested type: SetObjectField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetObjectField(
IntPtr thiz, IntPtr obj, IntPtr fieldID, IntPtr val);
#endregion
#region Nested type: SetShortArrayRegion
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetShortArrayRegion(
IntPtr thiz, IntPtr array, int start, int len, short* buf
/* const short * */);
#endregion
#region Nested type: SetShortField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetShortField(IntPtr thiz, IntPtr obj, IntPtr fieldID, short val
);
#endregion
#region Nested type: SetStaticBooleanField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticBooleanField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, byte value);
#endregion
#region Nested type: SetStaticByteField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticByteField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, byte value);
#endregion
#region Nested type: SetStaticCharField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticCharField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, ushort value);
#endregion
#region Nested type: SetStaticDoubleField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticDoubleField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, double value);
#endregion
#region Nested type: SetStaticFloatField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticFloatField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, float value);
#endregion
#region Nested type: SetStaticIntField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticIntField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, int value);
#endregion
#region Nested type: SetStaticLongField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticLongField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, long value);
#endregion
#region Nested type: SetStaticObjectField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticObjectField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, IntPtr value);
#endregion
#region Nested type: SetStaticShortField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void SetStaticShortField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, short value);
#endregion
#region Nested type: Throw
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate JNIResult Throw(IntPtr thiz, IntPtr obj);
#endregion
#region Nested type: ThrowNew
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate JNIResult ThrowNew(IntPtr thiz, IntPtr clazz, IntPtr msg);
#endregion
#region Nested type: ToReflectedField
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr ToReflectedField(
IntPtr thiz, IntPtr clazz, IntPtr fieldID, byte isStatic);
#endregion
#region Nested type: ToReflectedMethod
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr ToReflectedMethod(
IntPtr thiz, IntPtr clazz, IntPtr methodID, byte isStatic);
#endregion
#region Nested type: UnregisterJavaPtrs
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate JNIResult UnregisterJavaPtrs(IntPtr thiz, IntPtr clazz);
#endregion
}
#endregion
}
} | {
"pile_set_name": "Github"
} |
// Dummy main implementation for noop-ing tests.
// TODO(htuch): remove when we have a solution for
// https://github.com/bazelbuild/bazel/issues/3510
// NOLINT(namespace-envoy)
int main(int /*argc*/, char** /*argv*/) { return 0; }
| {
"pile_set_name": "Github"
} |
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright (c) 2004-2008 Apple Inc. All Rights Reserved.
*
* Export of this software from the United States of America may require
* a specific license from the United States Government. It is the
* responsibility of any person or organization contemplating export to
* obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of Apple Inc. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Apple Inc. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
*/
/*
* pkinit_server.h - Server side routines for PKINIT
*
* Created 21 May 2004 by Doug Mitchell at Apple.
*/
#ifndef _PKINIT_SERVER_H_
#define _PKINIT_SERVER_H_
#include "krb5.h"
#include "pkinit_cms.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Parse PA-PK-AS-REQ message. Optionally evaluates the message's certificate chain
* if cert_status is non-NULL. Optionally returns various components.
*/
krb5_error_code krb5int_pkinit_as_req_parse(
krb5_context context,
const krb5_data *as_req,
krb5_timestamp *kctime, /* optionally RETURNED */
krb5_ui_4 *cusec, /* microseconds, optionally RETURNED */
krb5_ui_4 *nonce, /* optionally RETURNED */
krb5_checksum *pa_cksum, /* optional, contents mallocd and RETURNED */
krb5int_cert_sig_status *cert_status, /* optionally RETURNED */
krb5_ui_4 *num_cms_types, /* optionally RETURNED */
krb5int_algorithm_id **cms_types, /* optionally mallocd and RETURNED */
/*
* Cert fields, all optionally RETURNED.
*
* signer_cert is the full X.509 leaf cert from the incoming SignedData.
* all_certs is an array of all of the certs in the incoming SignedData,
* in full X.509 form.
*/
krb5_data *signer_cert, /* content mallocd */
krb5_ui_4 *num_all_certs, /* sizeof *all_certs */
krb5_data **all_certs, /* krb5_data's and their content mallocd */
/*
* Array of trustedCertifiers, optionally RETURNED. These are DER-encoded
* issuer/serial numbers.
*/
krb5_ui_4 *num_trusted_CAs, /* sizeof *trustedCAs */
krb5_data **trusted_CAs, /* krb5_data's and their content mallocd */
/* KDC cert specified by client as kdcPkId. DER-encoded issuer/serial number. */
krb5_data *kdc_cert);
/*
* Create a PA-PK-AS-REP message, public key (no Diffie Hellman) version.
*
* PA-PK-AS-REP is based on ReplyKeyPack like so:
*
* PA-PK-AS-REP ::= EnvelopedData(SignedData(ReplyKeyPack))
*/
krb5_error_code krb5int_pkinit_as_rep_create(
krb5_context context,
const krb5_keyblock *key_block,
const krb5_checksum *checksum, /* checksum of corresponding AS-REQ */
krb5_pkinit_signing_cert_t signer_cert, /* server's cert */
krb5_boolean include_server_cert, /* include signer_cert in SignerInfo */
const krb5_data *recipient_cert, /* client's cert */
/*
* These correspond to the same out-parameters from
* krb5int_pkinit_as_req_parse(). All are optional.
*/
krb5_ui_4 num_cms_types,
const krb5int_algorithm_id *cms_types,
krb5_ui_4 num_trusted_CAs,
krb5_data *trusted_CAs,
krb5_data *kdc_cert,
/* result here, mallocd and RETURNED */
krb5_data *as_rep);
#ifdef __cplusplus
}
#endif
#endif /* _PKINIT_SERVER_H_ */
| {
"pile_set_name": "Github"
} |
SOURCES = \
c_037.nls \
c_10000.nls \
c_10001.nls \
c_10002.nls \
c_10003.nls \
c_10004.nls \
c_10005.nls \
c_10006.nls \
c_10007.nls \
c_10008.nls \
c_10010.nls \
c_10017.nls \
c_10021.nls \
c_10029.nls \
c_10079.nls \
c_10081.nls \
c_10082.nls \
c_1026.nls \
c_1250.nls \
c_1251.nls \
c_1252.nls \
c_1253.nls \
c_1254.nls \
c_1255.nls \
c_1256.nls \
c_1257.nls \
c_1258.nls \
c_1361.nls \
c_20127.nls \
c_20866.nls \
c_20932.nls \
c_21866.nls \
c_28591.nls \
c_28592.nls \
c_28593.nls \
c_28594.nls \
c_28595.nls \
c_28596.nls \
c_28597.nls \
c_28598.nls \
c_28599.nls \
c_28603.nls \
c_28605.nls \
c_437.nls \
c_500.nls \
c_737.nls \
c_775.nls \
c_850.nls \
c_852.nls \
c_855.nls \
c_857.nls \
c_860.nls \
c_861.nls \
c_862.nls \
c_863.nls \
c_864.nls \
c_865.nls \
c_866.nls \
c_869.nls \
c_874.nls \
c_875.nls \
c_932.nls \
c_936.nls \
c_949.nls \
c_950.nls \
l_intl.nls \
normidna.nls \
normnfc.nls \
normnfd.nls \
normnfkc.nls \
normnfkd.nls \
sortdefault.nls
| {
"pile_set_name": "Github"
} |
<?php
/**
* @author QiangYu
*
* 配置 360 一站通登陆
*
* */
namespace Controller\Thirdpart\Dev360Auth;
use Core\Helper\Utility\Validator;
use Plugin\Thirdpart\Dev360Auth\Dev360AuthPlugin;
class Configure extends \Controller\AuthController
{
public function get($f3)
{
// 权限检查
$this->requirePrivilege('manage_plugin_plugin_configure');
// 取所有的设置值
$optionValueArray = array();
// shop
$optionValueArray['shop_dev360auth_app_id'] = Dev360AuthPlugin::getOptionValue('shop_dev360auth_app_id');
$optionValueArray['shop_dev360auth_app_key'] = Dev360AuthPlugin::getOptionValue('shop_dev360auth_app_key');
$optionValueArray['shop_dev360auth_app_secrect'] =
Dev360AuthPlugin::getOptionValue('shop_dev360auth_app_secrect');
// aimeidaren
$optionValueArray['aimeidaren_dev360auth_app_id'] =
Dev360AuthPlugin::getOptionValue('aimeidaren_dev360auth_app_id');
$optionValueArray['aimeidaren_dev360auth_app_key'] =
Dev360AuthPlugin::getOptionValue('aimeidaren_dev360auth_app_key');
$optionValueArray['aimeidaren_dev360auth_app_secrect'] =
Dev360AuthPlugin::getOptionValue('aimeidaren_dev360auth_app_secrect');
global $smarty;
$smarty->assign($optionValueArray);
out_display:
$smarty->display('dev360auth_configure.tpl', 'get');
}
public function post($f3)
{
// 权限检查
$this->requirePrivilege('manage_plugin_plugin_configure');
global $smarty;
// 参数验证
$validator = new Validator($f3->get('POST'));
// shop
$shop_dev360auth_app_id = $validator->required()->digits()->validate('shop_dev360auth_app_id');
$shop_dev360auth_app_key = $validator->required()->validate('shop_dev360auth_app_key');
$shop_dev360auth_app_secrect = $validator->required()->validate('shop_dev360auth_app_secrect');
// aimeidaren
$aimeidaren_dev360auth_app_id = $validator->required()->digits()->validate('aimeidaren_dev360auth_app_id');
$aimeidaren_dev360auth_app_key = $validator->required()->validate('aimeidaren_dev360auth_app_key');
$aimeidaren_dev360auth_app_secrect = $validator->required()->validate('aimeidaren_dev360auth_app_secrect');
if (!$this->validate($validator)) {
goto out_display;
}
// 保存设置 shop
Dev360AuthPlugin::saveOptionValue('shop_dev360auth_app_id', $shop_dev360auth_app_id);
Dev360AuthPlugin::saveOptionValue('shop_dev360auth_app_key', $shop_dev360auth_app_key);
Dev360AuthPlugin::saveOptionValue('shop_dev360auth_app_secrect', $shop_dev360auth_app_secrect);
// 保存设置 aimeidaren
Dev360AuthPlugin::saveOptionValue('aimeidaren_dev360auth_app_id', $aimeidaren_dev360auth_app_id);
Dev360AuthPlugin::saveOptionValue('aimeidaren_dev360auth_app_key', $aimeidaren_dev360auth_app_key);
Dev360AuthPlugin::saveOptionValue('aimeidaren_dev360auth_app_secrect', $aimeidaren_dev360auth_app_secrect);
$this->addFlashMessage('保存设置成功');
out_display:
$smarty->display('dev360auth_configure.tpl', 'post');
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `mul_with_overflow` fn in crate `std`.">
<meta name="keywords" content="rust, rustlang, rust-lang, mul_with_overflow">
<title>std::intrinsics::mul_with_overflow - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../../std/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a>
<p class='location'><a href='../index.html'>std</a>::<wbr><a href='index.html'>intrinsics</a></p><script>window.sidebarCurrent = {name: 'mul_with_overflow', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../index.html'>std</a>::<wbr><a href='index.html'>intrinsics</a>::<wbr><a class='fn' href=''>mul_with_overflow</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-4983' class='srclink' href='../../core/intrinsics/fn.mul_with_overflow.html?gotosrc=4983' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub unsafe extern "rust-intrinsic" fn mul_with_overflow<T>(x: T, y: T) -> <a class='primitive' href='../primitive.tuple.html'>(T, <a class='primitive' href='../primitive.bool.html'>bool</a>)</a></pre><div class='stability'><em class='stab unstable'>Unstable (<code>core_intrinsics</code> <a href="https://github.com/rust-lang/rust/issues/0">#0</a>)<p>: intrinsics are unlikely to ever be stabilized, instead they should be used through stabilized interfaces in the rest of the standard library</p>
</em></div><div class='docblock'><p>Performs checked integer multiplication</p>
</div></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "std";
window.playgroundUrl = "https://play.rust-lang.org/";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script src="../../playpen.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html> | {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<html><head>
<meta charset="utf-8">
<title>CSS Grid Test: 'stretch' of image with zero ratio</title>
<link rel="author" title="Mats Palmgren" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1315857">
<link rel="help" href="https://drafts.csswg.org/css-align-3/#valdef-justify-self-stretch">
<link rel="match" href="grid-item-intrinsic-ratio-stretch-007-ref.html">
<style type="text/css">
body,html { color:black; background:white; font:16px/1 monospace; padding:0; margin:0; }
.grid {
display: grid;
float: left;
grid: auto-flow auto / minmax(auto, 10px) minmax(auto, 30px) minmax(auto, 10px) minmax(auto, 30px) minmax(auto, 10px) minmax(auto, 30px) minmax(auto, 10px) minmax(auto, 30px) auto auto auto auto;
grid-gap: 5px;
border:1px solid;
}
img:nth-child(1n) { background: blue; }
img:nth-child(2n) { background: grey; }
img:nth-child(3n) { background: tan; }
img:nth-child(4n) { background: black; }
img {
width: 20px;
border: 1px solid;
}
.jend { justify-self: end; }
.aend { align-self: end; }
.end { justify-self: end; align-self: end; }
</style>
</head>
<body>
<div class="grid sz">
<img>
<img>
<img class="jend">
<img class="jend">
<img class="aend">
<img class="aend">
<img class="end">
<img class="end">
<img>
<img class="jend">
<img class="aend">
<img class="end">
</div>
<div class="grid sz t2">
<img>
<img>
<img class="jend">
<img class="jend">
<img class="aend">
<img class="aend">
<img class="end">
<img class="end">
<img>
<img class="jend">
<img class="aend">
<img class="end">
</div>
<div class="grid">
<img>
<img>
<img class="jend">
<img class="jend">
<img class="aend">
<img class="aend">
<img class="end">
<img class="end">
</div>
<div class="grid" style="grid:auto/auto auto">
<img>
<img class="jend">
<img class="aend">
<img class="end">
</div>
<div class="grid" style="grid:minmax(auto,30px) 30px/auto auto">
<img>
<img class="jend">
<img class="aend">
<img class="end">
</div>
<script>
var url = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="0px" height="16px"><circle cx="50%" cy="50%" r="50%" fill="pink"/></svg>'
var imgs = document.querySelectorAll('img');
for (var i = 0; i < imgs.length; ++i) {
var img = imgs[i];
img.src = url;
}
</script>
<!-- For generating image size results in -ref file (try reloading a few times if you see all zeros)
<script>
document.body.clientHeight;
var imgs = document.querySelectorAll('img');
var s = ' [\n';
for (var i = 0; i < imgs.length; ++i) {
s += " ['"+ imgs[i].width + "px', '" + imgs[i].height + "px'],\n";
}
s += ']';
console.log(s)
</script>
-->
</body>
</html>
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
#
# Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
# Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://opensource.org/licenses/MIT
#
# 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.
#
import json
import logging
from django.db import models
from django.utils.translation import ugettext_lazy as _
from backend.apps.configuration.models import BaseModel
logger = logging.getLogger(__name__)
class NodeOperType:
BkeInstall = "bke_install"
NodeInstall = "initialize"
NodeRemove = "remove"
InitialCheck = 'initial_check'
SoInitial = 'so_initial'
NodeReinstall = 'reinstall'
class ClusterOperType:
ClusterInstall = 'initialize'
ClusterRemove = 'remove'
InitialCheck = 'initial_check'
SoInitial = 'so_initial'
ClusterReinstall = 'reinstall'
ClusterUpgrade = "upgrade"
ClusterReupgrade = "reupgrade"
class CommonStatus:
InitialChecking = "initial_checking"
InitialCheckFailed = "check_failed"
Uninitialized = "uninitialized"
Initializing = "initializing"
InitialFailed = "initial_failed"
Normal = "normal"
Removing = "removing"
Removed = "removed"
RemoveFailed = "remove_failed"
SoInitial = "so_initializing"
SoInitialFailed = "so_init_failed"
ScheduleFailed = "schedule_failed"
Scheduling = "scheduling"
DeleteFailed = "delete_failed"
class ClusterStatus:
Uninitialized = "uninitialized"
Initializing = "initializing"
InitialFailed = "initial_failed"
Normal = "normal"
Upgrading = "upgrading"
UpgradeFailed = "upgrade_failed"
class NodeStatus:
Uninitialized = "uninitialized"
Initializing = "initializing"
InitialFailed = "initial_failed"
Normal = "normal"
ToRemoved = "to_removed"
Removable = "removable"
Removing = "removing"
RemoveFailed = "remove_failed"
Removed = "removed"
BkeInstall = "bke_installing"
BkeFailed = "bke_failed"
NotReady = "not_ready"
class GcloudPollingTask(models.Model):
project_id = models.CharField(max_length=64)
task_id = models.CharField(max_length=64, null=True)
token = models.CharField(max_length=64, null=True)
operator = models.CharField(max_length=16, null=True)
params = models.TextField()
is_finished = models.BooleanField(default=False)
is_polling = models.BooleanField(default=False)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
cluster_id = models.CharField(max_length=32)
log = models.TextField()
class Meta:
abstract = True
def set_is_finish(self, flag):
self.is_finished = flag
self.save()
def set_is_polling(self, flag):
self.is_polling = flag
self.save()
def set_status(self, status):
self.status = status
self.save()
def set_finish_polling_status(self, finish_flag, polling_flag, status):
self.is_finished = finish_flag
self.is_polling = polling_flag
self.status = status
self.save()
def set_task_id(self, task_id):
self.task_id = task_id
self.save()
def set_params(self, params):
self.params = json.dumps(params)
self.save()
@property
def log_params(self):
try:
return json.loads(self.params)
except Exception:
return {}
def activate_polling(self):
from backend.celery_app.tasks import cluster
from celery import chain
chain(cluster.polling_task.s(self.__class__.__name__, self.pk),
cluster.chain_polling_bke_status.s()).apply_async()
def polling_task(self):
"""轮训任务
"""
from backend.apps.cluster.views_bk import tasks
tasks.polling_task.delay(self.__class__.__name__, self.pk)
class ClusterInstallLog(GcloudPollingTask):
OPER_TYPE = (
("initialize", _("初始化集群")),
("reinstall", _("重新初始化集群")),
("initial_check", _("前置检查")),
("removing", _("删除集群")),
("so_initial", _("SO 机器初始化")),
("remove", _("删除集群")),
("upgrade", _("升级集群版本"))
)
status = models.CharField(max_length=32, null=True, blank=True)
oper_type = models.CharField(max_length=16, choices=OPER_TYPE, default="initialize")
def cluster_check_and_init_polling(self):
"""集群前置检查&初始化
"""
from backend.celery_app.tasks import cluster
from celery import chain
chain(cluster.polling_initial_task.s(self.__class__.__name__, self.pk),
cluster.so_init.s(),
cluster.polling_so_init.s(),
cluster.exec_bcs_task.s(),
cluster.chain_polling_task.s(self.__class__.__name__)).apply_async()
def cluster_so_and_init_polling(self):
"""集群so&初始化
"""
from backend.celery_app.tasks import cluster
from celery import chain
chain(cluster.polling_so_init.s(None, self.pk, self.__class__.__name__),
cluster.exec_bcs_task.s(),
cluster.chain_polling_task.s(self.__class__.__name__)).apply_async()
def delete_cluster(self):
"""删除集群
"""
from backend.celery_app.tasks import cluster
cluster.delete_cluster_task.delay(self.__class__.__name__, self.pk)
class NodeUpdateLog(GcloudPollingTask):
OPER_TYPE = (
("initialize", _("初始化节点")),
("reinstall", _("重新初始化节点")),
("removing", _("删除节点")),
("initial_check", _("前置检查")),
("so_initial", _("SO 机器初始化")),
("bke_install", _("安装BKE")),
("remove", _("删除节点")),
('bind_lb', _("绑定LB")),
('init_env', _("初始化环境"))
)
# node_id = models.CharField(max_length=32)
node_id = models.TextField()
status = models.CharField(max_length=32, null=True, blank=True)
oper_type = models.CharField(max_length=16, choices=OPER_TYPE, default="initialize")
def node_check_and_init_polling(self):
"""节点前置检查&初始化
"""
from backend.celery_app.tasks import cluster
from celery import chain
chain(cluster.polling_initial_task.s(self.__class__.__name__, self.pk),
cluster.so_init.s(),
cluster.polling_so_init.s(),
cluster.node_exec_bcs_task.s(),
cluster.chain_polling_task.s(self.__class__.__name__),
cluster.chain_polling_bke_status.s()).apply_async()
def node_so_and_init_polling(self):
"""节点so&初始化
"""
from backend.celery_app.tasks import cluster
from celery import chain
chain(cluster.polling_so_init.s(None, self.pk, self.__class__.__name__),
cluster.node_exec_bcs_task.s(),
cluster.chain_polling_task.s(self.__class__.__name__),
cluster.chain_polling_bke_status.s()).apply_async()
def bke_polling(self):
from backend.celery_app.tasks import cluster
cluster.polling_bke_status.delay(self.pk)
def node_force_delete_polling(self):
"""强制删除节点
"""
from backend.celery_app.tasks import cluster
from celery import chain
chain(
cluster.force_delete_node.s(self.__class__.__name__, self.pk),
cluster.delete_cluster_node.s(),
cluster.delete_cluster_node_polling.s()
).apply_async()
def log_factory(log_type):
if log_type == "ClusterInstallLog":
return ClusterInstallLog
elif log_type == "NodeUpdateLog":
return NodeUpdateLog
class NodeLabel(BaseModel):
project_id = models.CharField(_("项目ID"), max_length=32)
cluster_id = models.CharField(_("集群ID"), max_length=32)
node_id = models.IntegerField()
labels = models.TextField()
@property
def node_labels(self):
return json.loads(self.labels)
class Meta:
db_table = "node_label"
unique_together = (("node_id",))
| {
"pile_set_name": "Github"
} |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Unit tests for user_wrapper.py functions.
"""
import pytest
from botocore.exceptions import ClientError
import user_wrapper
@pytest.mark.parametrize("error_code", [None, "EntityAlreadyExists"])
def test_create_user(make_stubber, make_unique_name, error_code):
iam_stubber = make_stubber(user_wrapper.iam.meta.client)
user_name = make_unique_name('user-')
iam_stubber.stub_create_user(user_name, error_code=error_code)
if error_code is None:
user = user_wrapper.create_user(user_name)
assert user.name == user_name
else:
with pytest.raises(ClientError) as exc_info:
user_wrapper.create_user(user_name)
assert exc_info.value.response['Error']['Code'] == error_code
@pytest.mark.parametrize("error_code", [None, "DeleteConflict"])
def test_delete_user(make_stubber, make_unique_name, error_code):
iam_stubber = make_stubber(user_wrapper.iam.meta.client)
user_name = make_unique_name('user-')
iam_stubber.stub_delete_user(user_name, error_code=error_code)
if error_code is None:
user_wrapper.delete_user(user_name)
else:
with pytest.raises(ClientError) as exc_info:
user_wrapper.delete_user(user_name)
assert exc_info.value.response['Error']['Code'] == error_code
@pytest.mark.parametrize(
"user_count,error_code", [(5, None), (0, None), (3, "TestException")])
def test_list_users(make_stubber, user_count, error_code):
iam_stubber = make_stubber(user_wrapper.iam.meta.client)
user_count = 5
iam_stubber.stub_list_users(user_count, error_code=error_code)
if error_code is None:
got_users = user_wrapper.list_users()
assert len(got_users) == user_count
else:
with pytest.raises(ClientError) as exc_info:
user_wrapper.list_users()
assert exc_info.value.response['Error']['Code'] == error_code
@pytest.mark.parametrize(
"error_code", [None, "EntityTemporarilyUnmodifiable"])
def test_update_user(make_stubber, make_unique_name, error_code):
iam_stubber = make_stubber(user_wrapper.iam.meta.client)
old_name = make_unique_name('user-')
new_name = make_unique_name('user-')
iam_stubber.stub_update_user(old_name, new_name, error_code=error_code)
if error_code is None:
got_update = user_wrapper.update_user(old_name, new_name)
assert got_update.name == new_name
else:
with pytest.raises(ClientError) as exc_info:
user_wrapper.update_user(old_name, new_name)
assert exc_info.value.response['Error']['Code'] == error_code
@pytest.mark.parametrize("error_code", [None, "PolicyNotAttachable"])
def test_attach_policy(make_stubber, make_unique_name, error_code):
iam_stubber = make_stubber(user_wrapper.iam.meta.client)
user_name = make_unique_name('user-')
policy_arn = 'arn:aws:iam:::test/policy'
iam_stubber.stub_attach_user_policy(user_name, policy_arn, error_code=error_code)
if error_code is None:
user_wrapper.attach_policy(user_name, policy_arn)
else:
with pytest.raises(ClientError) as exc_info:
user_wrapper.attach_policy(user_name, policy_arn)
assert exc_info.value.response['Error']['Code'] == error_code
@pytest.mark.parametrize("error_code", [None, "NoSuchEntity"])
def test_detach_policy(make_stubber, make_unique_name, error_code):
iam_stubber = make_stubber(user_wrapper.iam.meta.client)
user_name = make_unique_name('user-')
policy_arn = 'arn:aws:iam:::test/policy'
iam_stubber.stub_detach_user_policy(user_name, policy_arn, error_code=error_code)
if error_code is None:
user_wrapper.detach_policy(user_name, policy_arn)
else:
with pytest.raises(ClientError) as exc_info:
user_wrapper.detach_policy(user_name, policy_arn)
assert exc_info.value.response['Error']['Code'] == error_code
| {
"pile_set_name": "Github"
} |
## What is an input stream?
1. Any data source that generates contiguous data like Standard Input *CORRECT*
2. An input from a user
3. The contents of a file
4. The contents of a website
> **1:** That's right. The input stream can come from any data source. Standard Input is one of them, and you can redirect it to almost any data source like user input, files, website contents and so on.
>
> **2-4:** Yes, that may be an input stream, but it doesn't explain what an input stream is.
>
## What does the program print?
```go
in := bufio.Scanner(os.Stdin)
in.Scan() // user enters: "hi!"
in.Scan() // user enters: "how are you?"
fmt.Println(in.Text())
```
1. "hi" and "how are you?"
2. "hi"
3. "how are you?" *CORRECT*
4. Nothing
> **3:** The Text() method only returns the last scanned token. A token can be a line or a word and so on.
>
## Using bufio.Scanner, how can you detect errors in the input stream?
1. Using the Err() method *CORRECT*
2. Using the Error() method
3. By checking whether the Scanner is nil or not
## How can you configure bufio.Scanner to only scan for the words?
```go
in := bufio.Scanner(os.Stdin)
// ...
```
1. `in = bufio.NewScanner(in, bufio.ScanWords)`
2. `in.Split(bufio.ScanWords)` *CORRECT*
3. `in.ScanWords()`
> **2:** That's right. bufio has a few splitters like ScanWords such as ScanLines (the default), ScanRunes, and so on.
>
## The function uses the "Must" prefix, why?
```go
regexp.MustCompile("...")
```
1. It's only being used for readability purposes
2. It's a guarantee that the function will work, no matter what
3. The function may crash your program *CORRECT*
> **3:** "Must" prefix is a convention. If a function or method may panic (= crash a program), then it's usually being prefixed with a "must" prefix.
> | {
"pile_set_name": "Github"
} |
# Copyright (c) 2016-2020 SUSE LLC
# Licensed under the terms of the MIT license.
Feature: Be able to bootstrap a Salt build host via the GUI
@buildhost
Scenario: Create the bootstrap repository for a Salt client build host
Given I am authorized
When I create the "x86_64" bootstrap repository for "build_host" on the server
@buildhost
Scenario: Bootstrap a SLES build host
Given I am authorized
When I go to the bootstrapping page
Then I should see a "Bootstrap Minions" text
When I enter the hostname of "build_host" as "hostname"
And I enter "22" as "port"
And I enter "root" as "user"
And I enter "linux" as "password"
And I select the hostname of "proxy" from "proxies"
And I click on "Bootstrap"
And I wait until I see "Successfully bootstrapped host!" text
@buildhost
Scenario: Check the new bootstrapped build host in System Overview page
Given I am authorized
When I go to the minion onboarding page
Then I should see a "accepted" text
When I am on the System Overview page
And I wait until I see the name of "build_host", refreshing the page
And I wait until onboarding is completed for "build_host"
Then the Salt master can reach "build_host"
@proxy
@buildhost
Scenario: Check connection from build host to proxy
Given I am on the Systems overview page of this "build_host"
When I follow "Details" in the content area
And I follow "Connection" in the content area
Then I should see "proxy" short hostname
@proxy
@buildhost
Scenario: Check registration on build host of minion
Given I am on the Systems overview page of this "proxy"
When I follow "Details" in the content area
And I follow "Proxy" in the content area
Then I should see "build_host" hostname
@buildhost
Scenario: Detect latest Salt changes on the SLES build host
When I query latest Salt changes on "build_host"
@buildhost
Scenario: Turn the SLES build host into a container build host
Given I am on the Systems overview page of this "build_host"
When I follow "Details" in the content area
And I follow "Properties" in the content area
And I check "container_build_host"
And I click on "Update Properties"
Then I should see a "Container Build Host type has been applied." text
And I should see a "Note: This action will not result in state application" text
And I should see a "To apply the state, either use the states page or run state.highstate from the command line." text
And I should see a "System properties changed" text
@buildhost
Scenario: Turn the SLES build host into a OS image build host
Given I am on the Systems overview page of this "build_host"
When I follow "Details" in the content area
And I follow "Properties" in the content area
And I check "osimage_build_host"
And I click on "Update Properties"
Then I should see a "OS Image Build Host type has been applied." text
And I should see a "Note: This action will not result in state application" text
And I should see a "To apply the state, either use the states page or run state.highstate from the command line." text
And I should see a "System properties changed" text
@buildhost
Scenario: Apply the highstate to the build host
Given I am on the Systems overview page of this "build_host"
When I wait until no Salt job is running on "build_host"
And I enable repositories before installing Docker
And I apply highstate on "build_host"
And I wait until "docker" service is active on "build_host"
And I wait until file "/var/lib/Kiwi/repo/rhn-org-trusted-ssl-cert-osimage-1.0-1.noarch.rpm" exists on "build_host"
And I disable repositories after installing Docker
@buildhost
Scenario: Check that the build host is now a build host
Given I am on the Systems overview page of this "build_host"
Then I should see a "[Container Build Host]" text
Then I should see a "[OS Image Build Host]" text
@buildhost
Scenario: Check events history for failures on SLES build host
Given I am on the Systems overview page of this "build_host"
Then I check for failed events on history event page
| {
"pile_set_name": "Github"
} |
/*#define _GNU_SOURCE*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv) {
int shmsz; /* size of shared mem (default 128) */
int shmid; /* id of shared mem segment */
key_t key; /* 'name' of shared memory */
char *shm, *s; /* pointer to shared mem */
char *str = NULL; /* data to put into the shared mem */
int c;
int errors = 0;
char *out_filename = NULL;
FILE *out_file = NULL;
opterr = 0;
/* Get options */
while ((c = getopt(argc, argv, "k:s:m:o:h")) != -1) {
switch(c) {
case 'k':
if ((key = strtol(optarg, NULL, 10)) < 1000) {
fprintf(stderr, "Key needs to be a 4 digit number.\n");
errors++;
}
break;
case 's':
if ((shmsz = atoi(optarg)) <= 0) {
fprintf(stderr, "Size needs to be an integer.\n");
errors++;
}
break;
case 'o':
out_filename = optarg;
break;
case 'm':
str = optarg;
break;
case 'h':
printf("Usage: shm_server -k <key> -s <size> -m <data>\nex) shm_server -k 1234 -s 128 -m 'Hello World'\n");
return 0;
break;
case '?':
fprintf(stderr, "Illegal argument!\n");
errors++;
break;
}
}
if (!str) {
fprintf(stderr, "No data provided.\n");
errors++;
} else if (strlen(str) >= shmsz) {
fprintf(stderr, "Data too large for shared memory segment.\n");
errors++;
}
if (errors) {
printf("Usage: shm_server -k <key> -s <size> -m <data>\nex) shm_server -k 1234 -s 128 -m 'Hello World'\n");
return 1;
}
/* Create the shared segment */
if ((shmid = shmget(key, shmsz, IPC_CREAT | 0666)) < 0) {
fprintf(stderr, "shmget error\n");
return 1;
}
/* attach segment to our data space */
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
fprintf(stderr, "shmat error\n");
return 1;
}
/* put stuff in memory */
s = shm; /* pointer to memory in shm */
/* Clear memory */
memset(s, 0, shmsz);
/* copy in the data */
strcpy(shm, str);
/* write out the shared memory id */
if (out_filename) {
if ((out_file = fopen(out_filename, "w"))) {
fprintf(out_file, "%d", shmid);
fclose(out_file);
out_file = NULL;
} else {
fprintf(stderr, "Failed to open output file: \"%s\"\n", out_filename);
fprintf(stdout, "%d", shmid);
}
} else {
fprintf(stdout, "%d", shmid);
}
/* wait for input */
fprintf(stderr, "Press any key to exit...");
getchar();
fprintf(stderr, "\n");
return 0;
}
| {
"pile_set_name": "Github"
} |
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
| {
"pile_set_name": "Github"
} |
# Used for CI - It should match environment.yml
# Base conda deps
setuptools
setuptools-scm
pylint
black
flake8
isort
twine
wheel
pytest
pytest-cov
# This project conda deps
cython
numpy
scipy
scikit-learn
matplotlib
notebook
jupyterlab
# This project pip deps
| {
"pile_set_name": "Github"
} |
output.. = bin/
bin.includes = META-INF/,\
.,\
OSGI-INF/
source.. = src/
| {
"pile_set_name": "Github"
} |
/* *********************************************************************** *
* project: org.matsim.*
* *
* *********************************************************************** *
* *
* copyright : (C) 2017 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
/**
*
*/
package org.matsim.contrib.av.intermodal;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.matsim.api.core.v01.Scenario;
import org.matsim.api.core.v01.TransportMode;
import org.matsim.api.core.v01.population.Leg;
import org.matsim.api.core.v01.population.Person;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.population.io.PopulationReader;
import org.matsim.core.router.TripStructureUtils;
import org.matsim.core.router.TripStructureUtils.Trip;
import org.matsim.core.scenario.ScenarioUtils;
import org.matsim.testcases.MatsimTestUtils;
/**
* @author jbischoff
*
*/
public class RunTaxiPTIntermodalExampleIT {
@Rule
public MatsimTestUtils utils = new MatsimTestUtils();
@Test
public void testIntermodalExample() throws MalformedURLException {
URL configUrl = new File(utils.getClassInputDirectory() + "config.xml").toURI().toURL();
new RunTaxiPTIntermodalExample().run(configUrl, false);
// check for intermodal trips
Config config = ConfigUtils.createConfig();
Scenario scenario = ScenarioUtils.createScenario(config);
PopulationReader reader = new PopulationReader(scenario);
reader.readFile("./output/intermodalExample/output_plans.xml.gz");
int intermodalTripCounter = 0;
for (Person person: scenario.getPopulation().getPersons().values()) {
List<Trip> trips = TripStructureUtils.getTrips(person.getSelectedPlan().getPlanElements());
for (Trip trip: trips) {
Map<String, Integer> mode2NumberOfLegs = new HashMap<>();
for (Leg leg: trip.getLegsOnly()) {
if (!mode2NumberOfLegs.containsKey(leg.getMode())) {
mode2NumberOfLegs.put(leg.getMode(), 1);
} else {
mode2NumberOfLegs.put(leg.getMode(), mode2NumberOfLegs.get(leg.getMode()) + 1);
}
}
if (mode2NumberOfLegs.containsKey(TransportMode.taxi) && mode2NumberOfLegs.containsKey(TransportMode.pt)) {
intermodalTripCounter++;
}
}
}
Assert.assertTrue("no pt agent has any intermodal route (=taxi for access or egress to pt)", intermodalTripCounter > 0);
}
}
| {
"pile_set_name": "Github"
} |
# from the create-react-app post-build message:
git commit -am "Save local changes"
git checkout -B gh-pages
git add -f build
git commit -am "Rebuild website"
git filter-branch -f --prune-empty --subdirectory-filter build
git push -f origin gh-pages
git checkout -
| {
"pile_set_name": "Github"
} |
--TEST--
Integration of fixers: phpdoc_no_empty_return,no_empty_phpdoc.
--RULESET--
{"phpdoc_no_empty_return": true, "no_empty_phpdoc": true}
--EXPECT--
<?php
--INPUT--
<?php
/**
* @return void
*/
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build amd64,!gccgo,!appengine
package blake2s
import "golang.org/x/sys/cpu"
var (
useSSE4 = cpu.X86.HasSSE41
useSSSE3 = cpu.X86.HasSSSE3
useSSE2 = cpu.X86.HasSSE2
)
//go:noescape
func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte)
//go:noescape
func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte)
//go:noescape
func hashBlocksSSE4(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte)
func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) {
switch {
case useSSE4:
hashBlocksSSE4(h, c, flag, blocks)
case useSSSE3:
hashBlocksSSSE3(h, c, flag, blocks)
case useSSE2:
hashBlocksSSE2(h, c, flag, blocks)
default:
hashBlocksGeneric(h, c, flag, blocks)
}
}
| {
"pile_set_name": "Github"
} |
# Model
`vc-primitive-model` 组件用于加载基于 glTF 的三维模型。
## 示例
### 加载 glTF 模型
#### 预览
<doc-preview>
<template>
<div class="viewer">
<vc-viewer @ready="ready">
<vc-primitive-model
:url="url"
@readyPromise="readyPromise"
:modelMatrix="modelMatrix"
:scale="10000"
:minimumPixelSize="128"
:maximumScale="200000"
>
</vc-primitive-model>
</vc-viewer>
</div>
</template>
<script>
export default {
data() {
return {
url: './statics/SampleData/models/CesiumAir/Cesium_Air.gltf',
modelMatrix: {}
}
},
methods: {
ready(cesiumInstance) {
const { Cesium, viewer } = cesiumInstance
this.viewer = viewer
this.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(105, 38, 10000))
},
readyPromise(model) {
const boundingSphere = Cesium.BoundingSphere.transform(model.boundingSphere, model.modelMatrix)
this.viewer.scene.camera.flyToBoundingSphere(boundingSphere)
}
}
}
</script>
</doc-preview>
#### 代码
```html
<template>
<div class="viewer">
<vc-viewer @ready="ready">
<vc-primitive-model
ref="model"
@readyPromise="readyPromise"
:url="url"
:modelMatrix="modelMatrix"
:scale="10000"
:minimumPixelSize="128"
:maximumScale="200000"
>
</vc-primitive-model>
</vc-viewer>
</div>
</template>
<script>
export default {
data() {
return {
url: './statics/SampleData/models/CesiumAir/Cesium_Air.gltf',
modelMatrix: {}
}
},
methods: {
ready(cesiumInstance) {
const { Cesium, viewer } = cesiumInstance
this.viewer = viewer
this.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(105, 38, 10000))
},
readyPromise(model) {
const boundingSphere = Cesium.BoundingSphere.transform(model.boundingSphere, model.modelMatrix)
this.viewer.scene.camera.flyToBoundingSphere(boundingSphere)
}
}
}
</script>
```
## 属性
<!-- prettier-ignore -->
| 属性名 | 类型 | 默认值 | 描述 |
| ------------------------- | ------- | ------ | ---------------------------------------------------------------------------------------------- |
| url | String | | `required` 指定 gltf 文件的 url 地址。 |
| basePath | String | | `optional` 指定 glTF JSON 中的路径相对于的基本路径。 |
| show | Boolean | `true` | `optional` 指定 model 图元是否显示。 |
| modelMatrix | Object | | `optional` 4x4 转换矩阵,用于将模型从模型坐标转换为世界坐标。 |
| scale | Number | `1.0` | `optional` 指定 model 缩放比例。 |
| minimumPixelSize | Number | `0.0` | `optional` 指定 model 的最小像素。 |
| maximumScale | Number | | `optional` 指定 model 最大像素。 |
| id | \* | | `optional` 指定与 model 关联的信息。 |
| allowPicking | Boolean | `true` | `optional` 指定与 model 是否可以被拾取。 |
| incrementallyLoadTextures | Boolean | `true` | `optional` 指定在加载模型后纹理是否可以继续流入。 |
| asynchronous | Boolean | `true` | `optional` 确定在加载所有 glTF 文件后,是否将模型 WebGL 资源创建分散在几个帧或块上,直到完成。 |
| clampAnimations | Boolean | `true` | `optional` 指定动画在没有帧动画的时候保持最后一个姿势。 |
| shadows | Number | `1` | `optional` 指定 model 是否投射或接收每个光源的阴影。 **DISABLED: 0, ENABLED: 1, CAST_ONLY: 2, RECEIVE_ONLY: 3, NUMBER_OF_SHADOW_MODES: 4, RECEIVE_ONLY: 3** |
| debugShowBoundingVolume | Boolean | `false` | `optional` 可选的仅用于调试。 为模型中的每个DrawCommand绘制边界球。 |
| debugWireframe | Boolean | `false` | `optional` 可选的仅用于调试。 仅用于调试。 在线框中绘制模型。 |
| heightReference | Number | `0` | `optional` 指定 model 的高度模式。 **NONE: 0, CLAMP_TO_GROUND: 1, RELATIVE_TO_GROUND: 2** |
| scene | Object | `false` | `optional` 对于使用height reference属性的模型必须传递。 |
| distanceDisplayCondition | Object | | `optional` 指定 model 随相机改变的显示条件。 **结构:{ near: number, far: number }** |
| color | Object\|String\|Array | `'WHITE'` | `optional` 指定 model 渲染混合的颜色。 |
| colorBlendMode | Number | `0` | `optional` 指定 model 与颜色混合模式。 **HIGHLIGHT: 0, REPLACE: 1, MIX: 2** |
| colorBlendAmount | Number | `0.5` | `optional` 指定 colorBlendMode 为 MIX 的颜色强度。0 表示模型颜色,1 表示纯色,0-1 表示混合。 |
| silhouetteColor | Object\|String\|Array | `'RED'` | `optional` 指定 model 轮廓线颜色。 |
| silhouetteSize | Number | `0.0` | `optional` 指定 model 轮廓线像素尺寸。 |
| clippingPlanes | Object | | `optional` 指定 model 屏幕裁剪参数。 |
| debugWireframe | Boolean | `true` | `optional` 确定是否在GPU上对Draco编码的模型进行了反量化。 这减少了编码模型的总内存使用量。 |
| credit | Object\|String | | `optional` 指定 model 的描述信息。 |
---
- 参考官方文档:**[Model](https://cesium.com/docs/cesiumjs-ref-doc/Model.html)**
## 事件
| 事件名 | 参数 | 描述 |
| ------------ | ------------------------------ | -------------------------------------------------------------------------------- |
| ready | {Cesium, viewer, cesiumObject} | 该组件渲染完毕时触发,返回 Cesium 类, viewer 实例,以及当前组件的 cesiumObject。 |
| readyPromise | model | 模型可用时触发。 返回模型对象。 |
---
| {
"pile_set_name": "Github"
} |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ResourceBundle;
import javax.swing.JMenuItem;
import org.compiere.model.PO;
import org.eevolution.tools.swing.SwingTool;
import org.eevolution.tools.worker.SingleWorker;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public abstract class PopupAction extends JMenuItem implements ActionListener {
protected final ResourceBundle language;
protected PropertyChangeSupport propertyChange;
protected boolean success;
protected boolean ignoreChange;
protected SingleWorker worker;
protected String errorMsg;
protected abstract void doAction(ActionEvent e);
protected abstract String getCommand();
protected abstract String validateAction();
protected boolean successful() {
return success;
}
public String getSuccessMsg() {
return "OK";
}
protected void setError(String msg) {
errorMsg = msg;
success = false;
}
public String getErrorMsg() {
return errorMsg;
}
public PopupAction(String property) {
super();
language = ResourceBundle.getBundle(getClass().getPackage().getName()+".language");
setText(language.getString(property));
setActionCommand(getCommand());
init();
addActionListener(this);
}
protected void init() {
this.success = true;
this.ignoreChange = false;
}
protected void beforeAction() {
init();
String valid = validateAction();
if(valid != null) {
setError(valid);
return;
}
SwingTool.setCursorsFromChild(this, true);
}
protected void afterAction() {
if(!isIgnoreChange()) {
propertyChange.firePropertyChange(getCommand(), false, successful());
}
SwingTool.setCursorsFromChild(this, false);
}
public void actionPerformed(ActionEvent e) {
final ActionEvent evt = e;
worker = new SingleWorker() {
protected Object doIt() {
run(evt);
return null;
};
};
worker.start();
}
protected void run(ActionEvent e) {
beforeAction();
if(getActionCommand() != null && getActionCommand().equals(e.getActionCommand())) {
doAction(e);
}
afterAction();
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
if(propertyChange == null) {
propertyChange = new PropertyChangeSupport(this);
}
propertyChange.addPropertyChangeListener(listener);
}
protected void setIgnoreChange(boolean ignore) {
ignoreChange = ignore;
}
public boolean isIgnoreChange() {
return ignoreChange;
}
protected void savePO(PO po) {
success = po.save(null);
}
protected void deletePO(PO po) {
success = po.delete(true, null);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2019 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: GPL-2.0
#pragma once
#include "Describer.h"
#include "ProcessImage.h"
namespace chap {
template <typename Offset>
class StackOverflowGuardDescriber : public Describer<Offset> {
typedef typename VirtualMemoryPartition<Offset>::ClaimedRanges ClaimedRanges;
public:
StackOverflowGuardDescriber(const ProcessImage<Offset> &processImage)
: _processImage(processImage),
_threadMap(processImage.GetThreadMap()),
_virtualAddressMap(processImage.GetVirtualAddressMap()),
_virtualMemoryPartition(processImage.GetVirtualMemoryPartition()),
_inaccessibleRanges(
_virtualMemoryPartition.GetClaimedInaccessibleRanges()),
_readOnlyRanges(_virtualMemoryPartition.GetClaimedReadOnlyRanges()) {}
/*
* If the address is understood, provide a description for the address,
* optionally with an additional explanation of why the address matches
* the description, and return true. Otherwise don't write anything
* and return false. Show addresses only if requested.
*/
bool Describe(Commands::Context &context, Offset address, bool explain,
bool showAddresses) const {
bool foundAsReadOnly = false;
typename ClaimedRanges::const_iterator it =
_inaccessibleRanges.find(address);
if (it == _inaccessibleRanges.end()) {
it = _readOnlyRanges.find(address);
if (it == _readOnlyRanges.end()) {
return false;
}
foundAsReadOnly = true;
}
if (it->_value != _processImage.STACK_OVERFLOW_GUARD) {
return false;
}
Offset guardBase = it->_base;
Offset guardLimit = it->_limit;
// TODO: There should be no assumption that the stack is currently
// associated with a thread.
Commands::Output &output = context.GetOutput();
if (showAddresses) {
output << "Address 0x" << std::hex << address << " is at offset 0x"
<< (address - guardBase) << " in stack overflow guard\n[0x"
<< guardBase << ", 0x" << guardLimit << ")\nfor ";
} else {
output << "This is a stack overflow guard for ";
}
const typename ThreadMap<Offset>::ThreadInfo *threadInfo =
_threadMap.find(guardLimit);
if (threadInfo == nullptr) {
output << "some unknown stack.\n";
} else {
output << "the stack for thread " << std::dec << threadInfo->_threadNum
<< ".\n";
}
if (explain) {
if (foundAsReadOnly) {
output << "The guard is marked readable, likely due to a bug in "
"creation of the core.\n";
} else {
if (_virtualAddressMap.find(address) == _virtualAddressMap.end()) {
output << "The guard is not listed in the core but is inferred "
"based on the adjacent ranges.\n";
}
}
}
return true;
}
private:
const ProcessImage<Offset> &_processImage;
const ThreadMap<Offset> &_threadMap;
const VirtualAddressMap<Offset> &_virtualAddressMap;
const VirtualMemoryPartition<Offset> &_virtualMemoryPartition;
const ClaimedRanges &_inaccessibleRanges;
const ClaimedRanges &_readOnlyRanges;
};
} // namespace chap
| {
"pile_set_name": "Github"
} |
require('dotenv').config()
const {assert} = require('chai');
require('electron-mocha');
require('isomorphic-fetch');
const embedder = require('../../electron/services/embedder');
describe('embedder', () => {
it('should check the sources for embed', done => {
new Promise(async() => {
const result = await embedder.cacheEmbedFiles(null);
console.log('result', result);
done();
})
})
});
| {
"pile_set_name": "Github"
} |
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
tb.h --
Original Author: Martin Janssen, Synopsys, Inc., 2002-02-15
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
/* Common interface file for test bench
Author: PRP
*/
SC_MODULE( tb )
{
SC_HAS_PROCESS( tb );
sc_in_clk clk;
// Output Reset Port
sc_signal<bool>& reset_sig;
// Output Data Ports
sc_signal<int>& i1;
sc_signal<int>& i2;
sc_signal<int>& i3;
sc_signal<int>& i4;
sc_signal<int>& i5;
// Output Control Ports
sc_signal<bool>& cont1;
sc_signal<bool>& cont2;
sc_signal<bool>& cont3;
// Input Data Ports
const sc_signal<int>& o1;
const sc_signal<int>& o2;
const sc_signal<int>& o3;
const sc_signal<int>& o4;
const sc_signal<int>& o5;
// Constructor
tb (
sc_module_name NAME,
sc_clock& CLK,
sc_signal<bool>& RESET_SIG,
sc_signal<int>& I1,
sc_signal<int>& I2,
sc_signal<int>& I3,
sc_signal<int>& I4,
sc_signal<int>& I5,
sc_signal<bool>& CONT1,
sc_signal<bool>& CONT2,
sc_signal<bool>& CONT3,
const sc_signal<int>& O1,
const sc_signal<int>& O2,
const sc_signal<int>& O3,
const sc_signal<int>& O4,
const sc_signal<int>& O5)
: reset_sig(RESET_SIG), i1(I1), i2(I2),
i3(I3), i4(I4), i5(I5), cont1 (CONT1), cont2 (CONT2),
cont3 (CONT3), o1(O1), o2(O2), o3(O3), o4(O4), o5(O5)
{
clk(CLK);
SC_CTHREAD( entry, clk.pos() );
}
void entry();
};
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>RiTa Reference</title>
<link rel="stylesheet" href="../../../css/bootstrap.css" type="text/css" />
<link rel="stylesheet" href="../../../css/syntax.css" type="text/css" />
<link rel="stylesheet" href="../../../css/style.css" type="text/css" />
<link rel="shortcut icon" type="image/x-icon" href="http://rednoise.org/rita/rita.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../../../css/normalize.css">
<link rel="stylesheet" href="../../../css/main.css">
<script src="../../../js/vendor/modernizr-2.6.2.min.js"></script>
<script language="javascript" src="../../../js/highlight.js"></script>
</head>
<body>
<?php include("../../../header.php"); ?>
<div class="gd-section pad-large">
<div class="gd-center pad-large">
<div class="row">
<div class="col1"></div>
<div class="col10">
<h3>Reference</h3>
<div class="page row">
<div class="refbar span3">
<div id="index">
<!-- begin publish.classesIndex -->
<h3></h3>
<ul class="classList" >
<br />
<li style="top:60px;left:50px">
<a href="../../index.php">Back to index</a>
</li>
</ul>
<hr />
<!-- end publish.classesIndex -->
</div>
</div>
<div class="span11">
<table cellpadding="0" cellspacing="0" border="0" class="ref-item">
<tr class="name-row">
<th scope="row">Class</th>
<!-- ------------ METHODS PROPERTIES HERE ------------ -->
<!-- ClASS -->
<td><h3><a href="../../RiTa.php">RiTa</a></h3></td>
</tr>
<tr class="name-row">
<th scope="row">Name</th>
<!-- METHOD NAME -->
<td><h3>RiTa.reload</h3></td>
</tr>
<tr class="">
<th scope="row">Description</th>
<!-- DESCRIPTION -->
<td>Clears then reloads the default lexicon</td>
</tr>
<tr class='Syntax'>
<th scope="row">Syntax</th>
<!-- SYNTAX -->
<td><pre>RiTa.reload();</pre></td>
</tr>
<tr class='Parameters' style='display:none'>
<th scope="row">Parameters</th>
<td>
<!-- PARAMETERS -->
<table cellpadding="0" cellspacing="0" border="0" class="sub-table">
tmp_parameters
</table></td>
</tr>
<tr class='Returns'>
<th scope="row">Returns</th>
<td>
<!-- RETURNS/TYPE (for variables) -->
<table cellpadding="0" cellspacing="0" border="0" class="sub-table">
<tr class=''><th width='25%' scope='row' class=nobold>void</th><td width='75%'></td></tr>
</table></td>
</tr>
<tr class='Related' style='display:none'>
<th scope="row">Related</th>
<!-- RELATED -->
<td>tmp_related</td>
</tr>
<tr class='Note' style='display:none'>
<th scope="row">Note</th>
<!-- NOTE -->
<td>tmp_note</td>
</tr>
<tr class='Example'>
<th scope='row'>Example</th>
<td>
<div class="example">
<!-- EXAMPLE -->
<!--img src="../../../img/RiTa-logo4.png" alt="example pic" /-->
<pre class="margin">RiTa.removeWord("abandon");<br>RiTa.reload();</pre>
</div></td>
</tr>
<tr class="">
<th scope="row">Platform</th>
<!-- PLATFORM -->
<td>Java / JavaScript</td>
</tr>
<tr class="">
<th scope="row"></th>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="col1"></div>
</div>
</div>
</div>
<?php include("../../../footer.php"); ?>
</body>
</html>
| {
"pile_set_name": "Github"
} |
// Copyright 2014-2017 Ulrich Kunitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lzma
import (
"errors"
"fmt"
)
// maximum and minimum values for the LZMA properties.
const (
minPB = 0
maxPB = 4
)
// maxPropertyCode is the possible maximum of a properties code byte.
const maxPropertyCode = (maxPB+1)*(maxLP+1)*(maxLC+1) - 1
// Properties contains the parameters LC, LP and PB. The parameter LC
// defines the number of literal context bits; parameter LP the number
// of literal position bits and PB the number of position bits.
type Properties struct {
LC int
LP int
PB int
}
// String returns the properties in a string representation.
func (p *Properties) String() string {
return fmt.Sprintf("LC %d LP %d PB %d", p.LC, p.LP, p.PB)
}
// PropertiesForCode converts a properties code byte into a Properties value.
func PropertiesForCode(code byte) (p Properties, err error) {
if code > maxPropertyCode {
return p, errors.New("lzma: invalid properties code")
}
p.LC = int(code % 9)
code /= 9
p.LP = int(code % 5)
code /= 5
p.PB = int(code % 5)
return p, err
}
// verify checks the properties for correctness.
func (p *Properties) verify() error {
if p == nil {
return errors.New("lzma: properties are nil")
}
if !(minLC <= p.LC && p.LC <= maxLC) {
return errors.New("lzma: lc out of range")
}
if !(minLP <= p.LP && p.LP <= maxLP) {
return errors.New("lzma: lp out of range")
}
if !(minPB <= p.PB && p.PB <= maxPB) {
return errors.New("lzma: pb out of range")
}
return nil
}
// Code converts the properties to a byte. The function assumes that
// the properties components are all in range.
func (p Properties) Code() byte {
return byte((p.PB*5+p.LP)*9 + p.LC)
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.scenariosimulation.api.model;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ScesimModelDescriptorTest {
private ScesimModelDescriptor scesimModelDescriptor;
private FactIdentifier factIdentifier;
private ExpressionIdentifier expressionIdentifier;
@Before
public void init() {
scesimModelDescriptor = new ScesimModelDescriptor();
factIdentifier = FactIdentifier.create("test fact", String.class.getCanonicalName());
expressionIdentifier = ExpressionIdentifier.create("test expression", FactMappingType.EXPECT);
}
@Test
public void getFactIdentifiers() {
scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
final Set<FactIdentifier> retrieved = scesimModelDescriptor.getFactIdentifiers();
assertNotNull(retrieved);
assertEquals(1, retrieved.size());
assertEquals(factIdentifier, retrieved.iterator().next());
}
@Test
public void addFactMappingByIndexAndFactMapping() {
FactMapping toClone = new FactMapping();
toClone.setFactAlias("ALIAS");
toClone.setExpressionAlias("EXPRESSION_ALIAS");
final FactMapping cloned = scesimModelDescriptor.addFactMapping(0, toClone);
assertEquals(toClone.getFactAlias(), cloned.getFactAlias());
assertEquals(toClone.getExpressionAlias(), cloned.getExpressionAlias());
}
@Test
public void addFactMappingByFactIdentifierAndExpressionIdentifier() {
scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
}
@Test(expected = IllegalArgumentException.class)
public void addFactMappingByFactIdentifierAndExpressionIdentifierFail() {
scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
// Should fail
scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
}
@Test
public void addFactMappingByIndexAndFactIdentifierAndExpressionIdentifier() {
scesimModelDescriptor.addFactMapping(0, factIdentifier, expressionIdentifier);
}
@Test(expected = IllegalArgumentException.class)
public void addFactMappingByIndexAndFactIdentifierAndExpressionIdentifierFail() {
// Should fail
scesimModelDescriptor.addFactMapping(1, factIdentifier, expressionIdentifier);
}
@Test(expected = IndexOutOfBoundsException.class)
public void removeFactMappingByIndex() {
int testingIndex = 0;
scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
assertNotNull(scesimModelDescriptor.getFactMappingByIndex(testingIndex));
scesimModelDescriptor.removeFactMappingByIndex(testingIndex);
scesimModelDescriptor.getFactMappingByIndex(testingIndex);
}
@Test
public void removeFactMapping() {
FactMapping retrieved = scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
assertTrue(scesimModelDescriptor.getUnmodifiableFactMappings().contains(retrieved));
scesimModelDescriptor.removeFactMapping(retrieved);
assertFalse(scesimModelDescriptor.getUnmodifiableFactMappings().contains(retrieved));
}
@Test
public void getIndexByIdentifierTest() {
List<FactMapping> originalFactMappings = IntStream.range(0, 2).boxed()
.map(i -> scesimModelDescriptor
.addFactMapping(FactIdentifier.create("test " + i, String.class.getCanonicalName()), this.expressionIdentifier)
).collect(Collectors.toList());
int indexToCheck = 0;
int indexRetrieved = scesimModelDescriptor.getIndexByIdentifier(originalFactMappings.get(indexToCheck).getFactIdentifier(), this.expressionIdentifier);
assertEquals(indexToCheck, indexRetrieved);
indexToCheck = 1;
indexRetrieved = scesimModelDescriptor.getIndexByIdentifier(originalFactMappings.get(indexToCheck).getFactIdentifier(), this.expressionIdentifier);
assertEquals(indexToCheck, indexRetrieved);
}
@Test(expected = IllegalArgumentException.class)
public void getIndexByIdentifierTestFail() {
IntStream.range(0, 2).forEach(i -> scesimModelDescriptor
.addFactMapping(FactIdentifier.create("test " + i, String.class.getCanonicalName()), this.expressionIdentifier));
FactIdentifier notExisting = new FactIdentifier();
scesimModelDescriptor.getIndexByIdentifier(notExisting, this.expressionIdentifier);
}
@Test
public void getFactMappingsByFactName() {
IntStream.range(0, 2).forEach(i -> scesimModelDescriptor
.addFactMapping(FactIdentifier.create("test", String.class.getCanonicalName()), ExpressionIdentifier.create("test expression " + i, FactMappingType.EXPECT)));
scesimModelDescriptor
.addFactMapping(FactIdentifier.create("TEST", String.class.getCanonicalName()), ExpressionIdentifier.create("test expression 2", FactMappingType.EXPECT));
scesimModelDescriptor
.addFactMapping(FactIdentifier.create("Test", String.class.getCanonicalName()), ExpressionIdentifier.create("test expression 3", FactMappingType.EXPECT));
scesimModelDescriptor
.addFactMapping(FactIdentifier.create("tEsT", String.class.getCanonicalName()), ExpressionIdentifier.create("test expression 4", FactMappingType.EXPECT));
final List<FactMapping> retrieved = scesimModelDescriptor.getFactMappingsByFactName("test");
assertNotNull(retrieved);
assertEquals(5, retrieved.size());
}
@Test
public void moveFactMappingTest() {
ExpressionIdentifier expressionIdentifier2 = ExpressionIdentifier.create("Test expression 2", FactMappingType.GIVEN);
ExpressionIdentifier expressionIdentifier3 = ExpressionIdentifier.create("Test expression 3", FactMappingType.GIVEN);
FactMapping factMapping1 = scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
FactMapping factMapping2 = scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier2);
FactMapping factMapping3 = scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier3);
List<FactMapping> factMappings = scesimModelDescriptor.getUnmodifiableFactMappings();
assertEquals(factMappings.get(0), factMapping1);
assertEquals(factMappings.get(1), factMapping2);
assertEquals(factMappings.get(2), factMapping3);
scesimModelDescriptor.moveFactMapping(0, 1);
factMappings = scesimModelDescriptor.getUnmodifiableFactMappings();
assertEquals(factMappings.get(0), factMapping2);
assertEquals(factMappings.get(1), factMapping1);
assertEquals(factMappings.get(2), factMapping3);
scesimModelDescriptor.moveFactMapping(2, 1);
factMappings = scesimModelDescriptor.getUnmodifiableFactMappings();
assertEquals(factMappings.get(0), factMapping2);
assertEquals(factMappings.get(1), factMapping3);
assertEquals(factMappings.get(2), factMapping1);
scesimModelDescriptor.moveFactMapping(2, 2);
factMappings = scesimModelDescriptor.getUnmodifiableFactMappings();
assertEquals(factMappings.get(0), factMapping2);
assertEquals(factMappings.get(1), factMapping3);
assertEquals(factMappings.get(2), factMapping1);
}
@Test
public void moveFactMappingOldFailTest() {
ExpressionIdentifier expressionIdentifier2 = ExpressionIdentifier.create("Test expression 2", FactMappingType.GIVEN);
scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
scesimModelDescriptor.addFactMapping(factIdentifier, expressionIdentifier2);
muteException(() -> {
scesimModelDescriptor.moveFactMapping(2, 0);
fail();
},
IndexOutOfBoundsException.class);
muteException(() -> {
scesimModelDescriptor.moveFactMapping(-1, 0);
fail();
},
IndexOutOfBoundsException.class);
muteException(() -> {
scesimModelDescriptor.moveFactMapping(0, 2);
fail();
},
IndexOutOfBoundsException.class);
muteException(() -> {
scesimModelDescriptor.moveFactMapping(0, -1);
fail();
},
IndexOutOfBoundsException.class);
}
private <T extends Throwable> void muteException(Runnable toBeExecuted, Class<T> expected) {
try {
toBeExecuted.run();
} catch (Throwable t) {
//noinspection NonJREEmulationClassesInClientCode
if (!t.getClass().isAssignableFrom(expected)) {
throw t;
}
}
}
}
| {
"pile_set_name": "Github"
} |
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.agent.api.storage;
public class UploadProgressCommand extends UploadCommand {
public static enum RequestType {
GET_STATUS, ABORT, RESTART, PURGE, GET_OR_RESTART
}
private String jobId;
private RequestType request;
protected UploadProgressCommand() {
super();
}
public UploadProgressCommand(UploadCommand cmd, String jobId, RequestType req) {
super(cmd);
this.jobId = jobId;
this.setRequest(req);
}
public String getJobId() {
return jobId;
}
public void setRequest(RequestType request) {
this.request = request;
}
public RequestType getRequest() {
return request;
}
}
| {
"pile_set_name": "Github"
} |
// ***************************************************************************
// *
// * Copyright (C) 2010 International Business Machines
// * Corporation and others. All Rights Reserved.
// * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java
// * Source File:<path>/icu-config.xml & build.xml
// *
// ***************************************************************************
no{
"%%ALIAS"{"nb"}
}
| {
"pile_set_name": "Github"
} |
# Getting started with the Keras Sequential model
The `Sequential` model is a linear stack of layers.
You can create a `Sequential` model by passing a list of layer instances to the constructor:
```python
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
```
You can also simply add layers via the `.add()` method:
```python
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
```
----
## Specifying the input shape
The model needs to know what input shape it should expect. For this reason, the first layer in a `Sequential` model (and only the first, because following layers can do automatic shape inference) needs to receive information about its input shape. There are several possible ways to do this:
- Pass an `input_shape` argument to the first layer. This is a shape tuple (a tuple of integers or `None` entries, where `None` indicates that any positive integer may be expected). In `input_shape`, the batch dimension is not included.
- Some 2D layers, such as `Dense`, support the specification of their input shape via the argument `input_dim`, and some 3D temporal layers support the arguments `input_dim` and `input_length`.
- If you ever need to specify a fixed batch size for your inputs (this is useful for stateful recurrent networks), you can pass a `batch_size` argument to a layer. If you pass both `batch_size=32` and `input_shape=(6, 8)` to a layer, it will then expect every batch of inputs to have the batch shape `(32, 6, 8)`.
As such, the following snippets are strictly equivalent:
```python
model = Sequential()
model.add(Dense(32, input_shape=(784,)))
```
```python
model = Sequential()
model.add(Dense(32, input_dim=784))
```
----
## Compilation
Before training a model, you need to configure the learning process, which is done via the `compile` method. It receives three arguments:
- An optimizer. This could be the string identifier of an existing optimizer (such as `rmsprop` or `adagrad`), or an instance of the `Optimizer` class. See: [optimizers](/optimizers).
- A loss function. This is the objective that the model will try to minimize. It can be the string identifier of an existing loss function (such as `categorical_crossentropy` or `mse`), or it can be an objective function. See: [losses](/losses).
- A list of metrics. For any classification problem you will want to set this to `metrics=['accuracy']`. A metric could be the string identifier of an existing metric or a custom metric function.
```python
# For a multi-class classification problem
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
# For a binary classification problem
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
# For a mean squared error regression problem
model.compile(optimizer='rmsprop',
loss='mse')
# For custom metrics
import keras.backend as K
def mean_pred(y_true, y_pred):
return K.mean(y_pred)
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy', mean_pred])
```
----
## Training
Keras models are trained on Numpy arrays of input data and labels. For training a model, you will typically use the `fit` function. [Read its documentation here](/models/sequential).
```python
# For a single-input model with 2 classes (binary classification):
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
# Generate dummy data
import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)
```
```python
# For a single-input model with 10 classes (categorical classification):
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Generate dummy data
import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(10, size=(1000, 1))
# Convert labels to categorical one-hot encoding
one_hot_labels = keras.utils.to_categorical(labels, num_classes=10)
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, one_hot_labels, epochs=10, batch_size=32)
```
----
## Examples
Here are a few examples to get you started!
In the [examples folder](https://github.com/keras-team/keras/tree/master/examples), you will also find example models for real datasets:
- CIFAR10 small images classification: Convolutional Neural Network (CNN) with realtime data augmentation
- IMDB movie review sentiment classification: LSTM over sequences of words
- Reuters newswires topic classification: Multilayer Perceptron (MLP)
- MNIST handwritten digits classification: MLP & CNN
- Character-level text generation with LSTM
...and more.
### Multilayer Perceptron (MLP) for multi-class softmax classification:
```python
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
# Generate dummy data
import numpy as np
x_train = np.random.random((1000, 20))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
x_test = np.random.random((100, 20))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
model = Sequential()
# Dense(64) is a fully-connected layer with 64 hidden units.
# in the first layer, you must specify the expected input data shape:
# here, 20-dimensional vectors.
model.add(Dense(64, activation='relu', input_dim=20))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)
```
### MLP for binary classification:
```python
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout
# Generate dummy data
x_train = np.random.random((1000, 20))
y_train = np.random.randint(2, size=(1000, 1))
x_test = np.random.random((100, 20))
y_test = np.random.randint(2, size=(100, 1))
model = Sequential()
model.add(Dense(64, input_dim=20, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)
```
### VGG-like convnet:
```python
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD
# Generate dummy data
x_train = np.random.random((100, 100, 100, 3))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
x_test = np.random.random((20, 100, 100, 3))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(20, 1)), num_classes=10)
model = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# this applies 32 convolution filters of size 3x3 each.
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)
model.fit(x_train, y_train, batch_size=32, epochs=10)
score = model.evaluate(x_test, y_test, batch_size=32)
```
### Sequence classification with LSTM:
```python
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers import Embedding
from keras.layers import LSTM
model = Sequential()
model.add(Embedding(max_features, output_dim=256))
model.add(LSTM(128))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=16, epochs=10)
score = model.evaluate(x_test, y_test, batch_size=16)
```
### Sequence classification with 1D convolutions:
```python
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers import Embedding
from keras.layers import Conv1D, GlobalAveragePooling1D, MaxPooling1D
model = Sequential()
model.add(Conv1D(64, 3, activation='relu', input_shape=(seq_length, 100)))
model.add(Conv1D(64, 3, activation='relu'))
model.add(MaxPooling1D(3))
model.add(Conv1D(128, 3, activation='relu'))
model.add(Conv1D(128, 3, activation='relu'))
model.add(GlobalAveragePooling1D())
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=16, epochs=10)
score = model.evaluate(x_test, y_test, batch_size=16)
```
### Stacked LSTM for sequence classification
In this model, we stack 3 LSTM layers on top of each other,
making the model capable of learning higher-level temporal representations.
The first two LSTMs return their full output sequences, but the last one only returns
the last step in its output sequence, thus dropping the temporal dimension
(i.e. converting the input sequence into a single vector).
<img src="https://keras.io/img/regular_stacked_lstm.png" alt="stacked LSTM" style="width: 300px;"/>
```python
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np
data_dim = 16
timesteps = 8
num_classes = 10
# expected input data shape: (batch_size, timesteps, data_dim)
model = Sequential()
model.add(LSTM(32, return_sequences=True,
input_shape=(timesteps, data_dim))) # returns a sequence of vectors of dimension 32
model.add(LSTM(32, return_sequences=True)) # returns a sequence of vectors of dimension 32
model.add(LSTM(32)) # return a single vector of dimension 32
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# Generate dummy training data
x_train = np.random.random((1000, timesteps, data_dim))
y_train = np.random.random((1000, num_classes))
# Generate dummy validation data
x_val = np.random.random((100, timesteps, data_dim))
y_val = np.random.random((100, num_classes))
model.fit(x_train, y_train,
batch_size=64, epochs=5,
validation_data=(x_val, y_val))
```
### Same stacked LSTM model, rendered "stateful"
A stateful recurrent model is one for which the internal states (memories) obtained after processing a batch
of samples are reused as initial states for the samples of the next batch. This allows to process longer sequences
while keeping computational complexity manageable.
[You can read more about stateful RNNs in the FAQ.](/getting-started/faq/#how-can-i-use-stateful-rnns)
```python
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np
data_dim = 16
timesteps = 8
num_classes = 10
batch_size = 32
# Expected input batch shape: (batch_size, timesteps, data_dim)
# Note that we have to provide the full batch_input_shape since the network is stateful.
# the sample of index i in batch k is the follow-up for the sample i in batch k-1.
model = Sequential()
model.add(LSTM(32, return_sequences=True, stateful=True,
batch_input_shape=(batch_size, timesteps, data_dim)))
model.add(LSTM(32, return_sequences=True, stateful=True))
model.add(LSTM(32, stateful=True))
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# Generate dummy training data
x_train = np.random.random((batch_size * 10, timesteps, data_dim))
y_train = np.random.random((batch_size * 10, num_classes))
# Generate dummy validation data
x_val = np.random.random((batch_size * 3, timesteps, data_dim))
y_val = np.random.random((batch_size * 3, num_classes))
model.fit(x_train, y_train,
batch_size=batch_size, epochs=5, shuffle=False,
validation_data=(x_val, y_val))
```
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.