max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
848 | <gh_stars>100-1000
#
# Copyright 2019 Xilinx Inc.
#
# 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.
#
import imp
import os
import sys
import torch
from torch.utils.cpp_extension import load, _import_module_from_library
from nndct_shared.utils import create_work_dir, NndctScreenLogger
_cur_dir = os.path.dirname(os.path.realpath(__file__))
_aot = False
for name in os.listdir(_cur_dir):
if name.split(".")[-1] == "so":
_aot = True
break
if _aot:
try:
from pytorch_nndct.nn import _kernels
nndct_kernels = _kernels
except ImportError as e:
NndctScreenLogger().error(f"{str(e)}")
sys.exit(1)
else:
NndctScreenLogger().info(f"Loading NNDCT kernels...")
else:
if os.path.exists(os.path.join(_cur_dir, "kernel")):
from .kernel import NN_PATH
else:
NN_PATH = _cur_dir
try:
cwd = NN_PATH
lib_path = os.path.join(cwd, "lib")
create_work_dir(lib_path)
cpu_src_path = os.path.join(cwd, "../../../csrc/cpu")
source_files = []
for name in os.listdir(cpu_src_path):
if name.split(".")[-1] in ["cpp", "cc", "c"]:
source_files.append(os.path.join(cpu_src_path, name))
extra_include_paths = [
os.path.join(cwd, "../../../include/cpu"),
os.path.join(cwd, "include")
]
with_cuda = False
#if torch.cuda.is_available() and "CUDA_HOME" in os.environ:
if "CUDA_HOME" in os.environ:
cuda_src_path = os.path.join(cwd, "../../../csrc/cuda")
for name in os.listdir(cuda_src_path):
if name.split(".")[-1] in ["cu", "cpp", "cc", "c"]:
source_files.append(os.path.join(cuda_src_path, name))
cpp_src_path = os.path.join(cwd, "src/cuda")
for name in os.listdir(cpp_src_path):
if name.split(".")[-1] in ["cpp", "cc", "c"]:
source_files.append(os.path.join(cpp_src_path, name))
extra_include_paths.append(os.path.join(cwd, "../../../include/cuda"))
with_cuda = None
else:
print("CUDA is not available, or CUDA_HOME not found in the environment "
"so building without GPU support.")
cpp_src_path = os.path.join(cwd, "src/cpu")
for name in os.listdir(cpp_src_path):
if name.split(".")[-1] in ["cpp", "cc", "c"]:
source_files.append(os.path.join(cpp_src_path, name))
nndct_kernels = load(
name="nndct_kernels",
sources=source_files,
verbose=False,
build_directory=lib_path,
extra_include_paths=extra_include_paths,
with_cuda=with_cuda)
except ImportError as e:
NndctScreenLogger().error(f"{str(e)}")
sys.exit(1)
else:
NndctScreenLogger().info(f"Loading NNDCT kernels...")
| 1,379 |
634 | <filename>modules/base/project-model-impl/src/main/java/consulo/roots/impl/OptimizedSingleContentEntryImpl.java
/*
* Copyright 2013-2020 consulo.io
*
* 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 consulo.roots.impl;
import com.google.common.base.Predicate;
import com.intellij.openapi.roots.ContentFolder;
import com.intellij.openapi.roots.impl.BaseModuleRootLayerChild;
import com.intellij.openapi.roots.impl.ContentEntryImpl;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import consulo.roots.ContentFolderTypeProvider;
import consulo.util.collection.ArrayUtil;
import org.jdom.Element;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;
/**
* @author VISTALL
* @since 2020-08-29
*
* Optimized version of {@link ContentEntryImpl} without supporting data inside
*/
public class OptimizedSingleContentEntryImpl extends BaseModuleRootLayerChild implements ContentEntryEx {
@Nonnull
private final VirtualFilePointer myRoot;
public OptimizedSingleContentEntryImpl(@Nonnull VirtualFile file, @Nonnull ModuleRootLayerImpl m) {
this(file.getUrl(), m);
}
public OptimizedSingleContentEntryImpl(@Nonnull String url, @Nonnull ModuleRootLayerImpl m) {
super(m);
myRoot = VirtualFilePointerManager.getInstance().create(url, this, null);
}
public OptimizedSingleContentEntryImpl(@Nonnull Element e, @Nonnull ModuleRootLayerImpl m) {
this(ContentEntryImpl.getUrlFrom(e), m);
}
public void writeExternal(@Nonnull Element element) {
assert !isDisposed();
element.setAttribute(ContentEntryImpl.URL_ATTRIBUTE, myRoot.getUrl());
}
@Override
public VirtualFile getFile() {
return myRoot.getFile();
}
@Override
@Nonnull
public String getUrl() {
return myRoot.getUrl();
}
@Nonnull
@Override
public ContentFolder[] getFolders(@Nonnull Predicate<ContentFolderTypeProvider> predicate) {
return ContentFolder.EMPTY_ARRAY;
}
@Nonnull
@Override
public VirtualFile[] getFolderFiles(@Nonnull Predicate<ContentFolderTypeProvider> predicate) {
return VirtualFile.EMPTY_ARRAY;
}
@Nonnull
@Override
public String[] getFolderUrls(@Nonnull Predicate<ContentFolderTypeProvider> predicate) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
@Nonnull
@Override
public Collection<ContentFolder> getContentFolders() {
return Collections.emptyList();
}
@Nonnull
@Override
public ContentFolder addFolder(@Nonnull VirtualFile file, @Nonnull ContentFolderTypeProvider contentFolderType) {
throw new UnsupportedOperationException();
}
@Nonnull
@Override
public ContentFolder addFolder(@Nonnull String url, @Nonnull ContentFolderTypeProvider contentFolderType) {
throw new UnsupportedOperationException();
}
@Override
public void removeFolder(@Nonnull ContentFolder contentFolder) {
throw new UnsupportedOperationException();
}
@Override
public ContentEntryEx cloneEntry(ModuleRootLayerImpl layer) {
assert !isDisposed();
return new OptimizedSingleContentEntryImpl(myRoot.getUrl(), layer);
}
}
| 1,113 |
529 | <gh_stars>100-1000
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <tinyhal.h>
#include <usart_decl.h>
#include "..\Log\Log.h"
//--//
#ifndef _UART_TEST_
#define _UART_TEST_ 1
//--//
#define BUFFER_SIZE 8
#define FlowCtrlNone USART_FLOW_NONE
#define FlowCtrlSW USART_FLOW_SW_IN_EN | USART_FLOW_SW_OUT_EN
#define FlowCtrlHW USART_FLOW_HW_IN_EN | USART_FLOW_HW_OUT_EN
//--//
class UART
{
int m_com; // Com port may enumerate from 0, ...
int m_baud; //{1200, 9600, 57600, 115200, 230400, ...}
int m_parity; // parity
int m_stop; // stop bit
int m_data; // data bit count
int m_flow; // flow-control, see USART_decl.h
char m_xmitBuffer[BUFFER_SIZE]; // for out-bound messages
char m_recvBuffer[BUFFER_SIZE]; // for in-bound messages
//--//
public:
UART ( int com, int baud, int parity, int stop, int data, int flow );
BOOL Execute ( LOG_STREAM Stream );
void InitializeXmitBuffer ( );
BOOL Validate ( );
};
#endif
//--//
| 735 |
937 | """
自定义的sum模块,需要自测成功后再使用
1- 书写格式,如果在本模块下执行这个模块,python会自定义一个值为__main__的__name__变量
2- main()可以直接写,但是开发时候常用if __name__ == '__main__'的方式
3- if __name__ == '__main__': 类似于main函数的入口
4- 如果在其他模块中引入并且调用这个模块任何方法和属性,那么__name__就变成了本函数名
"""
# 模块中的全局变量
name = "加法运算"
# 模块中自定义类
class Person(object):
pass
# 加法运算函数
def my_sum(a, b):
return a + b
# 自测函数
def main():
result = my_sum(3, 5)
print(result)
# main()
# 书写格式, __main__, 防止测试工程师使用这个模块的时候执行自己的自测函数
print(__name__)
if __name__ == '__main__':
main()
"""
__all__ = []只有列表中的元素才能被外部的模块使用
但是__all__只能配合from 模块名 import * 这种格式下才有效
"""
__all__ = ["name", "Person", "my_sum"] | 656 |
427 | // RUN: rm -rf %t
// RUN: %clang_cc1 -fsyntax-only -fapinotes -fapinotes-cache-path=%t %s -I %S/Inputs/BrokenHeaders -verify
#include "SomeBrokenLib.h"
// expected-error@AP<EMAIL>:4{{unknown key 'Nu llabilityOfRet'}}
| 96 |
2,757 | <gh_stars>1000+
#!/usr/bin/env python2.7
#Copyright 2018 Google LLC
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# 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.
import sqlite3
import random
import sys
BANNER = "=== Media DB ==="
MENU = """\
1) add song
2) play artist
3) play song
4) shuffle artist
5) exit"""
with open('oauth_token') as fd:
flag = fd.read()
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("CREATE TABLE oauth_tokens (oauth_token text)")
c.execute("CREATE TABLE media (artist text, song text)")
c.execute("INSERT INTO oauth_tokens VALUES ('{}')".format(flag))
def my_print(s):
sys.stdout.write(s + '\n')
sys.stdout.flush()
def print_playlist(query):
my_print("")
my_print("== new playlist ==")
for i, res in enumerate(c.execute(query).fetchall()):
my_print('{}: "{}" by "{}"'.format(i+1, res[1], res[0]))
my_print("")
my_print(BANNER)
while True:
my_print(MENU)
sys.stdout.write("> ")
sys.stdout.flush()
choice = raw_input()
if choice not in ['1', '2', '3', '4', '5']:
my_print('invalid input')
continue
if choice == '1':
my_print("artist name?")
artist = raw_input().replace('"', "")
my_print("song name?")
song = raw_input().replace('"', "")
c.execute("""INSERT INTO media VALUES ("{}", "{}")""".format(artist, song))
elif choice == '2':
my_print("artist name?")
artist = raw_input().replace("'", "")
print_playlist("SELECT artist, song FROM media WHERE artist = '{}'".format(artist))
elif choice == '3':
my_print("song name?")
song = raw_input().replace("'", "")
print_playlist("SELECT artist, song FROM media WHERE song = '{}'".format(song))
elif choice == '4':
artist = random.choice(list(c.execute("SELECT DISTINCT artist FROM media")))[0]
my_print("choosing songs from random artist: {}".format(artist))
print_playlist("SELECT artist, song FROM media WHERE artist = '{}'".format(artist))
else:
my_print("bye")
exit(0)
| 880 |
474 | #!/usr/bin/env python
from setuptools import setup
setup(
name="asyncio_redis",
author="<NAME>",
version="0.16.0",
license="LICENSE.txt",
classifiers=[
"Development Status :: 4 - Beta",
"Framework :: AsyncIO",
"Intended Audience :: Developers",
"Topic :: Database",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
url="https://github.com/jonathanslenders/asyncio-redis",
description="PEP 3156 implementation of the redis protocol.",
long_description=open("README.rst").read(),
packages=["asyncio_redis"],
python_requires=">=3.6",
extras_require={"hiredis": ["hiredis"]},
)
| 340 |
435 | <filename>pycon-au-2020/videos/oh-no-i-think-my-project-is-outgrowing-my-jupyter-notebook-how-do-i-survive.json
{
"copyright_text": "CC-BY-NC-SA 4.0",
"description": "Lydia Peabody\n\nhttps://2020.pycon.org.au/program/BAAES3\n\nAn example-focused discussion of the pitfalls and strengths of interactive Python notebooks. Topics up for discussion:\r\nNamespace pollution - what is it and why do I care?\r\nSpeed - when might my notebook be holding me back?\r\nPretty pictures - are there times when even for visuals I might skip the notebook?\r\nTransitions - I\u2019m so comfortable using my notebook. How do I change in useful ways without grinding to a halt?\r\nFunctional combinations - can there be a happy middle ground between notebooks and scripts?\n\nProduced by NDV: https://youtube.com/channel/UCQ7dFBzZGlBvtU2hCecsBBg?sub_confirmation=1\n\nPython, PyCon, PyConAU, PyConline\n\nFri Sep 4 11:00:00 2020 at Obvious",
"duration": 1719,
"language": "eng",
"recorded": "2020-09-05",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://2020.pycon.org.au/program/"
},
{
"label": "https://2020.pycon.org.au/program/BAAES3",
"url": "https://2020.pycon.org.au/program/BAAES3"
},
{
"label": "https://youtube.com/channel/UCQ7dFBzZGlBvtU2hCecsBBg?sub_confirmation=1",
"url": "https://youtube.com/channel/UCQ7dFBzZGlBvtU2hCecsBBg?sub_confirmation=1"
}
],
"speakers": [
"<NAME>"
],
"tags": [
"LydiaPeabody",
"PyCon",
"PyConAU",
"PyConline",
"Python",
"pyconau",
"pyconau_2020"
],
"thumbnail_url": "https://i.ytimg.com/vi/wTH58nuni4I/hqdefault.jpg?sqp=-oaymwEcCNACELwBSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLClzrDiYIqn1_jrgKnmmuoqODVKSg",
"title": "Oh no! I think my project is outgrowing my Jupyter notebook. How do I survive?",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=wTH58nuni4I"
}
]
} | 835 |
348 | {"nom":"Saint-Gilles-les-Forêts","dpt":"Haute-Vienne","inscrits":54,"abs":14,"votants":40,"blancs":4,"nuls":4,"exp":32,"res":[{"panneau":"1","voix":25},{"panneau":"2","voix":7}]} | 77 |
360 | __all__ = ['groups']
from .groups import LieGroupParameter, SO3, RxSO3, SE3, Sim3, cat, stack
| 33 |
421 | <reponame>hamarb123/dotnet-api-docs<filename>samples/snippets/cpp/VS_Snippets_Data/XmlDocument.XmlResolver/CPP/docresolver.cpp
// <snippet1>
#using <System.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Net;
int main()
{
// Supply the credentials necessary to access the DTD file stored on the network.
XmlUrlResolver^ resolver = gcnew XmlUrlResolver;
resolver->Credentials = CredentialCache::DefaultCredentials;
// Create and load the XmlDocument.
XmlDocument^ doc = gcnew XmlDocument;
doc->XmlResolver = resolver; // Set the resolver.
doc->Load( "book5.xml" );
// Display the entity replacement text which is pulled from the DTD file.
Console::WriteLine( doc->DocumentElement->LastChild->InnerText );
}
// </snippet1>
| 325 |
356 | <reponame>svishevsky/testcontainers-spring-boot
package com.playtika.test.mongodb;
import com.playtika.test.common.operations.NetworkTestOperations;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.data.Offset;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.Callable;
import static java.time.Duration.ofMillis;
import static org.assertj.core.api.Assertions.assertThat;
@Slf4j
@SpringBootTest(
properties = {
"embedded.mongodb.install.enabled=true",
"spring.data.mongodb.uri=mongodb://${embedded.mongodb.host}:${embedded.mongodb.port}/${embedded.mongodb.database}"
}
,classes = EmbeddedMongodbBootstrapConfigurationTest.TestConfiguration.class
)
public class EmbeddedMongodbBootstrapConfigurationTest {
@Autowired
MongoTemplate mongoTemplate;
@Autowired
ConfigurableEnvironment environment;
@Autowired
NetworkTestOperations mongodbNetworkTestOperations;
@Test
public void shouldSaveAndGet() {
String someId = UUID.randomUUID().toString();
Foo foo = new Foo(someId, "foo", Instant.parse("2019-09-26T07:57:12.801Z"), -42L);
mongoTemplate.save(foo);
assertThat(mongoTemplate.findById(someId, Foo.class)).isEqualTo(foo);
}
@Test
public void shouldEmulateLatency() throws Exception {
mongodbNetworkTestOperations.withNetworkLatency(ofMillis(1000),
() -> assertThat(durationOf(() -> mongoTemplate.findById("any", Foo.class)))
.isCloseTo(1000L, Offset.offset(100L))
);
assertThat(durationOf(() -> mongoTemplate.findById("any", Foo.class)))
.isLessThan(100L);
}
@Test
public void propertiesAreAvailable() {
assertThat(environment.getProperty("embedded.mongodb.port")).isNotEmpty();
assertThat(environment.getProperty("embedded.mongodb.host")).isNotEmpty();
assertThat(environment.getProperty("embedded.mongodb.database")).isNotEmpty();
}
private static long durationOf(Callable<?> op) throws Exception {
long start = System.currentTimeMillis();
op.call();
return System.currentTimeMillis() - start;
}
@Value
static class Foo {
@Id
String someId;
String someString;
Instant someTimestamp;
Long someNumber;
}
@EnableAutoConfiguration
@Configuration
static class TestConfiguration {
}
}
| 1,138 |
619 | package com.jzh.news.entity;
import java.io.Serializable;
/**
* Created by jzh on 2015/9/28.
*/
public class News_pinglun implements Serializable {
private int pid;
private int pcid;
private String user;
private String plocation;
private String ptime;
private String pcontent;
private String pzan;
//plid, user, location, time,
//content
public News_pinglun(int pcid, String user, String plocation, String ptime,
String pcontent, String pzan) {
super();
this.pcid = pcid;
this.user = user;
this.plocation = plocation;
this.ptime = ptime;
this.pcontent = pcontent;
this.pzan = pzan;
}
public News_pinglun(int pid, int pcid, String user, String plocation,
String ptime, String pcontent, String pzan) {
super();
this.pid = pid;
this.pcid = pcid;
this.user = user;
this.plocation = plocation;
this.ptime = ptime;
this.pcontent = pcontent;
this.pzan = pzan;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getPcid() {
return pcid;
}
public void setPcid(int pcid) {
this.pcid = pcid;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPlocation() {
return plocation;
}
public void setPlocation(String plocation) {
this.plocation = plocation;
}
public String getPtime() {
return ptime;
}
public void setPtime(String ptime) {
this.ptime = ptime;
}
public String getPcontent() {
return pcontent;
}
public void setPcontent(String pcontent) {
this.pcontent = pcontent;
}
public String getPzan() {
return pzan;
}
public void setPzan(String pzan) {
this.pzan = pzan;
}
public News_pinglun() {
}
}
| 683 |
721 | /**
* Copyright 2011 <NAME> <<EMAIL>>
*
* 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 brut.androlib;
import brut.androlib.java.AndrolibJava;
import brut.androlib.res.AndrolibResources;
import brut.androlib.res.data.ResPackage;
import brut.androlib.res.data.ResTable;
import brut.androlib.res.util.ExtFile;
import brut.androlib.src.SmaliBuilder;
import brut.androlib.src.SmaliDecoder;
import brut.common.BrutException;
import brut.directory.*;
import brut.util.BrutIO;
import brut.util.OS;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
/**
* @author <NAME> <<EMAIL>>
*/
public class Androlib {
private final AndrolibResources mAndRes = new AndrolibResources();
public ResTable getResTable(ExtFile apkFile) throws AndrolibException {
return mAndRes.getResTable(apkFile);
}
public void decodeSourcesRaw(ExtFile apkFile, File outDir, boolean debug)
throws AndrolibException {
try {
if (debug) {
LOGGER.warning("Debug mode not available.");
}
Directory apk = apkFile.getDirectory();
LOGGER.info("Copying raw classes.dex file...");
apkFile.getDirectory().copyToDir(outDir, "classes.dex");
} catch (DirectoryException ex) {
throw new AndrolibException(ex);
}
}
public void decodeSourcesSmali(File apkFile, File outDir, boolean debug)
throws AndrolibException {
try {
File smaliDir = new File(outDir, SMALI_DIRNAME);
OS.rmdir(smaliDir);
smaliDir.mkdirs();
LOGGER.info("Baksmaling...");
SmaliDecoder.decode(apkFile, smaliDir, debug);
} catch (BrutException ex) {
throw new AndrolibException(ex);
}
}
public void decodeSourcesJava(ExtFile apkFile, File outDir, boolean debug)
throws AndrolibException {
LOGGER.info("Decoding Java sources...");
new AndrolibJava().decode(apkFile, outDir);
}
public void decodeResourcesRaw(ExtFile apkFile, File outDir)
throws AndrolibException {
try {
Directory apk = apkFile.getDirectory();
LOGGER.info("Copying raw resources...");
apkFile.getDirectory().copyToDir(outDir, APK_RESOURCES_FILENAMES);
} catch (DirectoryException ex) {
throw new AndrolibException(ex);
}
}
public void decodeResourcesFull(ExtFile apkFile, File outDir,
ResTable resTable) throws AndrolibException {
mAndRes.decode(resTable, apkFile, outDir);
}
public void decodeRawFiles(ExtFile apkFile, File outDir)
throws AndrolibException {
LOGGER.info("Copying assets and libs...");
try {
Directory in = apkFile.getDirectory();
if (in.containsDir("assets")) {
in.copyToDir(outDir, "assets");
}
if (in.containsDir("lib")) {
in.copyToDir(outDir, "lib");
}
} catch (DirectoryException ex) {
throw new AndrolibException(ex);
}
}
public void writeMetaFile(File mOutDir, Map<String, Object> meta)
throws AndrolibException {
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
// options.setIndent(4);
Yaml yaml = new Yaml(options);
FileWriter writer = null;
try {
writer = new FileWriter(new File(mOutDir, "apktool.yml"));
yaml.dump(meta, writer);
} catch (IOException ex) {
throw new AndrolibException(ex);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ex) {}
}
}
}
public Map<String, Object> readMetaFile(ExtFile appDir)
throws AndrolibException {
InputStream in = null;
try {
in = appDir.getDirectory().getFileInput("apktool.yml");
Yaml yaml = new Yaml();
return (Map<String, Object>) yaml.load(in);
} catch (DirectoryException ex) {
throw new AndrolibException(ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {}
}
}
}
public void build(File appDir, File outFile, boolean forceBuildAll,
boolean debug) throws AndrolibException {
build(new ExtFile(appDir), outFile, forceBuildAll, debug);
}
public void build(ExtFile appDir, File outFile, boolean forceBuildAll,
boolean debug) throws AndrolibException {
Map<String, Object> meta = readMetaFile(appDir);
Object t1 = meta.get("isFrameworkApk");
boolean framework = t1 == null ? false : (Boolean) t1;
if (outFile == null) {
String outFileName = (String) meta.get("apkFileName");
outFile = new File(appDir, "dist" + File.separator +
(outFileName == null ? "out.apk" : outFileName));
}
new File(appDir, APK_DIRNAME).mkdirs();
buildSources(appDir, forceBuildAll, debug);
buildResources(appDir, forceBuildAll, framework,
(Map<String, Object>) meta.get("usesFramework"));
buildLib(appDir, forceBuildAll);
buildApk(appDir, outFile, framework);
}
public void buildSources(File appDir, boolean forceBuildAll, boolean debug)
throws AndrolibException {
if (! buildSourcesRaw(appDir, forceBuildAll, debug)
&& ! buildSourcesSmali(appDir, forceBuildAll, debug)
&& ! buildSourcesJava(appDir, forceBuildAll, debug)
) {
LOGGER.warning("Could not find sources");
}
}
public boolean buildSourcesRaw(File appDir, boolean forceBuildAll,
boolean debug) throws AndrolibException {
try {
File working = new File(appDir, "classes.dex");
if (! working.exists()) {
return false;
}
if (debug) {
LOGGER.warning("Debug mode not available.");
}
File stored = new File(appDir, APK_DIRNAME + "/classes.dex");
if (forceBuildAll || isModified(working, stored)) {
LOGGER.info("Copying classes.dex file...");
BrutIO.copyAndClose(new FileInputStream(working),
new FileOutputStream(stored));
}
return true;
} catch (IOException ex) {
throw new AndrolibException(ex);
}
}
public boolean buildSourcesSmali(File appDir, boolean forceBuildAll,
boolean debug) throws AndrolibException {
ExtFile smaliDir = new ExtFile(appDir, "smali");
if (! smaliDir.exists()) {
return false;
}
File dex = new File(appDir, APK_DIRNAME + "/classes.dex");
if (! forceBuildAll) {
LOGGER.info("Checking whether sources has changed...");
}
if (forceBuildAll || isModified(smaliDir, dex)) {
LOGGER.info("Smaling...");
dex.delete();
SmaliBuilder.build(smaliDir, dex, debug);
}
return true;
}
public boolean buildSourcesJava(File appDir, boolean forceBuildAll,
boolean debug) throws AndrolibException {
File javaDir = new File(appDir, "src");
if (! javaDir.exists()) {
return false;
}
File dex = new File(appDir, APK_DIRNAME + "/classes.dex");
if (! forceBuildAll) {
LOGGER.info("Checking whether sources has changed...");
}
if (forceBuildAll || isModified(javaDir, dex)) {
LOGGER.info("Building java sources...");
dex.delete();
new AndrolibJava().build(javaDir, dex);
}
return true;
}
public void buildResources(ExtFile appDir, boolean forceBuildAll,
boolean framework, Map<String, Object> usesFramework)
throws AndrolibException {
if (! buildResourcesRaw(appDir, forceBuildAll)
&& ! buildResourcesFull(appDir, forceBuildAll, framework,
usesFramework)) {
LOGGER.warning("Could not find resources");
}
}
public boolean buildResourcesRaw(ExtFile appDir, boolean forceBuildAll)
throws AndrolibException {
try {
if (! new File(appDir, "resources.arsc").exists()) {
return false;
}
File apkDir = new File(appDir, APK_DIRNAME);
if (! forceBuildAll) {
LOGGER.info("Checking whether resources has changed...");
}
if (forceBuildAll || isModified(
newFiles(APK_RESOURCES_FILENAMES, appDir),
newFiles(APK_RESOURCES_FILENAMES, apkDir))) {
LOGGER.info("Copying raw resources...");
appDir.getDirectory()
.copyToDir(apkDir, APK_RESOURCES_FILENAMES);
}
return true;
} catch (DirectoryException ex) {
throw new AndrolibException(ex);
}
}
public boolean buildResourcesFull(File appDir, boolean forceBuildAll,
boolean framework, Map<String, Object> usesFramework)
throws AndrolibException {
try {
if (! new File(appDir, "res").exists()) {
return false;
}
if (! forceBuildAll) {
LOGGER.info("Checking whether resources has changed...");
}
File apkDir = new File(appDir, APK_DIRNAME);
if (forceBuildAll || isModified(
newFiles(APP_RESOURCES_FILENAMES, appDir),
newFiles(APK_RESOURCES_FILENAMES, apkDir))) {
LOGGER.info("Building resources...");
File apkFile = File.createTempFile("APKTOOL", null);
apkFile.delete();
File ninePatch = new File(appDir, "9patch");
if (! ninePatch.exists()) {
ninePatch = null;
}
mAndRes.aaptPackage(
apkFile,
new File(appDir, "AndroidManifest.xml"),
new File(appDir, "res"),
ninePatch, null, parseUsesFramework(usesFramework),
false, framework
);
Directory tmpDir = new ExtFile(apkFile).getDirectory();
tmpDir.copyToDir(apkDir,
tmpDir.containsDir("res") ? APK_RESOURCES_FILENAMES :
APK_RESOURCES_WITHOUT_RES_FILENAMES);
}
return true;
} catch (IOException ex) {
throw new AndrolibException(ex);
} catch (DirectoryException ex) {
throw new AndrolibException(ex);
}
}
public void buildLib(File appDir, boolean forceBuildAll)
throws AndrolibException {
File working = new File(appDir, "lib");
if (! working.exists()) {
return;
}
File stored = new File(appDir, APK_DIRNAME + "/lib");
if (forceBuildAll || isModified(working, stored)) {
LOGGER.info("Copying libs...");
try {
OS.rmdir(stored);
OS.cpdir(working, stored);
} catch (BrutException ex) {
throw new AndrolibException(ex);
}
}
}
public void buildApk(File appDir, File outApk, boolean framework)
throws AndrolibException {
LOGGER.info("Building apk file...");
if (outApk.exists()) {
outApk.delete();
} else {
File outDir = outApk.getParentFile();
if (outDir != null && ! outDir.exists()) {
outDir.mkdirs();
}
}
File assetDir = new File(appDir, "assets");
if (! assetDir.exists()) {
assetDir = null;
}
mAndRes.aaptPackage(outApk, null, null,
new File(appDir, APK_DIRNAME), assetDir, null, false, framework);
}
public void publicizeResources(File arscFile) throws AndrolibException {
mAndRes.publicizeResources(arscFile);
}
public void installFramework(File frameFile, String tag)
throws AndrolibException {
mAndRes.installFramework(frameFile, tag);
}
public boolean isFrameworkApk(ResTable resTable) {
for (ResPackage pkg : resTable.listMainPackages()) {
if (pkg.getId() < 64) {
return true;
}
}
return false;
}
public static String getVersion() {
String version = ApktoolProperties.get("version");
return version.endsWith("-SNAPSHOT") ?
version.substring(0, version.length() - 9) + '.' +
ApktoolProperties.get("git.commit.id.abbrev")
: version;
}
private File[] parseUsesFramework(Map<String, Object> usesFramework)
throws AndrolibException {
if (usesFramework == null) {
return null;
}
List<Integer> ids = (List<Integer>) usesFramework.get("ids");
if (ids == null || ids.isEmpty()) {
return null;
}
String tag = (String) usesFramework.get("tag");
File[] files = new File[ids.size()];
int i = 0;
for (int id : ids) {
files[i++] = mAndRes.getFrameworkApk(id, tag);
}
return files;
}
private boolean isModified(File working, File stored) {
if (! stored.exists()) {
return true;
}
return BrutIO.recursiveModifiedTime(working) >
BrutIO.recursiveModifiedTime(stored);
}
private boolean isModified(File[] working, File[] stored) {
for (int i = 0; i < stored.length; i++) {
if (! stored[i].exists()) {
return true;
}
}
return BrutIO.recursiveModifiedTime(working) >
BrutIO.recursiveModifiedTime(stored);
}
private File[] newFiles(String[] names, File dir) {
File[] files = new File[names.length];
for (int i = 0; i < names.length; i++) {
files[i] = new File(dir, names[i]);
}
return files;
}
private final static Logger LOGGER =
Logger.getLogger(Androlib.class.getName());
private final static String SMALI_DIRNAME = "smali";
private final static String APK_DIRNAME = "build/apk";
private final static String[] APK_RESOURCES_FILENAMES =
new String[]{"resources.arsc", "AndroidManifest.xml", "res"};
private final static String[] APK_RESOURCES_WITHOUT_RES_FILENAMES =
new String[]{"resources.arsc", "AndroidManifest.xml"};
private final static String[] APP_RESOURCES_FILENAMES =
new String[]{"AndroidManifest.xml", "res"};
}
| 7,310 |
412 | <filename>src/goto-instrument/generate_function_bodies.h<gh_stars>100-1000
/*******************************************************************\
Module: Replace bodies of goto functions
Author: <NAME>.
\*******************************************************************/
#ifndef CPROVER_GOTO_PROGRAMS_GENERATE_FUNCTION_BODIES_H
#define CPROVER_GOTO_PROGRAMS_GENERATE_FUNCTION_BODIES_H
#include <memory>
#include <regex>
#include <util/irep.h>
class goto_functiont;
class goto_modelt;
class message_handlert;
class symbol_tablet;
struct c_object_factory_parameterst;
/// Base class for replace_function_body implementations
class generate_function_bodiest
{
protected:
/// Produce a body for the passed function
/// At this point the body of function is always empty,
/// and all function parameters have identifiers
/// \param function: whose body to generate
/// \param symbol_table: of the current goto program
/// \param function_name: Identifier of function
virtual void generate_function_body_impl(
goto_functiont &function,
symbol_tablet &symbol_table,
const irep_idt &function_name) const = 0;
public:
virtual ~generate_function_bodiest() = default;
/// Replace the function body with one based on the replace_function_body
/// class being used.
/// \param function: whose body to replace
/// \param symbol_table: of the current goto program
/// \param function_name: Identifier of function
void generate_function_body(
goto_functiont &function,
symbol_tablet &symbol_table,
const irep_idt &function_name) const;
private:
/// Generate parameter names for unnamed parameters.
/// CBMC expect functions to have parameter names
/// if they are called and have a body
void generate_parameter_names(
goto_functiont &function,
symbol_tablet &symbol_table,
const irep_idt &function_name) const;
};
std::unique_ptr<generate_function_bodiest> generate_function_bodies_factory(
const std::string &options,
const c_object_factory_parameterst &object_factory_parameters,
const symbol_tablet &symbol_table,
message_handlert &message_handler);
void generate_function_bodies(
const std::regex &functions_regex,
const generate_function_bodiest &generate_function_body,
goto_modelt &model,
message_handlert &message_handler);
/// Generate a clone of \p function_name (labelled with \p call_site_id) and
/// instantiate its body with selective havocing of its parameters.
/// \param function_name: The function whose body should be generated
/// \param call_site_id: the number of the call site
/// \param generate_function_body: the previously constructed body generator
/// \param model: the goto-model to be modified
/// \param message_handler: the message-handler
void generate_function_bodies(
const std::string &function_name,
const std::string &call_site_id,
const generate_function_bodiest &generate_function_body,
goto_modelt &model,
message_handlert &message_handler);
// clang-format off
#define OPT_REPLACE_FUNCTION_BODY \
"(generate-function-body):" \
"(generate-havocing-body):" \
"(generate-function-body-options):"
#define HELP_REPLACE_FUNCTION_BODY \
" --generate-function-body <regex>\n" \
/* NOLINTNEXTLINE(whitespace/line_length) */ \
" Generate bodies for functions matching regex\n" \
" --generate-havocing-body <option>\n" \
/* NOLINTNEXTLINE(whitespace/line_length) */ \
" <fun_name>,params:<p_n1;p_n2;..>\n" \
" or\n" \
/* NOLINTNEXTLINE(whitespace/line_length) */ \
" <fun_name>[,<call-site-id>,params:<p_n1;p_n2;..>]+\n" \
" --generate-function-body-options <option>\n" \
" One of assert-false, assume-false,\n" \
/* NOLINTNEXTLINE(whitespace/line_length) */ \
" nondet-return, assert-false-assume-false and\n" \
" havoc[,params:<regex>][,globals:<regex>]\n" \
" [,params:<p_n1;p_n2;..>]\n" \
" (default: nondet-return)\n"
// clang-format on
#endif // CPROVER_GOTO_PROGRAMS_GENERATE_FUNCTION_BODIES_H
| 1,602 |
14,668 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/display/projecting_observer.h"
#include <memory>
#include <vector>
#include "chromeos/dbus/power/fake_power_manager_client.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/display/fake/fake_display_snapshot.h"
namespace ash {
namespace {
std::unique_ptr<display::DisplaySnapshot> CreateInternalSnapshot() {
return display::FakeDisplaySnapshot::Builder()
.SetId(123)
.SetNativeMode(gfx::Size(1024, 768))
.SetType(display::DISPLAY_CONNECTION_TYPE_INTERNAL)
.Build();
}
std::unique_ptr<display::DisplaySnapshot> CreateVGASnapshot() {
return display::FakeDisplaySnapshot::Builder()
.SetId(456)
.SetNativeMode(gfx::Size(1024, 768))
.SetType(display::DISPLAY_CONNECTION_TYPE_VGA)
.Build();
}
display::DisplayConfigurator::DisplayStateList GetPointers(
const std::vector<std::unique_ptr<display::DisplaySnapshot>>& displays) {
display::DisplayConfigurator::DisplayStateList result;
for (const auto& display : displays)
result.push_back(display.get());
return result;
}
} // namespace
class ProjectingObserverTest : public testing::Test {
public:
ProjectingObserverTest() = default;
void SetUp() override {
chromeos::PowerManagerClient::InitializeFake();
observer_ = std::make_unique<ProjectingObserver>(nullptr);
}
void TearDown() override {
observer_.reset();
chromeos::PowerManagerClient::Shutdown();
}
ProjectingObserverTest(const ProjectingObserverTest&) = delete;
ProjectingObserverTest& operator=(const ProjectingObserverTest&) = delete;
~ProjectingObserverTest() override = default;
protected:
chromeos::FakePowerManagerClient* power_client() {
return chromeos::FakePowerManagerClient::Get();
}
std::unique_ptr<ProjectingObserver> observer_;
};
TEST_F(ProjectingObserverTest, CheckNoDisplay) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
observer_->OnDisplayModeChanged(GetPointers(displays));
EXPECT_EQ(1, power_client()->num_set_is_projecting_calls());
EXPECT_FALSE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest, CheckWithoutInternalDisplay) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateVGASnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
EXPECT_EQ(1, power_client()->num_set_is_projecting_calls());
EXPECT_FALSE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest, CheckWithInternalDisplay) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateInternalSnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
EXPECT_EQ(1, power_client()->num_set_is_projecting_calls());
EXPECT_FALSE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest, CheckWithTwoVGADisplays) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateVGASnapshot());
displays.push_back(CreateVGASnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
EXPECT_EQ(1, power_client()->num_set_is_projecting_calls());
// We need at least 1 internal display to set projecting to on.
EXPECT_FALSE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest, CheckWithInternalAndVGADisplays) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateInternalSnapshot());
displays.push_back(CreateVGASnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
EXPECT_EQ(1, power_client()->num_set_is_projecting_calls());
EXPECT_TRUE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest, CheckWithVGADisplayAndOneCastingSession) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateVGASnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
observer_->OnCastingSessionStartedOrStopped(true);
EXPECT_EQ(2, power_client()->num_set_is_projecting_calls());
// Need at least one internal display to set projecting state to |true|.
EXPECT_FALSE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest, CheckWithInternalDisplayAndOneCastingSession) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateInternalSnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
observer_->OnCastingSessionStartedOrStopped(true);
EXPECT_EQ(2, power_client()->num_set_is_projecting_calls());
EXPECT_TRUE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest, CheckProjectingAfterClosingACastingSession) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateInternalSnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
observer_->OnCastingSessionStartedOrStopped(true);
observer_->OnCastingSessionStartedOrStopped(true);
EXPECT_EQ(3, power_client()->num_set_is_projecting_calls());
EXPECT_TRUE(power_client()->is_projecting());
observer_->OnCastingSessionStartedOrStopped(false);
EXPECT_EQ(4, power_client()->num_set_is_projecting_calls());
EXPECT_TRUE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest,
CheckStopProjectingAfterClosingAllCastingSessions) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateInternalSnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
observer_->OnCastingSessionStartedOrStopped(true);
observer_->OnCastingSessionStartedOrStopped(false);
EXPECT_EQ(3, power_client()->num_set_is_projecting_calls());
EXPECT_FALSE(power_client()->is_projecting());
}
TEST_F(ProjectingObserverTest,
CheckStopProjectingAfterDisconnectingSecondOutput) {
std::vector<std::unique_ptr<display::DisplaySnapshot>> displays;
displays.push_back(CreateInternalSnapshot());
displays.push_back(CreateVGASnapshot());
observer_->OnDisplayModeChanged(GetPointers(displays));
// Remove VGA output.
displays.erase(displays.begin() + 1);
observer_->OnDisplayModeChanged(GetPointers(displays));
EXPECT_EQ(2, power_client()->num_set_is_projecting_calls());
EXPECT_FALSE(power_client()->is_projecting());
}
} // namespace ash
| 2,147 |
456 | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2019-2020 <NAME>
// All rights reserved.
#include <djvUIPy/UIPy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
PYBIND11_MODULE(djvUIPy, m)
{
//! \todo Base classes need to be wrapped first?
wrapWidget(m);
wrapLabel(m);
wrapWindow(m);
}
| 157 |
14,668 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sharing/shared_clipboard/shared_clipboard_message_handler_android.h"
#include "base/android/jni_string.h"
#include "base/trace_event/trace_event.h"
#include "chrome/android/chrome_jni_headers/SharedClipboardMessageHandler_jni.h"
#include "ui/base/clipboard/clipboard_buffer.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
SharedClipboardMessageHandlerAndroid::SharedClipboardMessageHandlerAndroid(
SharingDeviceSource* device_source)
: SharedClipboardMessageHandler(device_source) {}
SharedClipboardMessageHandlerAndroid::~SharedClipboardMessageHandlerAndroid() =
default;
void SharedClipboardMessageHandlerAndroid::ShowNotification(
const std::string& device_name) {
TRACE_EVENT0("sharing",
"SharedClipboardMessageHandlerAndroid::ShowNotification");
JNIEnv* env = base::android::AttachCurrentThread();
Java_SharedClipboardMessageHandler_showNotification(
env, base::android::ConvertUTF8ToJavaString(env, device_name));
}
| 376 |
341 | package com.aventstack.extentreports.markuputils;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
abstract class HtmlList {
@SuppressWarnings("unchecked")
protected String getList(Object object, ListType listType) {
final StringBuilder sb = new StringBuilder();
sb.append("<" + listType.toString().toLowerCase() + ">");
if (object instanceof Map) {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) object).entrySet()) {
sb.append("<li>");
sb.append(entry.getKey());
sb.append(":");
sb.append(entry.getValue());
sb.append("</li>");
}
} else if (object instanceof List || object instanceof Set || object.getClass().isArray()) {
if (object.getClass().isArray())
object = Arrays.asList((Object[])object);
for (Object o : (Collection<Object>) object) {
sb.append("<li>");
sb.append(o.toString());
sb.append("</li>");
}
} else {
sb.append("<li>");
sb.append(object.toString());
sb.append("</li>");
}
sb.append("</" + listType.toString().toLowerCase() + ">");
return sb.toString();
}
}
| 670 |
477 | #!/usr/bin/env python
"""Test faster version of sematic similarity"""
from __future__ import print_function
# Computing basic semantic similarities between GO terms
# Adapted from book chapter written by _<NAME> and <NAME>_
# How to compute semantic similarity between GO terms.
# First we need to write a function that calculates the minimum number
# of branches connecting two GO terms.
import os
import timeit
from collections import Counter
## from goatools.base import get_godag
## from goatools.associations import dnld_assc
## from goatools.semantic import semantic_similarity
## from goatools.semantic import TermCounts
## from goatools.semantic import get_info_content
## from goatools.semantic import deepest_common_ancestor
## from goatools.semantic import resnik_sim
## from goatools.semantic import lin_sim
## from goatools.godag.consts import NS2GO
from goatools.anno.gpad_reader import GpadReader
from goatools.semantic import TermCounts
from tests.utils import get_godag
from tests.utils import get_anno_fullname
from tests.utils import prt_hms
REPO = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
def test_semantic_similarity():
"""Test faster version of sematic similarity"""
godag_r0 = get_godag('go-basic.obo')
## godag_r1 = get_godag('go-basic.obo', optional_attrs=['relationship'])
annoobj = GpadReader(get_anno_fullname('goa_human.gpad'), godag=godag_r0)
ns2assoc = annoobj.get_ns2assc()
assoc = annoobj.get_id2gos('all')
# Get TermCounts for each namespace and for all namespaces
ns2tcnt = {ns:TermCounts(godag_r0, ns2assoc[ns]) for ns in ['BP', 'MF', 'CC']}
tic = timeit.default_timer()
tcntobj = TermCounts(godag_r0, assoc)
prt_hms(tic, 'CUR ACTUAL {N:,} TermCounts initialized'.format(N=len(tcntobj.gocnts)))
# Compare various TermCount counts
for nspc in ['BP', 'MF', 'CC']:
for goid, cnt in ns2tcnt[nspc].gocnts.items():
assert tcntobj.gocnts[goid] == cnt
# Compare old and new count
tic = timeit.default_timer()
gocnts_old = _old_init_count_terms(godag_r0, assoc.values())
assert gocnts_old
prt_hms(tic, 'OLD EXPECTED {N:,} TermCounts initialized'.format(N=len(gocnts_old)))
for goid, cnt_old in gocnts_old.items():
assert cnt_old == tcntobj.gocnts[goid]
def _old_init_count_terms(go2obj, annots_values):
'''
Fills in the counts and overall aspect counts.
'''
gocnts = Counter()
gonotindag = set()
# Fill gocnts with GO IDs in annotations and their corresponding counts
for terms in annots_values: # key is 'gene'
# Make a union of all the terms for a gene, if term parents are
# propagated but they won't get double-counted for the gene
allterms = set()
for go_id in terms:
goobj = go2obj.get(go_id, None)
if goobj is not None:
allterms.add(go_id)
allterms |= goobj.get_all_parents()
else:
gonotindag.add(go_id)
# Add 1 for each GO annotated to this gene product
for parent in allterms:
gocnts[parent] += 1
if gonotindag:
print("{N} Assc. GO IDs not found in the GODag\n".format(N=len(gonotindag)))
return gocnts
if __name__ == '__main__':
test_semantic_similarity()
| 1,321 |
453 | <filename>tce/newlib-1.17.0/newlib/libc/machine/spu/vprintf.c
#include <_ansi.h>
#include <stdio.h>
#include "c99ppe.h"
#ifdef _HAVE_STDC
#include <stdarg.h>
#else
#include <varargs.h>
#endif
#ifdef INTEGER_ONLY
# define vprintf viprintf
#endif
typedef struct
{
_CONST char* fmt;
unsigned int pad0[ 3 ];
va_list ap;
} c99_vprintf_t;
#ifndef _REENT_ONLY
int
_DEFUN (vprintf, (fmt, ap),
_CONST char *fmt _AND
va_list ap)
{
c99_vprintf_t args;
CHECK_STD_INIT(_REENT);
args.fmt = fmt;
va_copy(args.ap,ap);
return __send_to_ppe(SPE_C99_SIGNALCODE, SPE_C99_VPRINTF, &args);
}
#endif /* ! _REENT_ONLY */
| 313 |
5,169 | <reponame>Gantios/Specs
{
"name": "VAMPMaioAdapter",
"version": "1.5.5.3",
"summary": "Maio Adapter for VAMP.",
"description": "VAMP is Video Ad Mediation Platform, including maio and more ad networks. The maio adapter helps you to use maio with VAMP.",
"license": {
"type": "Copyright",
"text": "Copyright (c) Supership Inc. All rights reserved."
},
"authors": "Supership Inc.",
"homepage": "https://github.com/AdGeneration/VAMP-iOS-SDK",
"source": {
"http": "https://d2dylwb3shzel1.cloudfront.net/iOS/VAMPMaioAdapter-v1.5.5.3.zip"
},
"platforms": {
"ios": "9.0"
},
"vendored_frameworks": "VAMPMaioAdapter.framework",
"dependencies": {
"VAMP-SDK": [
"~> 4.0.3-beta"
],
"MaioSDK": [
"~> 1.5.5"
]
}
}
| 337 |
879 | package org.zstack.core.eventlog;
import java.util.ArrayList;
import java.util.Collections;
public class EventLogBuilder {
String content;
String resourceUuid;
String resourceType;
String category;
String trackingId;
ArrayList<Object> arguments = new ArrayList<Object>();
EventLogType type = EventLogType.Info;
public EventLogBuilder resource(String uuid, String type) {
this.resourceUuid = uuid;
this.resourceType = type;
return this;
}
public EventLogBuilder content(String content) {
this.content = content;
return this;
}
public EventLogBuilder type(EventLogType type) {
this.type = type;
return this;
}
public EventLogBuilder trackingId(String trackingId) {
this.trackingId = trackingId;
return this;
}
public EventLogBuilder category(String category) {
this.category = category;
return this;
}
public EventLogBuilder arguments(Object...args) {
if (args != null) {
Collections.addAll(this.arguments, args);
}
return this;
}
}
| 441 |
374 | <filename>CoreFoundation/CFFileDescriptor.h
/* Copyright (c) 2008-2009 <NAME>
Permission is hereby granted,free of charge,to any person obtaining a copy of this software and associated documentation files (the "Software"),to deal in the Software without restriction,including without limitation the rights to use,copy,modify,merge,publish,distribute,sublicense,and/or sell copies of the Software,and to permit persons to whom the Software is furnished to do so,subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#import <CoreFoundation/CFBase.h>
#import <CoreFoundation/CFRunLoop.h>
typedef struct CFFileDescriptor *CFFileDescriptorRef;
typedef int CFFileDescriptorNativeDescriptor;
enum {
kCFFileDescriptorReadCallBack = (1 << 0),
kCFFileDescriptorWriteCallBack = (1 << 1),
};
typedef void (*CFFileDescriptorCallBack)(CFFileDescriptorRef self, CFOptionFlags flags, void *info);
typedef struct {
CFIndex version;
void *info;
CFAllocatorRetainCallBack retain;
CFAllocatorReleaseCallBack release;
CFAllocatorCopyDescriptionCallBack copyDescription;
} CFFileDescriptorContext;
COREFOUNDATION_EXPORT CFTypeID CFFileDescriptorGetTypeID(void);
COREFOUNDATION_EXPORT CFFileDescriptorRef CFFileDescriptorCreate(CFAllocatorRef allocator, CFFileDescriptorNativeDescriptor fd, Boolean closeOnInvalidate, CFFileDescriptorCallBack callback, const CFFileDescriptorContext *context);
COREFOUNDATION_EXPORT CFFileDescriptorNativeDescriptor CFFileDescriptorGetNativeDescriptor(CFFileDescriptorRef self);
COREFOUNDATION_EXPORT void CFFileDescriptorGetContext(CFFileDescriptorRef self, CFFileDescriptorContext *context);
COREFOUNDATION_EXPORT CFRunLoopSourceRef CFFileDescriptorCreateRunLoopSource(CFAllocatorRef allocator, CFFileDescriptorRef self, CFIndex order);
COREFOUNDATION_EXPORT void CFFileDescriptorDisableCallBacks(CFFileDescriptorRef self, CFOptionFlags flags);
COREFOUNDATION_EXPORT void CFFileDescriptorEnableCallBacks(CFFileDescriptorRef self, CFOptionFlags flags);
COREFOUNDATION_EXPORT void CFFileDescriptorInvalidate(CFFileDescriptorRef self);
COREFOUNDATION_EXPORT Boolean CFFileDescriptorIsValid(CFFileDescriptorRef self);
| 854 |
351 | <filename>data/json/countries/er.json
{"name":{"common":"Eritrea","official":"State of Eritrea","Native":{"ara":{"common":"إرتريا","official":"دولة إرتريا"},"eng":{"common":"Eritrea","official":"State of Eritrea"},"tir":{"common":"ኤርትራ","official":"ሃገረ ኤርትራ"}}},"EuMember":false,"LandLocked":false,"Nationality":"","tld":[".er"],"Languages":{"ara":"Arabic","eng":"English","tir":"Tigrinya"},"Translations":{"CYM":{"common":"Eritrea","official":"State of Eritrea"},"DEU":{"common":"Eritrea","official":"Staat Eritrea"},"FRA":{"common":"Érythrée","official":"État d'Érythrée"},"ITA":{"common":"Eritrea","official":"Stato di Eritrea"},"JPN":{"common":"エリトリア","official":"エリトリア国"},"NLD":{"common":"Eritrea","official":"Staat Eritrea"},"RUS":{"common":"Эритрея","official":"Государство Эритрея"}},"currency":["ERN"],"Borders":["DJI","ETH","SDN"],"cca2":"ER","cca3":"ERI","CIOC":"ERI","CCN3":"232","callingCode":["291"],"InternationalPrefix":"00","region":"Africa","subregion":"Eastern Africa","Continent":"Africa","capital":"Asmara","Area":117600,"longitude":"39 00 E","latitude":"15 00 N","MinLongitude":36.483333,"MinLatitude":12.383333,"MaxLongitude":43.114722,"MaxLatitude":18.033333,"Latitude":15.397199630737305,"Longitude":39.087188720703125} | 465 |
6,717 | <reponame>crossmob/WinObjC
//******************************************************************************
//
// Copyright (c) 2016 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#pragma once
#import <CoreAudio/CoreAudioTypes.h>
#import <CoreFoundation/CFArray.h>
#import <CoreFoundation/CFString.h>
#import <CoreMedia/CMBlockBuffer.h>
#import <CoreMedia/CMFormatDescription.h>
#import <CoreMedia/CMTime.h>
#import <CoreMedia/CoreMediaExport.h>
#import <CoreMedia/CMTypes.h>
#import <CoreVideo/CVImageBuffer.h>
typedef struct opaqueCMSampleBuffer* CMSampleBufferRef;
typedef struct {
CMTime duration;
CMTime presentationTimeStamp;
CMTime decodeTimeStamp;
} CMSampleTimingInfo;
typedef OSStatus (*CMSampleBufferMakeDataReadyCallback)(CMSampleBufferRef, void*);
typedef OSStatus (*CMSampleBufferInvalidateCallback)(CMSampleBufferRef, uint64_t);
COREMEDIA_EXPORT OSStatus CMAudioSampleBufferCreateWithPacketDescriptions(CFAllocatorRef allocator,
CMBlockBufferRef dataBuffer,
Boolean dataReady,
CMSampleBufferMakeDataReadyCallback makeDataReadyCallback,
void* makeDataReadyRefcon,
CMFormatDescriptionRef formatDescription,
CMItemCount numSamples,
CMTime sbufPTS,
const AudioStreamPacketDescription* packetDescriptions,
CMSampleBufferRef _Nullable* sBufOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferCallForEachSample(CMSampleBufferRef sbuf,
OSStatus (*callback)(CMSampleBufferRef, CMItemCount, void*),
void* refcon) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferCopySampleBufferForRange(CFAllocatorRef allocator,
CMSampleBufferRef sbuf,
CFRange sampleRange,
CMSampleBufferRef _Nullable* sBufOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferCreate(CFAllocatorRef allocator,
CMBlockBufferRef dataBuffer,
Boolean dataReady,
CMSampleBufferMakeDataReadyCallback makeDataReadyCallback,
void* makeDataReadyRefcon,
CMFormatDescriptionRef formatDescription,
CMItemCount numSamples,
CMItemCount numSampleTimingEntries,
const CMSampleTimingInfo* sampleTimingArray,
CMItemCount numSampleSizeEntries,
const size_t* sampleSizeArray,
CMSampleBufferRef _Nullable* sBufOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferCreateCopy(CFAllocatorRef allocator,
CMSampleBufferRef sbuf,
CMSampleBufferRef _Nullable* sbufCopyOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferCreateCopyWithNewTiming(CFAllocatorRef allocator,
CMSampleBufferRef originalSBuf,
CMItemCount numSampleTimingEntries,
const CMSampleTimingInfo* sampleTimingArray,
CMSampleBufferRef _Nullable* sBufCopyOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferCreateForImageBuffer(CFAllocatorRef allocator,
CVImageBufferRef imageBuffer,
Boolean dataReady,
CMSampleBufferMakeDataReadyCallback makeDataReadyCallback,
void* makeDataReadyRefcon,
CMVideoFormatDescriptionRef formatDescription,
const CMSampleTimingInfo* sampleTiming,
CMSampleBufferRef _Nullable* sBufOut) STUB_METHOD;
COREMEDIA_EXPORT Boolean CMSampleBufferDataIsReady(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(CMSampleBufferRef sbuf,
size_t* bufferListSizeNeededOut,
AudioBufferList* bufferListOut,
size_t bufferListSize,
CFAllocatorRef bbufStructAllocator,
CFAllocatorRef bbufMemoryAllocator,
uint32_t flags,
CMBlockBufferRef _Nullable* blockBufferOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferGetAudioStreamPacketDescriptions(CMSampleBufferRef sbuf,
size_t packetDescriptionsSize,
AudioStreamPacketDescription* packetDescriptionsOut,
size_t* packetDescriptionsSizeNeededOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus
CMSampleBufferGetAudioStreamPacketDescriptionsPtr(CMSampleBufferRef sbuf,
const AudioStreamPacketDescription* _Nullable* packetDescriptionsPtrOut,
size_t* packetDescriptionsSizeOut) STUB_METHOD;
COREMEDIA_EXPORT CMBlockBufferRef CMSampleBufferGetDataBuffer(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CMTime CMSampleBufferGetDecodeTimeStamp(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CMTime CMSampleBufferGetDuration(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CMFormatDescriptionRef CMSampleBufferGetFormatDescription(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CVImageBufferRef CMSampleBufferGetImageBuffer(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CMItemCount CMSampleBufferGetNumSamples(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CMTime CMSampleBufferGetOutputDecodeTimeStamp(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CMTime CMSampleBufferGetOutputDuration(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CMTime CMSampleBufferGetOutputPresentationTimeStamp(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferGetOutputSampleTimingInfoArray(CMSampleBufferRef sbuf,
CMItemCount timingArrayEntries,
CMSampleTimingInfo* timingArrayOut,
CMItemCount* timingArrayEntriesNeededOut) STUB_METHOD;
COREMEDIA_EXPORT CMTime CMSampleBufferGetPresentationTimeStamp(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CFArrayRef CMSampleBufferGetSampleAttachmentsArray(CMSampleBufferRef sbuf, Boolean createIfNecessary) STUB_METHOD;
COREMEDIA_EXPORT size_t CMSampleBufferGetSampleSize(CMSampleBufferRef sbuf, CMItemIndex sampleIndex) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferGetSampleSizeArray(CMSampleBufferRef sbuf,
CMItemCount sizeArrayEntries,
size_t* sizeArrayOut,
CMItemCount* sizeArrayEntriesNeededOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferGetSampleTimingInfo(CMSampleBufferRef sbuf,
CMItemIndex sampleIndex,
CMSampleTimingInfo* timingInfoOut) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferGetSampleTimingInfoArray(CMSampleBufferRef sbuf,
CMItemCount timingArrayEntries,
CMSampleTimingInfo* timingArrayOut,
CMItemCount* timingArrayEntriesNeededOut) STUB_METHOD;
COREMEDIA_EXPORT size_t CMSampleBufferGetTotalSampleSize(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT CFTypeID CMSampleBufferGetTypeID() STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferInvalidate(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT Boolean CMSampleBufferIsValid(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferMakeDataReady(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferSetDataBuffer(CMSampleBufferRef sbuf, CMBlockBufferRef dataBuffer) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferSetDataBufferFromAudioBufferList(CMSampleBufferRef sbuf,
CFAllocatorRef bbufStructAllocator,
CFAllocatorRef bbufMemoryAllocator,
uint32_t flags,
const AudioBufferList* bufferList) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferSetDataReady(CMSampleBufferRef sbuf) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferSetInvalidateCallback(CMSampleBufferRef sbuf,
CMSampleBufferInvalidateCallback invalidateCallback,
uint64_t invalidateRefCon) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferSetOutputPresentationTimeStamp(CMSampleBufferRef sbuf,
CMTime outputPresentationTimeStamp) STUB_METHOD;
COREMEDIA_EXPORT OSStatus CMSampleBufferTrackDataReadiness(CMSampleBufferRef sbuf, CMSampleBufferRef sbufToTrack) STUB_METHOD;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferNotification_DataBecameReady;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferConduitNotification_InhibitOutputUntil;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferConduitNotification_ResetOutput;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferConduitNotification_UpcomingOutputPTSRangeChanged;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferConsumerNotification_BufferConsumed;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferConduitNotificationParameter_ResumeTag;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferConduitNotificationParameter_UpcomingOutputPTSRangeMayOverlapQueuedOutputPTSRange;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferConduitNotificationParameter_MinUpcomingOutputPTS;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferConduitNotificationParameter_MaxUpcomingOutputPTS;
COREMEDIA_EXPORT const CFStringRef kCMSampleAttachmentKey_NotSync;
COREMEDIA_EXPORT const CFStringRef kCMSampleAttachmentKey_PartialSync;
COREMEDIA_EXPORT const CFStringRef kCMSampleAttachmentKey_HasRedundantCoding;
COREMEDIA_EXPORT const CFStringRef kCMSampleAttachmentKey_IsDependedOnByOthers;
COREMEDIA_EXPORT const CFStringRef kCMSampleAttachmentKey_DependsOnOthers;
COREMEDIA_EXPORT const CFStringRef kCMSampleAttachmentKey_EarlierDisplayTimesAllowed;
COREMEDIA_EXPORT const CFStringRef kCMSampleAttachmentKey_DisplayImmediately;
COREMEDIA_EXPORT const CFStringRef kCMSampleAttachmentKey_DoNotDisplay;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_ResetDecoderBeforeDecoding;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_DrainAfterDecoding;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_PostNotificationWhenConsumed;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_ResumeOutput;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_TransitionID;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_TrimDurationAtStart;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_TrimDurationAtEnd;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_SpeedMultiplier;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_Reverse;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_FillDiscontinuitiesWithSilence;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_EmptyMedia;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_PermanentEmptyMedia;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_DisplayEmptyMediaImmediately;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_EndsPreviousSampleDuration;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_SampleReferenceURL;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_SampleReferenceByteOffset;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_GradualDecoderRefresh;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_DroppedFrameReason;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferAttachmentKey_DroppedFrameReasonInfo;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferDroppedFrameReason_FrameWasLate;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferDroppedFrameReason_OutOfBuffers;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferDroppedFrameReason_Discontinuity;
COREMEDIA_EXPORT const CFStringRef kCMSampleBufferDroppedFrameReasonInfo_CameraModeSwitch;
| 7,763 |
575 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_BASE_AUDIO_CAPTURER_SOURCE_H_
#define MEDIA_BASE_AUDIO_CAPTURER_SOURCE_H_
#include <string>
#include <vector>
#include "base/memory/ref_counted.h"
#include "media/base/audio_bus.h"
#include "media/base/audio_parameters.h"
#include "media/base/media_export.h"
namespace media {
class AudioProcessorControls;
// AudioCapturerSource is an interface representing the source for
// captured audio. An implementation will periodically call Capture() on a
// callback object.
class AudioCapturerSource
: public base::RefCountedThreadSafe<media::AudioCapturerSource> {
public:
class CaptureCallback {
public:
// Signals that audio recording has been started. Called asynchronously
// after Start() has completed. If Start() encounters problems before this
// callback can be made, OnCaptureError will be called instead.
// This callback is provided for sources such as local audio sources that
// require asynchronous initialization so not all sources will support this
// notification.
virtual void OnCaptureStarted() {}
// Callback to deliver the captured data from the OS.
virtual void Capture(const AudioBus* audio_source,
base::TimeTicks audio_capture_time,
double volume,
bool key_pressed) = 0;
// Signals an error has occurred.
virtual void OnCaptureError(const std::string& message) = 0;
// Signals the muted state has changed. May be called before
// OnCaptureStarted.
virtual void OnCaptureMuted(bool is_muted) = 0;
// For streams created with audio processing, signals that a controllable
// audio processor has been created.
virtual void OnCaptureProcessorCreated(AudioProcessorControls* controls) {}
protected:
virtual ~CaptureCallback() {}
};
// Sets information about the audio stream format and the device to be used.
// It must be called exactly once before any of the other methods.
virtual void Initialize(const AudioParameters& params,
CaptureCallback* callback) = 0;
// Starts the audio recording.
virtual void Start() = 0;
// Stops the audio recording. This API is synchronous, and no more data
// callback will be passed to the client after it is being called.
virtual void Stop() = 0;
// Sets the capture volume, with range [0.0, 1.0] inclusive.
virtual void SetVolume(double volume) = 0;
// Enables or disables the WebRtc AGC control.
virtual void SetAutomaticGainControl(bool enable) = 0;
// Sets the output device the source should cancel echo from, if
// supported. Must be called on the main thread. Device ids are gotten from
// device enumerations.
virtual void SetOutputDeviceForAec(const std::string& output_device_id) = 0;
protected:
friend class base::RefCountedThreadSafe<AudioCapturerSource>;
virtual ~AudioCapturerSource() {}
};
} // namespace media
#endif // MEDIA_BASE_AUDIO_CAPTURER_SOURCE_H_
| 973 |
1,577 | <gh_stars>1000+
# flake8: noqa
from rastervision.core.analyzer.analyzer import *
from rastervision.core.analyzer.analyzer_config import *
from rastervision.core.analyzer.stats_analyzer import *
from rastervision.core.analyzer.stats_analyzer_config import *
| 85 |
971 | /*
* argument_matchers.hpp
* Copyright (c) 2014 <NAME>.
*
* This program is made available under the terms of the MIT License.
*
* Created on Jan 12, 2015
*/
#pragma once
namespace fakeit {
struct IMatcher : Destructible {
~IMatcher() = default;
virtual std::string format() const = 0;
};
template<typename T>
struct TypedMatcher : IMatcher {
virtual bool matches(const T &actual) const = 0;
};
template<typename T>
struct TypedMatcherCreator {
virtual ~TypedMatcherCreator() = default;
virtual TypedMatcher<T> *createMatcher() const = 0;
};
template<typename T>
struct ComparisonMatcherCreator : public TypedMatcherCreator<T> {
virtual ~ComparisonMatcherCreator() = default;
ComparisonMatcherCreator(const T &arg)
: _expected(arg) {
}
struct Matcher : public TypedMatcher<T> {
Matcher(const T &expected)
: _expected(expected) {
}
const T _expected;
};
const T &_expected;
};
namespace internal {
template<typename T>
struct TypedAnyMatcher : public TypedMatcherCreator<T> {
virtual ~TypedAnyMatcher() = default;
TypedAnyMatcher() {
}
struct Matcher : public TypedMatcher<T> {
virtual bool matches(const T &) const override {
return true;
}
virtual std::string format() const override {
return "Any";
}
};
virtual TypedMatcher<T> *createMatcher() const override {
return new Matcher();
}
};
template<typename T>
struct EqMatcherCreator : public ComparisonMatcherCreator<T> {
virtual ~EqMatcherCreator() = default;
EqMatcherCreator(const T &expected)
: ComparisonMatcherCreator<T>(expected) {
}
struct Matcher : public ComparisonMatcherCreator<T>::Matcher {
Matcher(const T &expected)
: ComparisonMatcherCreator<T>::Matcher(expected) {
}
virtual std::string format() const override {
return TypeFormatter<T>::format(this->_expected);
}
virtual bool matches(const T &actual) const override {
return actual == this->_expected;
}
};
virtual TypedMatcher<T> *createMatcher() const {
return new Matcher(this->_expected);
}
};
template<typename T>
struct GtMatcherCreator : public ComparisonMatcherCreator<T> {
virtual ~GtMatcherCreator() = default;
GtMatcherCreator(const T &expected)
: ComparisonMatcherCreator<T>(expected) {
}
struct Matcher : public ComparisonMatcherCreator<T>::Matcher {
Matcher(const T &expected)
: ComparisonMatcherCreator<T>::Matcher(expected) {
}
virtual bool matches(const T &actual) const override {
return actual > this->_expected;
}
virtual std::string format() const override {
return std::string(">") + TypeFormatter<T>::format(this->_expected);
}
};
virtual TypedMatcher<T> *createMatcher() const override {
return new Matcher(this->_expected);
}
};
template<typename T>
struct GeMatcherCreator : public ComparisonMatcherCreator<T> {
virtual ~GeMatcherCreator() = default;
GeMatcherCreator(const T &expected)
: ComparisonMatcherCreator<T>(expected) {
}
struct Matcher : public ComparisonMatcherCreator<T>::Matcher {
Matcher(const T &expected)
: ComparisonMatcherCreator<T>::Matcher(expected) {
}
virtual bool matches(const T &actual) const override {
return actual >= this->_expected;
}
virtual std::string format() const override {
return std::string(">=") + TypeFormatter<T>::format(this->_expected);
}
};
virtual TypedMatcher<T> *createMatcher() const override {
return new Matcher(this->_expected);
}
};
template<typename T>
struct LtMatcherCreator : public ComparisonMatcherCreator<T> {
virtual ~LtMatcherCreator() = default;
LtMatcherCreator(const T &expected)
: ComparisonMatcherCreator<T>(expected) {
}
struct Matcher : public ComparisonMatcherCreator<T>::Matcher {
Matcher(const T &expected)
: ComparisonMatcherCreator<T>::Matcher(expected) {
}
virtual bool matches(const T &actual) const override {
return actual < this->_expected;
}
virtual std::string format() const override {
return std::string("<") + TypeFormatter<T>::format(this->_expected);
}
};
virtual TypedMatcher<T> *createMatcher() const override {
return new Matcher(this->_expected);
}
};
template<typename T>
struct LeMatcherCreator : public ComparisonMatcherCreator<T> {
virtual ~LeMatcherCreator() = default;
LeMatcherCreator(const T &expected)
: ComparisonMatcherCreator<T>(expected) {
}
struct Matcher : public ComparisonMatcherCreator<T>::Matcher {
Matcher(const T &expected)
: ComparisonMatcherCreator<T>::Matcher(expected) {
}
virtual bool matches(const T &actual) const override {
return actual <= this->_expected;
}
virtual std::string format() const override {
return std::string("<=") + TypeFormatter<T>::format(this->_expected);
}
};
virtual TypedMatcher<T> *createMatcher() const override {
return new Matcher(this->_expected);
}
};
template<typename T>
struct NeMatcherCreator : public ComparisonMatcherCreator<T> {
virtual ~NeMatcherCreator() = default;
NeMatcherCreator(const T &expected)
: ComparisonMatcherCreator<T>(expected) {
}
struct Matcher : public ComparisonMatcherCreator<T>::Matcher {
Matcher(const T &expected)
: ComparisonMatcherCreator<T>::Matcher(expected) {
}
virtual bool matches(const T &actual) const override {
return actual != this->_expected;
}
virtual std::string format() const override {
return std::string("!=") + TypeFormatter<T>::format(this->_expected);
}
};
virtual TypedMatcher<T> *createMatcher() const override {
return new Matcher(this->_expected);
}
};
}
struct AnyMatcher {
} static _;
template<typename T>
internal::TypedAnyMatcher<T> Any() {
internal::TypedAnyMatcher<T> rv;
return rv;
}
template<typename T>
internal::EqMatcherCreator<T> Eq(const T &arg) {
internal::EqMatcherCreator<T> rv(arg);
return rv;
}
template<typename T>
internal::GtMatcherCreator<T> Gt(const T &arg) {
internal::GtMatcherCreator<T> rv(arg);
return rv;
}
template<typename T>
internal::GeMatcherCreator<T> Ge(const T &arg) {
internal::GeMatcherCreator<T> rv(arg);
return rv;
}
template<typename T>
internal::LtMatcherCreator<T> Lt(const T &arg) {
internal::LtMatcherCreator<T> rv(arg);
return rv;
}
template<typename T>
internal::LeMatcherCreator<T> Le(const T &arg) {
internal::LeMatcherCreator<T> rv(arg);
return rv;
}
template<typename T>
internal::NeMatcherCreator<T> Ne(const T &arg) {
internal::NeMatcherCreator<T> rv(arg);
return rv;
}
}
| 4,270 |
386 | <reponame>ccoderJava/bus
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2021 aoju.org <NAME> and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *
********************************************************************************/
package org.aoju.bus.gitlab.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import org.aoju.bus.gitlab.support.JacksonJson;
import org.aoju.bus.gitlab.support.JacksonJsonEnumHelper;
import java.util.Date;
import java.util.Map;
public class ExportStatus {
private Integer id;
private String description;
private String name;
private String nameWithNamespace;
private String path;
private String pathWithNamespace;
private Date createdAt;
private Status exportStatus;
@JsonProperty("_links")
private Map<String, String> links;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameWithNamespace() {
return nameWithNamespace;
}
public void setNameWithNamespace(String nameWithNamespace) {
this.nameWithNamespace = nameWithNamespace;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getPathWithNamespace() {
return pathWithNamespace;
}
public void setPathWithNamespace(String pathWithNamespace) {
this.pathWithNamespace = pathWithNamespace;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Status getExportStatus() {
return exportStatus;
}
public void setExportStatus(Status exportStatus) {
this.exportStatus = exportStatus;
}
public Map<String, String> getLinks() {
return links;
}
public void setLinks(Map<String, String> links) {
this.links = links;
}
@JsonIgnore
public String getLinkByName(String name) {
if (links == null || links.isEmpty()) {
return (null);
}
return (links.get(name));
}
@Override
public String toString() {
return (JacksonJson.toJsonString(this));
}
/**
* Enum representing the status of the export.
*/
public enum Status {
NONE, STARTED, FINISHED,
/**
* Represents that the export process has been completed successfully and the platform is
* performing some actions on the resulted file. For example, sending an email notifying
* the user to download the file, uploading the exported file to a web server, etc.
*/
AFTER_EXPORT_ACTION;
private static JacksonJsonEnumHelper<Status> enumHelper = new JacksonJsonEnumHelper<>(Status.class);
@JsonCreator
public static Status forValue(String value) {
return enumHelper.forValue(value);
}
@JsonValue
public String toValue() {
return (enumHelper.toString(this));
}
@Override
public String toString() {
return (enumHelper.toString(this));
}
}
}
| 2,374 |
710 | <gh_stars>100-1000
package me.panavtec.cleancontacts.domain.interactors.contacts;
import me.panavtec.cleancontacts.domain.interactors.InteractorError;
public class GetContactError implements InteractorError {
}
| 70 |
1,717 | package com.fasterxml.jackson.core.filter;
import com.fasterxml.jackson.core.JsonPointer;
/**
* Simple {@link TokenFilter} implementation that takes a single
* {@link JsonPointer} and matches a single value accordingly.
* Instances are immutable and fully thread-safe, shareable,
* and efficient to use.
*
* @since 2.6
*/
public class JsonPointerBasedFilter extends TokenFilter
{
protected final JsonPointer _pathToMatch;
public JsonPointerBasedFilter(String ptrExpr) {
this(JsonPointer.compile(ptrExpr));
}
public JsonPointerBasedFilter(JsonPointer match) {
_pathToMatch = match;
}
@Override
public TokenFilter includeElement(int index) {
JsonPointer next = _pathToMatch.matchElement(index);
if (next == null) {
return null;
}
if (next.matches()) {
return TokenFilter.INCLUDE_ALL;
}
return new JsonPointerBasedFilter(next);
}
@Override
public TokenFilter includeProperty(String name) {
JsonPointer next = _pathToMatch.matchProperty(name);
if (next == null) {
return null;
}
if (next.matches()) {
return TokenFilter.INCLUDE_ALL;
}
return new JsonPointerBasedFilter(next);
}
@Override
public TokenFilter filterStartArray() {
return this;
}
@Override
public TokenFilter filterStartObject() {
return this;
}
@Override
protected boolean _includeScalar() {
// should only occur for root-level scalars, path "/"
return _pathToMatch.matches();
}
@Override
public String toString() {
return "[JsonPointerFilter at: "+_pathToMatch+"]";
}
}
| 714 |
2,151 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/arc/boot_phase_monitor/arc_instance_throttle.h"
#include "ash/shell.h"
#include "ash/wm/window_util.h"
#include "components/arc/arc_util.h"
#include "ui/wm/public/activation_client.h"
namespace arc {
namespace {
void ThrottleInstance(aura::Window* active) {
SetArcCpuRestriction(!IsArcAppWindow(active));
}
} // namespace
ArcInstanceThrottle::ArcInstanceThrottle() {
if (!ash::Shell::HasInstance()) // for unit testing.
return;
ash::Shell::Get()->activation_client()->AddObserver(this);
ThrottleInstance(ash::wm::GetActiveWindow());
}
ArcInstanceThrottle::~ArcInstanceThrottle() {
if (!ash::Shell::HasInstance())
return;
ash::Shell::Get()->activation_client()->RemoveObserver(this);
}
void ArcInstanceThrottle::OnWindowActivated(ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) {
ThrottleInstance(gained_active);
}
} // namespace arc
| 449 |
5,279 | /*
* 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 org.apache.beam.fn.harness.data;
import org.apache.beam.runners.core.construction.Timer;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.fn.data.CloseableFnDataReceiver;
import org.apache.beam.sdk.fn.data.FnDataReceiver;
import org.apache.beam.sdk.fn.data.InboundDataClient;
import org.apache.beam.sdk.fn.data.LogicalEndpoint;
/**
* The {@link BeamFnTimerClient} is able to forward inbound timers to a {@link FnDataReceiver} and
* provide a receiver for outbound timers. Callers can register a timer {@link LogicalEndpoint} to
* both send and receive timers.
*/
public interface BeamFnTimerClient {
/**
* A handler capable of blocking for inbound timers and also capable of consuming outgoing timers.
* See {@link InboundDataClient} for all details related to handling inbound timers and see {@link
* CloseableFnDataReceiver} for all details related to sending outbound timers.
*/
interface TimerHandler<K> extends InboundDataClient, CloseableFnDataReceiver<Timer<K>> {}
/**
* Registers for a timer handler for for the provided instruction id and target.
*
* <p>The provided coder is used to encode and decode timers. The inbound timers are passed to the
* provided receiver. Any failure during decoding or processing of the timer will complete the
* timer handler exceptionally. On successful termination of the stream, the returned timer
* handler is completed successfully.
*
* <p>The receiver is not required to be thread safe.
*/
<K> TimerHandler<K> register(
LogicalEndpoint timerEndpoint, Coder<Timer<K>> coder, FnDataReceiver<Timer<K>> receiver);
}
| 685 |
735 | <gh_stars>100-1000
package com.mcxiaoke.next.http;
import org.junit.Assert;
/**
* User: mcxiaoke
* Date: 15/7/6
* Time: 14:41
*/
public class BaseTest {
void isTrue(boolean condition) {
Assert.assertTrue(condition);
}
void isFalse(boolean condition) {
Assert.assertFalse(condition);
}
void notNull(Object object) {
Assert.assertNotNull(object);
}
void isNull(Object object) {
Assert.assertNull(object);
}
void isEquals(boolean expected, boolean actual) {
Assert.assertEquals(expected, actual);
}
void isEquals(int expected, int actual) {
Assert.assertEquals(expected, actual);
}
void isEquals(long expected, long actual) {
Assert.assertEquals(expected, actual);
}
void isEquals(Object expected, Object actual) {
Assert.assertEquals(expected, actual);
}
}
| 364 |
1,602 | <filename>third-party/libfabric/libfabric-src/prov/util/src/util_ns.c
/*
* Copyright (c) 2017 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* BSD license below:
*
* 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* A name server is started on each node as a thread within one of
* the processes on that node. It maintains a database that maps
* "services" to "endpoint names". Other processes on the same node
* talk to this name server to update mapping information.
*
* To resolve a "node:service" pair into an provider internal endpoint name
* that can be used as the input of fi_av_insert, a process needs to make
* a query to the name server residing on "node".
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ofi_util.h>
#include <rdma/providers/fi_log.h>
#include <ofi.h>
#include "rbtree.h"
#define OFI_NS_DEFAULT_HOSTNAME "localhost"
enum {
OFI_UTIL_NS_ADD,
OFI_UTIL_NS_DEL,
OFI_UTIL_NS_QUERY,
OFI_UTIL_NS_ACK,
};
#define OFI_NS_VERSION 0
/* Send and received in network-byte order */
struct util_ns_cmd {
uint8_t version;
uint8_t op;
uint16_t reserved; /* TODO: this should be the msg len */
uint32_t status;
};
const size_t cmd_len = sizeof(struct util_ns_cmd);
static int util_ns_map_add(struct util_ns *ns, void *service_in,
void *name_in)
{
void *name, *service;
int ret;
service = calloc(ns->service_len, 1);
if (!service) {
ret = -FI_ENOMEM;
goto err1;
}
memcpy(service, service_in, ns->service_len);
name = calloc(ns->name_len, 1);
if (!name) {
ret = -FI_ENOMEM;
goto err2;
}
memcpy(name, name_in, ns->name_len);
if (rbtFind(ns->map, service)) {
ret = -FI_EADDRINUSE;
goto err3;
}
if (rbtInsert(ns->map, service, name)) {
ret = -FI_ENOMEM;
goto err3;
}
return FI_SUCCESS;
err3:
free(name);
err2:
free(service);
err1:
return ret;
}
static int util_ns_map_del(struct util_ns *ns, void *service_in,
void *name_in)
{
RbtIterator it;
int ret = -FI_ENOENT;
void *service, *name;
it = rbtFind(ns->map, service_in);
if (it) {
rbtKeyValue(ns->map, it, &service, &name);
if (memcmp(name, name_in, ns->name_len))
return ret;
free(service);
free(name);
rbtErase(ns->map, it);
ret = FI_SUCCESS;
}
return ret;
}
static int util_ns_map_lookup(struct util_ns *ns, void *service_in,
void *name_out)
{
RbtIterator it;
void *key, *name;
it = rbtFind(ns->map, service_in);
if (!it)
return -FI_ENOENT;
rbtKeyValue(ns->map, it, &key, (void **)&name);
memcpy(name_out, name, ns->name_len);
if (ns->is_service_wildcard && ns->is_service_wildcard(service_in))
memcpy(service_in, key, ns->service_len);
return FI_SUCCESS;
}
static int util_ns_process_cmd(struct util_ns *ns, struct util_ns_cmd *cmd,
SOCKET sock)
{
int ret = FI_SUCCESS;
size_t io_len = 0;
void *io_buf, *service, *name;
if (cmd->version != OFI_NS_VERSION)
return -FI_ENOSYS;
switch (cmd->op) {
case OFI_UTIL_NS_ADD:
case OFI_UTIL_NS_DEL:
io_len = ns->name_len + ns->service_len;
io_buf = calloc(io_len, 1);
if (!io_buf) {
ret = -FI_ENOMEM;
goto out;
}
ret = ofi_recvall_socket(sock, io_buf, io_len);
if (!ret) {
service = io_buf;
name = (char *) io_buf + ns->service_len;
ret = (cmd->op == OFI_UTIL_NS_ADD) ?
util_ns_map_add(ns, service, name) :
util_ns_map_del(ns, service, name);
} else {
ret = -FI_ENODATA;
}
break;
case OFI_UTIL_NS_QUERY:
io_len = ns->service_len;
io_buf = calloc(cmd_len + ns->service_len + ns->name_len, 1);
if (!io_buf) {
ret = -FI_ENOMEM;
goto out;
}
memcpy(io_buf, cmd, cmd_len);
cmd = io_buf;
service = (char *) io_buf + cmd_len;
name = (char *) service + ns->service_len;
ret = ofi_recvall_socket(sock, service, io_len);
if (!ret) {
cmd->op = OFI_UTIL_NS_ACK;
cmd->status = htonl(util_ns_map_lookup(ns, service, name));
} else {
ret = -FI_ENODATA;
break;
}
if (!cmd->status)
io_len = cmd_len + ns->service_len + ns->name_len;
else
io_len = cmd_len;
ret = ofi_sendall_socket(sock, io_buf, io_len) ?
-FI_ENODATA : FI_SUCCESS;
break;
default:
assert(0);
ret = -FI_ENODATA;
goto out;
}
free(io_buf);
out:
FI_INFO(&core_prov, FI_LOG_CORE,
"Name server processed command - returned %d (%s)\n", ret, fi_strerror(-ret));
return ret;
}
static void util_ns_close_listen(struct util_ns *ns)
{
ofi_close_socket(ns->listen_sock);
ns->listen_sock = INVALID_SOCKET;
}
/*
* We only start one name server among all peer processes. We rely
* on getting an ADDRINUSE error on either bind or listen if another
* process has started the name server.
*/
static int util_ns_listen(struct util_ns *ns)
{
struct addrinfo hints = {
.ai_flags = AI_PASSIVE,
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM
};
struct addrinfo *res, *p;
char *service;
int n = 1, ret;
if (asprintf(&service, "%d", ns->port) < 0)
return -FI_ENOMEM;
ret = getaddrinfo(NULL, service, &hints, &res);
free(service);
if (ret)
return -FI_EADDRNOTAVAIL;
for (p = res; p; p = p->ai_next) {
ns->listen_sock = ofi_socket(p->ai_family, p->ai_socktype,
p->ai_protocol);
if (ns->listen_sock == INVALID_SOCKET)
continue;
(void) setsockopt(ns->listen_sock, SOL_SOCKET, SO_REUSEADDR,
(void *) &n, sizeof(n));
ret = bind(ns->listen_sock, p->ai_addr, (socklen_t) p->ai_addrlen);
if (!ret)
break;
ret = errno;
util_ns_close_listen(ns);
if (ret == EADDRINUSE) {
freeaddrinfo(res);
return -ret;
}
}
freeaddrinfo(res);
if (ns->listen_sock == INVALID_SOCKET)
return -FI_EADDRNOTAVAIL;
ret = listen(ns->listen_sock, 256);
if (ret) {
util_ns_close_listen(ns);
ret = -errno;
}
return ret;
}
static void *util_ns_accept_handler(void *args)
{
struct util_ns *ns = args;
SOCKET conn_sock;
struct util_ns_cmd cmd;
int ret;
while (ns->run) {
conn_sock = accept(ns->listen_sock, NULL, 0);
if (conn_sock == INVALID_SOCKET)
break;
ret = ofi_recvall_socket(conn_sock, &cmd, cmd_len);
if (!ret)
util_ns_process_cmd(ns, &cmd, conn_sock);
ofi_close_socket(conn_sock);
}
return NULL;
}
/*
* Name server API: client side
*/
static SOCKET util_ns_connect_server(struct util_ns *ns, const char *server)
{
struct addrinfo hints = {
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM
};
struct addrinfo *res, *p;
char *service;
SOCKET sockfd = INVALID_SOCKET;
int n;
if (asprintf(&service, "%d", ns->port) < 0)
return INVALID_SOCKET;
n = getaddrinfo(server, service, &hints, &res);
if (n < 0) {
free(service);
return INVALID_SOCKET;
}
for (p = res; p; p = p->ai_next) {
sockfd = ofi_socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockfd != INVALID_SOCKET) {
if (!connect(sockfd, p->ai_addr, (socklen_t) p->ai_addrlen))
break;
ofi_close_socket(sockfd);
sockfd = INVALID_SOCKET;
}
}
freeaddrinfo(res);
free(service);
return sockfd;
}
int ofi_ns_add_local_name(struct util_ns *ns, void *service, void *name)
{
SOCKET sockfd;
int ret;
void *write_buf;
size_t write_len = 0;
struct util_ns_cmd cmd = {
.version = OFI_NS_VERSION,
.op = OFI_UTIL_NS_ADD,
};
if (!ns->is_initialized) {
FI_WARN(&core_prov, FI_LOG_CORE,
"Cannot add local name - name server uninitialized\n");
return -FI_EINVAL;
}
write_buf = calloc(cmd_len + ns->service_len + ns->name_len, 1);
if (!write_buf) {
ret = -FI_ENOMEM;
goto err1;
}
memcpy(write_buf, &cmd, cmd_len);
write_len += cmd_len;
memcpy((void *)((char *)write_buf + write_len), service,
ns->service_len);
write_len += ns->service_len;
memcpy((void *)((char *)write_buf + write_len), name,
ns->name_len);
write_len += ns->name_len;
sockfd = util_ns_connect_server(ns, ns->hostname);
if (sockfd == INVALID_SOCKET) {
ret = -FI_ENODATA;
goto err2;
}
ret = ofi_sendall_socket(sockfd, write_buf, write_len) ?
-FI_ENODATA : FI_SUCCESS;
ofi_close_socket(sockfd);
err2:
free(write_buf);
err1:
return ret;
}
int ofi_ns_del_local_name(struct util_ns *ns, void *service, void *name)
{
SOCKET sockfd;
int ret;
void *write_buf;
size_t write_len = 0;
struct util_ns_cmd cmd = {
.version = OFI_NS_VERSION,
.op = OFI_UTIL_NS_DEL
};
if (!ns->is_initialized)
return -FI_EINVAL;
write_buf = calloc(cmd_len + ns->service_len + ns->name_len, 1);
if (!write_buf) {
ret = -FI_ENOMEM;
goto err1;
}
memcpy(write_buf, &cmd, cmd_len);
write_len += cmd_len;
memcpy((void *)((char *)write_buf + write_len), service,
ns->service_len);
write_len += ns->service_len;
memcpy((void *)((char *)write_buf + write_len), name,
ns->name_len);
write_len += ns->name_len;
sockfd = util_ns_connect_server(ns, ns->hostname);
if (sockfd == INVALID_SOCKET) {
ret = -FI_ENODATA;
goto err2;
}
ret = ofi_sendall_socket(sockfd, write_buf, write_len) ?
-FI_ENODATA : FI_SUCCESS;
ofi_close_socket(sockfd);
err2:
free(write_buf);
err1:
return ret;
}
void *ofi_ns_resolve_name(struct util_ns *ns, const char *server, void *service)
{
void *dest_addr = NULL, *io_buf;
size_t io_len = 0;
SOCKET sockfd;
ssize_t ret = 0;
struct util_ns_cmd cmd = {
.version = OFI_NS_VERSION,
.op = OFI_UTIL_NS_QUERY
};
if (!ns->is_initialized)
return NULL;
sockfd = util_ns_connect_server(ns, server);
if (sockfd == INVALID_SOCKET)
goto err1;
io_buf = calloc(cmd_len + ns->service_len, 1);
if (!io_buf)
goto err2;
memcpy(io_buf, &cmd, cmd_len);
io_len += cmd_len;
memcpy((void *)((char *)io_buf + io_len), service,
ns->service_len);
io_len += ns->service_len;
ret = ofi_sendall_socket(sockfd, io_buf, io_len);
if (ret)
goto err3;
free(io_buf);
io_len = ns->service_len + ns->name_len;
io_buf = calloc(io_len, 1);
if (!io_buf)
goto err2;
ret = ofi_recvall_socket(sockfd, &cmd, cmd_len);
if (ret || cmd.status)
goto err3;
ret = ofi_recvall_socket(sockfd, io_buf, io_len);
if (!ret) {
dest_addr = calloc(ns->name_len, 1);
if (!dest_addr)
goto err3;
io_len = 0;
memcpy(service, (char *) io_buf + io_len, ns->service_len);
io_len += ns->service_len;
memcpy(dest_addr, (char *) io_buf + io_len, ns->name_len);
}
err3:
free(io_buf);
err2:
ofi_close_socket(sockfd);
err1:
return dest_addr;
}
/*
* Name server API: server side
*/
int ofi_ns_start_server(struct util_ns *ns)
{
int ret;
assert(ns->is_initialized);
if (ofi_atomic_inc32(&ns->ref) > 1)
return 0;
ns->map = rbtNew(ns->service_cmp);
if (!ns->map) {
ret = -FI_ENOMEM;
goto err1;
}
ret = util_ns_listen(ns);
if (ret) {
/* EADDRINUSE likely indicates a peer is running the NS */
if (ret == -FI_EADDRINUSE) {
rbtDelete(ns->map);
return 0;
}
goto err2;
}
ns->run = 1;
ret = -pthread_create(&ns->thread, NULL,
util_ns_accept_handler, (void *) ns);
if (ret)
goto err3;
return 0;
err3:
ns->run = 0;
util_ns_close_listen(ns);
err2:
rbtDelete(ns->map);
err1:
FI_WARN(&core_prov, FI_LOG_CORE, "Error starting name server\n");
ofi_atomic_dec32(&ns->ref);
return ret;
}
void ofi_ns_stop_server(struct util_ns *ns)
{
SOCKET sock;
assert(ns->is_initialized);
if (ofi_atomic_dec32(&ns->ref))
return;
if (ns->listen_sock == INVALID_SOCKET)
return;
ns->run = 0;
sock = util_ns_connect_server(ns, ns->hostname);
if (sock != INVALID_SOCKET)
ofi_close_socket(sock);
util_ns_close_listen(ns);
(void) pthread_join(ns->thread, NULL);
rbtDelete(ns->map);
}
/* TODO: This isn't thread safe -- neither are start/stop */
void ofi_ns_init(struct util_ns *ns)
{
assert(ns && ns->name_len && ns->service_len && ns->service_cmp);
if (ns->is_initialized)
return;
ofi_atomic_initialize32(&ns->ref, 0);
ns->listen_sock = INVALID_SOCKET;
if (!ns->hostname)
ns->hostname = OFI_NS_DEFAULT_HOSTNAME;
ns->is_initialized = 1;
}
| 5,751 |
507 | <reponame>spacerace/romfont<gh_stars>100-1000
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL_gfxPrimitives.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <string.h>
#include <SDL/SDL_rotozoom.h>
#define FTYPE8x8 1
#define FTYPE8x16 2
#define FTYPE8x14 3
#define FTYPE8x15 4
int putc_(SDL_Surface *dst, int xoff, int yoff, int fy, int c, uint8_t r, uint8_t g, uint8_t b, uint8_t a);
void draw_zoomed(SDL_Surface *pic, int x, int y, double zoom);
/* SDL Stuff */
SDL_Surface *screen, *charset, *charset_zoomed, *ch;
uint32_t rmask, gmask, bmask, amask;
/* font buffer */
uint8_t buffer[4096];
int main(int argc, char **argv) {
int x, y, c, infile_size, i, fy = 0;
char filename[128], temp[128];
struct stat stbuf;
FILE *f, *f2;
if(argc < 2) {
printf("usage: %s <infile> <outfile>\n", argv[0]);
}
strcpy(filename, argv[1]);
f = fopen(filename, "r");
if(f == NULL) {
printf("cant open input file\n");
exit(-1);
}
strcpy(temp, argv[2]);
f2 = fopen(temp, "w");
if(f == NULL) {
printf("cant open output file\n");
exit(-1);
}
fclose(f2);
/* get filesize */
stat(filename, &stbuf);
infile_size = stbuf.st_size;
printf("displaying '%s' (%dbytes)\n", filename, infile_size);
switch(infile_size) {
case 1024:
printf("1/2 8x8 font (1024)\n");
fy = 8;
memset(buffer, 0xff, 2048);
break;
case 2048:
printf("8x8 font (2048b)\n");
fy = 8;
break;
case 3584:
printf("8x14 font (3584b)\n");
fy = 14;
break;
case 3840:
printf("8x15 font (3840b)\n");
fy = 15;
break;
case 4096:
printf("8x16 font (4096b)\n");
fy = 16;
break;
default:
printf("not a font\n");
exit(-2);
break;
}
/* load font */
for(i = 0; i < infile_size; i++) {
buffer[i] = getc(f);
}
fclose(f);
/* SDL Stuff */
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
#else
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
#endif
SDL_Init(SDL_INIT_VIDEO);
atexit(SDL_Quit);
screen = SDL_SetVideoMode(700, 730, 16, SDL_HWSURFACE);
/* create surfaces that fit 8x16, 8x8 uses only half */
/* create a empty surface that fits a 8x16 font charset with 1px between chars */
charset = SDL_CreateRGBSurface(SDL_SWSURFACE, 72*2, 144*2, 32, rmask, gmask, bmask, amask);
int fx = 8;
/* draw the charset (unzoomed) */
for(y = 0; y < 16; y++) {
for(x = 0; x < 16; x++) {
c = (y*16)+x;
putc_(charset, x*(fx+1), y*(fy+1), fy, c, 255, 255, 255, 255);
}
}
SDL_BlitSurface(charset, NULL, screen, NULL);
printf("writing to '%s'...\r\n", temp);
if(SDL_SaveBMP(charset, temp) < 0) {
printf("error saving bmp.\n");
}
return 0;
}
/* draw a char to surface dst */
int putc_(SDL_Surface *dst, int xoff, int yoff, int fy, int c, uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
int x, y, line_data;
int off = c*fy;
int posx, posy;
for(y = 0; y < fy; y++) {
line_data = buffer[off+y];
for(x = 0; x < 8; x++) {
if((line_data>>x) & 0x01) {
posx = xoff+8-x;
posy = yoff+y;
pixelRGBA(dst, posx, posy, r, g, b, a);
}
}
}
return 0;
}
void draw_zoomed(SDL_Surface *pic, int x, int y, double zoom) {
double angle = 0;
SDL_Surface *tmp;
SDL_Rect tmpRect;
int w, h;
SDL_Rect r;
r = pic->clip_rect;
r.x = x;
r.y = y;
tmpRect = pic->clip_rect;
rotozoomSurfaceSize(tmpRect.w, tmpRect.h, angle, zoom, &w, &h);
tmp = rotozoomSurface(pic, angle, zoom, SMOOTHING_OFF);
SDL_BlitSurface(tmp, NULL, screen, &r);
SDL_FreeSurface(tmp);
}
| 1,848 |
808 | // Copyright (c) 2019 PaddlePaddle Authors. 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.
#include <gtest/gtest.h>
#include <cstring>
#include "lite/api/paddle_use_kernels.h"
#include "lite/api/paddle_use_ops.h"
#include "lite/core/test/arena/framework.h"
#include "lite/tests/utils/fill_data.h"
namespace paddle {
namespace lite {
template <class T>
class FillZerosLikeComputeTester : public arena::TestCase {
protected:
std::string x_ = "x";
std::string out_ = "out";
DDim x_dims_;
public:
FillZerosLikeComputeTester(const Place& place,
const std::string& alias,
const DDim& x_dims)
: TestCase(place, alias), x_dims_(x_dims) {}
void RunBaseline(Scope* scope) override {
auto* out = scope->NewTensor(out_);
auto* x = scope->FindTensor(x_);
out->Resize(x_dims_);
out->set_lod(x->lod());
auto* out_data = out->template mutable_data<T>();
for (int64_t i = 0; i < out->numel(); i++) {
out_data[i] = static_cast<T>(0);
}
}
void PrepareOpDesc(cpp::OpDesc* op_desc) {
op_desc->SetType("fill_zeros_like");
op_desc->SetInput("X", {x_});
op_desc->SetOutput("Out", {out_});
}
void PrepareData() override {
std::vector<T> x(x_dims_.production());
fill_data_rand(
x.data(), static_cast<T>(-1), static_cast<T>(1), x_dims_.production());
SetCommonTensor(x_, x_dims_, x.data());
}
};
template <class T>
void TestFillZerosLike(Place place, float abs_error) {
std::vector<std::vector<int64_t>> x_shapes{
{2, 3, 4, 5}, {2, 3, 4}, {3, 4}, {4}};
std::string alias("def");
auto precision = lite_api::PrecisionTypeTrait<T>::Type();
switch (precision) {
case PRECISION(kFloat):
alias = std::string("float32");
break;
case PRECISION(kInt32):
alias = std::string("int32");
break;
case PRECISION(kInt64):
alias = std::string("int64");
break;
default:
LOG(FATAL) << "unsupported data type: "
<< lite_api::PrecisionToStr(precision);
}
for (auto x_shape : x_shapes) {
std::unique_ptr<arena::TestCase> tester(
new FillZerosLikeComputeTester<T>(place, alias, DDim(x_shape)));
arena::Arena arena(std::move(tester), place, abs_error);
arena.TestPrecision();
}
}
TEST(fill_zeros_like, precision) {
Place place;
float abs_error = 1e-5;
#if defined(LITE_WITH_XPU)
place = TARGET(kXPU);
#elif defined(LITE_WITH_ARM) || defined(LITE_WITH_X86)
place = TARGET(kHost);
#else
return;
#endif
TestFillZerosLike<float>(place, abs_error);
TestFillZerosLike<int>(place, abs_error);
TestFillZerosLike<int64_t>(place, abs_error);
}
} // namespace lite
} // namespace paddle
| 1,314 |
1,844 | import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
def plot(out, history):
plt.figure()
n = max(map(len, history.values()))
plt.xticks(range(n), [v + 1 for v in range(n)])
plt.grid()
for values in history.values():
plt.plot(values)
plt.xlabel("epoch")
plt.legend(list(history))
plt.savefig(out, format="png")
plt.close()
| 181 |
2,151 | //===-- XCoreSelectionDAGInfo.h - XCore SelectionDAG Info -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the XCore subclass for TargetSelectionDAGInfo.
//
//===----------------------------------------------------------------------===//
#ifndef XCORESELECTIONDAGINFO_H
#define XCORESELECTIONDAGINFO_H
#include "llvm/Target/TargetSelectionDAGInfo.h"
namespace llvm {
class XCoreTargetMachine;
class XCoreSelectionDAGInfo : public TargetSelectionDAGInfo {
public:
explicit XCoreSelectionDAGInfo(const XCoreTargetMachine &TM);
~XCoreSelectionDAGInfo();
};
}
#endif
| 249 |
377 | // REQUIRES: system-linux
// RUN: clang -o %t %s -O2 -mno-sse
// RUN: llvm-mctoll -d -I /usr/include/stdio.h -I /usr/include/string.h -I /usr/include/stdlib.h %t
// RUN: clang -o %t1 %t-dis.ll
// RUN: %t1 2>&1 | FileCheck %s
// CHECK: Copied String: Hello
/* Raising the binary of this source file tests
a) correct detection of void return type of wrapper_free()
b) correct return type of functions based on any tail calls -
such as wrapper_strncpy and wrapper_malloc
NOTES:
a) All pointer return types are converted as i64 types.
b) Return type of a function such as
void foo(int i) {
printf("Value %d\n", i);
}
is detected as i32 becasue the binary typically contains a
tail call to printf whose return value type is int. Distinguising
return values of tail calls in a function with void return from one
that returns the tail call return is not possible.
*/
#include <stddef.h>
#include <string.h>
void * __attribute__((noinline))
wrapper_malloc(size_t size) {
return malloc(size);
}
void * __attribute__((noinline))
wrapper_strncpy(void *dest, const char *src, size_t n) {
return strncpy(dest, src, n);
}
void __attribute__((noinline))
wrapper_free(void * p) {
return free(p);
}
#include <stdio.h>
int main(int argc, char **argv) {
char * dest = wrapper_malloc(8);
if (dest == NULL) {
printf("Failed to allocate memory. Exiting\n");
exit(-1);
}
if (wrapper_strncpy(dest, "Hello World!", 6) != dest) {
printf("strncpy failed. Exiting\n");
exit(-1);
}
printf("Copied String: %s\n", dest);
wrapper_free(dest);
return 0;
}
| 647 |
3,678 | //
// Person.h
// CoreDataDemo
//
// Created by <NAME> on 19/11/12.
// Copyright (c) 2012 iOSCreator. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Person : NSManagedObject
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSString * firstName;
@property (nonatomic, retain) NSString * lastName;
@end
| 134 |
1,172 | // Copyright (C) 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.caja.lang.css;
import com.google.caja.SomethingWidgyHappenedError;
import com.google.caja.config.AllowedFileResolver;
import com.google.caja.config.ConfigUtil;
import com.google.caja.config.ImportResolver;
import com.google.caja.lexer.FilePosition;
import com.google.caja.lexer.InputSource;
import com.google.caja.lexer.ParseException;
import com.google.caja.lexer.TokenConsumer;
import com.google.caja.parser.ParseTreeNode;
import com.google.caja.parser.css.CssPropertySignature;
import com.google.caja.parser.js.ArrayConstructor;
import com.google.caja.parser.js.BooleanLiteral;
import com.google.caja.parser.js.Declaration;
import com.google.caja.parser.js.Expression;
import com.google.caja.parser.js.Identifier;
import com.google.caja.parser.js.IntegerLiteral;
import com.google.caja.parser.js.MultiDeclaration;
import com.google.caja.parser.js.ObjectConstructor;
import com.google.caja.parser.js.Statement;
import com.google.caja.parser.js.StringLiteral;
import com.google.caja.parser.js.ValueProperty;
import com.google.caja.parser.quasiliteral.QuasiBuilder;
import com.google.caja.render.JsMinimalPrinter;
import com.google.caja.reporting.EchoingMessageQueue;
import com.google.caja.reporting.MessageContext;
import com.google.caja.reporting.MessageQueue;
import com.google.caja.reporting.RenderContext;
import com.google.caja.reporting.SimpleMessageQueue;
import com.google.caja.tools.BuildCommand;
import com.google.caja.util.Bag;
import com.google.caja.util.Charsets;
import com.google.caja.util.Name;
import com.google.caja.util.Pair;
import com.google.caja.util.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Operates on CSS property signatures to come up with a schema that can be
* used to validate properties.
*
* <p>
* This class produces a javascript file like<pre>
* var CSS_PROP_BIT_x = ...;
* // Sets of allowed literal tokens.
* var CSS_LIT_GROUP = [["auto",...],...];
* var CSS_REGEX = [/^...$/];
* var cssSchema = {
* "float": {
* // Describe the kinds of tokens that can appear in the named
* // property's value and any additional restrictions.
* cssPropBits: CSS_PROP_BIT_x | CSS_PROP_BIT_y | ...,
* // Groups of literal values allowed including keywords and specific
* // numeric values like font-weight:300
* cssLitGroup: [CSS_LIT_GROUP[1],CSS_LIT_GROUP[3],CSS_LIT_GROUP[16]],
* // Schema keys for functions that are allowed (non-transitively).
* cssFns: []
* },
* ...
* // Functions are top-level constructs that have their own filters which
* // can be applied to their actuals.
* "rgba()": { ... },
* ...
* };
* </pre>
*
* <h3>Program Flow</h3>
* <p>
* This class examines a schema and builds a list of all allowed CSS properties, * and each function.
* It then tries to deduce for each property value and function the set of
* keywords/literal token values, how to interpret quoted strings, and what to
* do with loose identifiers that do not match a known keyword.
* <p>
* Once it has collections of keywords/literal-tokens, it tries to group
* commonly co-occuring literal-tokens together to reduce download size.
* Finally, it identifies patterns like {@code border-top} and
* {@code border-bottom} which have identical results.
* <p>
* Finally it builds a javascript parse tree that assigns the {@code css}
* namespace to an object whose keys are CSS property names, and whose
* values are data maps similar to the example code above.
*
* <p>
* "sanitize-css.js" uses this map extensively to sanitize & normalize CSS
* properties, rewriting URIs as needed.
*
* @author <EMAIL>
*/
public class CssPropertyPatterns {
private final CssSchema schema;
public CssPropertyPatterns(CssSchema schema) {
this.schema = schema;
}
static final class CssPropertyData {
final String key;
final CssPropertySignature sig;
final EnumSet<CssPropBit> properties;
final Set<String> literals;
final Set<CssPropertySignature.CallSignature> fns;
CssPropertyData(String key, CssPropertySignature sig) {
assert key.equals(Strings.lower(key)) : key;
this.key = key;
this.sig = sig;
this.properties = EnumSet.noneOf(CssPropBit.class);
this.literals = Sets.newHashSet();
this.fns = Sets.newTreeSet(SignatureComparator.SINGLETON);
}
}
/**
* Generates a data map for the given signature.
*/
public CssPropertyData cssPropertyToData(
String key, CssPropertySignature sig) {
CssPropertyData data = new CssPropertyData(key, sig);
new Inspector(data).inspect();
return data;
}
private static final Set<String> KNOWN_VENDOR_PREFIXES = ImmutableSet.of(
"apple",
"css",
"epub",
"khtml",
"moz",
"ms",
"mso",
"o",
"rim",
"wap",
"webkit",
"xv"
);
public static String withoutVendorPrefix(String cssIdentifier) {
if (cssIdentifier.startsWith("-")) {
int dash = cssIdentifier.indexOf('-', 1);
if (dash >= 0) {
String possiblePrefix = cssIdentifier.substring(1, dash);
if (KNOWN_VENDOR_PREFIXES.contains(possiblePrefix)) {
return cssIdentifier.substring(dash + 1);
}
}
}
return cssIdentifier;
}
public static boolean hasVendorPrefix(String cssIdentifier) {
return !cssIdentifier.equals(withoutVendorPrefix(cssIdentifier));
}
/**
* Walks a property signature to figure out what tokens can comprise its
* value and how non-symbolic tokens like quoted strings, and non-keyword
* identifiers are used.
*/
private class Inspector {
/** Modified in-place as the inspector encounters symbols. */
final CssPropertyData data;
/** Avoid infinitely recursing on symbol cycles. */
private final Bag<String> refsUsed;
private Inspector(CssPropertyData data) {
this.data = data;
this.refsUsed = Bag.newHashBag();
}
void inspect() {
this.data.literals.clear();
this.data.properties.clear();
this.data.fns.clear();
inspectSig(data.sig);
}
private void inspectSig(CssPropertySignature sig) {
// Dispatch to a set of handlers that either append balanced content to
// out, or append cruft and return null.
if (sig instanceof CssPropertySignature.LiteralSignature) {
inspectLit((CssPropertySignature.LiteralSignature) sig);
} else if (sig instanceof CssPropertySignature.RepeatedSignature) {
inspectRep((CssPropertySignature.RepeatedSignature) sig);
} else if (sig instanceof CssPropertySignature.PropertyRefSignature) {
inspectRef((CssPropertySignature.PropertyRefSignature) sig);
} else if (sig instanceof CssPropertySignature.SeriesSignature) {
inspectSeries((CssPropertySignature.SeriesSignature) sig);
} else if (sig instanceof CssPropertySignature.SymbolSignature) {
inspectSymbol((CssPropertySignature.SymbolSignature) sig);
} else if (sig instanceof CssPropertySignature.SetSignature
|| sig instanceof CssPropertySignature.ExclusiveSetSignature) {
inspectSet(sig);
} else if (sig instanceof CssPropertySignature.CallSignature) {
inspectCall((CssPropertySignature.CallSignature) sig);
} else if (sig instanceof CssPropertySignature.ProgIdSignature) {
// Ignore. progid is of interest for old versions of IE and should
// probably be obsoleted.
} else {
throw new SomethingWidgyHappenedError(
sig + " : " + sig.getClass().getSimpleName());
}
}
private void inspectLit(CssPropertySignature.LiteralSignature lit) {
String litValue = lit.getValue();
// Match some trailing whitespace.
// Since some patterns can match nothing (e.g. foo*), we make sure that
// all positive matches are followed by token-breaking space.
// The pattern as a whole can then be matched against the value with one
// space added at the end.
data.literals.add(withoutVendorPrefix(litValue));
}
private void inspectRep(CssPropertySignature.RepeatedSignature sig) {
CssPropertySignature rep = sig.getRepeatedSignature();
inspectSig(rep);
}
private void inspectRef(CssPropertySignature.PropertyRefSignature sig) {
Name propertyName = sig.getPropertyName();
if (refsUsed.incr(propertyName.getCanonicalForm()) == 0) {
CssSchema.CssPropertyInfo p = schema.getCssProperty(propertyName);
if (p == null) {
throw new SomethingWidgyHappenedError(
"Unsatisfied reference " + propertyName);
}
inspectSig(p.sig);
}
}
private void inspectSeries(CssPropertySignature.SeriesSignature sig) {
for (CssPropertySignature child : sig.children()) {
inspectSig(child);
}
}
private void inspectSymbol(CssPropertySignature.SymbolSignature sig) {
Name symbolName = sig.getValue();
CssSchema.SymbolInfo s = schema.getSymbol(symbolName);
if (s != null) {
inspectSig(s.sig);
} else if (!inspectBuiltin(symbolName)) {
throw new SomethingWidgyHappenedError(
"unknown CSS symbol " + symbolName);
}
}
private void inspectSet(CssPropertySignature sig) {
for (CssPropertySignature child : sig.children()) {
inspectSig(child);
}
}
private void inspectCall(CssPropertySignature.CallSignature sig) {
data.fns.add(sig);
}
private boolean inspectBuiltin(Name name) {
String key = name.getCanonicalForm();
int colon = key.lastIndexOf(':');
boolean negative = key.lastIndexOf('-') > colon;
String baseKey = colon >= 0 ? key.substring(0, colon) : key;
CssPropBit b = BUILTIN_PROP_BITS.get(baseKey);
if (b == null) {
return false;
}
data.properties.add(b);
// The negative bit allows for some schemas to reject positioning
// outside the parents' bounding boxes, and negative offsets for clip
// regions.
if (b == CssPropBit.QUANTITY && (colon < 0 || negative)) {
// TODO: maybe tighten this condition
data.properties.add(CssPropBit.NEGATIVE_QUANTITY);
}
return true;
}
}
private static final Map<String, CssPropBit> BUILTIN_PROP_BITS
= new ImmutableMap.Builder<String, CssPropBit>()
.put("angle", CssPropBit.QUANTITY)
.put("frequency", CssPropBit.QUANTITY)
.put("global-name", CssPropBit.GLOBAL_NAME)
.put("hex-color", CssPropBit.HASH_VALUE)
.put("integer", CssPropBit.QUANTITY)
.put("length", CssPropBit.QUANTITY)
.put("number", CssPropBit.QUANTITY)
.put("percentage", CssPropBit.QUANTITY)
.put("property-name", CssPropBit.PROPERTY_NAME)
.put("quotable-word", CssPropBit.UNRESERVED_WORD)
.put("specific-voice", CssPropBit.QSTRING)
.put("string", CssPropBit.QSTRING)
.put("time", CssPropBit.QUANTITY)
.put("unicode-range", CssPropBit.UNICODE_RANGE)
.put("unreserved-word", CssPropBit.UNRESERVED_WORD)
.put("uri", CssPropBit.URL)
.put("z-index", CssPropBit.QUANTITY)
.build();
public static void generatePatterns(CssSchema schema, Appendable out)
throws IOException {
FilePosition unk = FilePosition.UNKNOWN;
CssPropertyPatterns pp = new CssPropertyPatterns(schema);
List<CssSchema.CssPropertyInfo> props
= Lists.newArrayList(schema.getCssProperties());
Collections.sort(
props, new Comparator<CssSchema.CssPropertyInfo>() {
public int compare(CssSchema.CssPropertyInfo a,
CssSchema.CssPropertyInfo b) {
return a.name.compareTo(b.name);
}
});
List<Pair<CssSchema.CssPropertyInfo, CssPropertyData>> propData
= Lists.newArrayList();
List<Expression> stringPool = Lists.newArrayList();
List<Expression> regexPool = Lists.newArrayList();
// Inspect each property's signature in the schema.
Set<String> keys = Sets.newHashSet();
for (CssSchema.CssPropertyInfo prop : props) {
if (!schema.isPropertyAllowed(prop.name)) { continue; }
String key = prop.name.getCanonicalForm();
if (hasVendorPrefix(key)) { continue; }
CssPropertyData data = new CssPropertyData(key, prop.sig);
pp.new Inspector(data).inspect();
propData.add(Pair.pair(prop, data));
keys.add(data.key);
}
// Now, rewalk the list, and add an entry for each unique function signature
// seen, and allocate names for the functions.
Map<CssPropertySignature, CssPropertyData> fnSigToData
= Maps.newTreeMap(SignatureComparator.SINGLETON);
for (int i = 0; i < propData.size() /* Walks over fns as added */; ++i) {
for (CssPropertySignature.CallSignature fn : propData.get(i).b.fns) {
if (!fnSigToData.containsKey(fn)) {
String fnName = fn.getName();
if (fnName == null) { continue; }
String fnKey = allocateKey(fnName + "()", keys);
CssPropertyData fnData = new CssPropertyData(
fnKey, fn.getArgumentsSignature());
pp.new Inspector(fnData).inspect();
fnSigToData.put(fn, fnData);
keys.add(fnKey);
propData.add(Pair.pair((CssSchema.CssPropertyInfo) null, fnData));
}
}
}
Statement poolDecls = null;
if (!stringPool.isEmpty()) {
poolDecls = joinDeclarations(
poolDecls,
new Declaration(unk, new Identifier(unk, "s"),
new ArrayConstructor(unk, stringPool)));
}
if (!regexPool.isEmpty()) {
poolDecls = joinDeclarations(
poolDecls,
new Declaration(unk, new Identifier(unk, "c"),
new ArrayConstructor(unk, regexPool)));
}
// Given keyword sets like
// [['red','blue','green','transparent','inherit',;none'],
// ['red','blue','green'],
// ['inherit','none','bold','bolder']]
// recognize that ['red','blue','green'] probably occurs frequently and
// create a partition like
// [['red','blue','green'],['bold','bolder'],['inherit',none'],
// ['transparent']]
// and then store indices into the array of partition elements with
// CSS property names so they can be unioned as needed.
List<Set<String>> literalSets = Lists.newArrayList();
for (Pair<CssSchema.CssPropertyInfo, CssPropertyData> p : propData) {
literalSets.add(p.b.literals);
}
Partitions.Partition<String> litPartition = Partitions.partition(
literalSets, String.class, null);
List<ArrayConstructor> literalSetArrs = Lists.newArrayList();
for (int[] literalIndices : litPartition.partition) {
List<StringLiteral> literalArr = Lists.newArrayList();
for (int litIndex : literalIndices) {
literalArr.add(StringLiteral.valueOf(
unk, litPartition.universe[litIndex]));
}
literalSetArrs.add(new ArrayConstructor(unk, literalArr));
}
if (!literalSetArrs.isEmpty()) {
poolDecls = joinDeclarations(
poolDecls,
new Declaration(unk, new Identifier(unk, "L"),
new ArrayConstructor(unk, literalSetArrs)));
}
List<ValueProperty> cssSchemaProps = Lists.newArrayList();
StringLiteral propbitsObjKey = new StringLiteral(unk, "cssPropBits");
StringLiteral litgroupObjKey = new StringLiteral(unk, "cssLitGroup");
StringLiteral fnsObjKey = new StringLiteral(unk, "cssFns");
// Keep track of the JS we generate so we can reuse data-objects for
// CSS properties whose filtering schemes are functionally equivalent.
Map<String, String> dataJsToKey = Maps.newHashMap();
boolean hasAliases = false;
for (int propIndex = 0, n = propData.size(); propIndex < n; ++propIndex) {
Pair<CssSchema.CssPropertyInfo, CssPropertyData> d
= propData.get(propIndex);
CssPropertyData data = d.b;
ObjectConstructor dataObj = new ObjectConstructor(unk);
int propBits = 0;
for (CssPropBit b : data.properties) {
propBits |= b.jsValue;
}
dataObj.appendChild(
new ValueProperty(propbitsObjKey, new IntegerLiteral(unk, propBits)));
List<Expression> litGroups = Lists.newArrayList();
for (int groupIndex : litPartition.unions[propIndex]) {
litGroups.add((Expression) QuasiBuilder.substV(
"L[@i]", "i", new IntegerLiteral(unk, groupIndex)));
}
if (!litGroups.isEmpty()) {
dataObj.appendChild(new ValueProperty(
litgroupObjKey, new ArrayConstructor(unk, litGroups)));
}
List<Expression> fnKeyStrs = Lists.newArrayList();
for (CssPropertySignature.CallSignature fn : data.fns) {
String fnKey = fnSigToData.get(fn).key;
fnKeyStrs.add(StringLiteral.valueOf(unk, fnKey));
}
ArrayConstructor fnKeyArray = new ArrayConstructor(unk, fnKeyStrs);
dataObj.appendChild(new ValueProperty(fnsObjKey, fnKeyArray));
String dataJs;
{
StringBuilder js = new StringBuilder();
JsMinimalPrinter tokenConsumer = new JsMinimalPrinter(js);
dataObj.render(new RenderContext(tokenConsumer));
tokenConsumer.noMoreTokens();
dataJs = js.toString();
}
String equivKey = dataJsToKey.get(dataJs);
Expression value = dataObj;
if (equivKey == null) {
dataJsToKey.put(dataJs, data.key);
} else {
value = StringLiteral.valueOf(unk, equivKey);
hasAliases = true;
}
cssSchemaProps.add(new ValueProperty(
unk, StringLiteral.valueOf(unk, data.key), value));
}
ObjectConstructor cssSchema = new ObjectConstructor(unk, cssSchemaProps);
ParseTreeNode js = QuasiBuilder.substV(
""
+ "var cssSchema = (function () {"
+ " @poolDecls?;"
+ " var schema = @cssSchema;"
+ " if (@hasAliases) {"
+ " for (var key in schema) {"
+ " if ('string' === typeof schema[key]"
+ " && Object.hasOwnProperty.call(schema, key)) {"
+ " schema[key] = schema[schema[key]];"
+ " }"
+ " }"
+ " }"
+ " return schema;"
+ "})();",
"poolDecls", poolDecls,
"cssSchema", cssSchema,
"hasAliases", new BooleanLiteral(unk, hasAliases));
TokenConsumer tc = js.makeRenderer(out, null);
js.render(new RenderContext(tc));
tc.noMoreTokens();
out.append(";\n");
}
private static Statement joinDeclarations(
@Nullable Statement decl, Declaration d) {
if (decl == null) { return d; }
if (decl instanceof Declaration) {
decl = new MultiDeclaration(
FilePosition.UNKNOWN, Arrays.asList((Declaration) decl));
}
((MultiDeclaration) decl).appendChild(d);
return decl;
}
public static class Builder implements BuildCommand {
public boolean build(List<File> inputs, List<File> deps,
Map<String, Object> options, File output)
throws IOException {
File symbolsAndPropertiesFile = null;
File functionsFile = null;
for (File input : inputs) {
if (input.getName().endsWith(".json")) {
if (symbolsAndPropertiesFile == null) {
symbolsAndPropertiesFile = input;
} else if (functionsFile == null) {
functionsFile = input;
} else {
throw new IOException("Unused input " + input);
}
}
}
if (symbolsAndPropertiesFile == null) {
throw new IOException("No JSON whitelist for CSS Symbols + Properties");
}
if (functionsFile == null) {
throw new IOException("No JSON whitelist for CSS Functions");
}
FilePosition sps = FilePosition.startOfFile(new InputSource(
symbolsAndPropertiesFile.getAbsoluteFile().toURI()));
FilePosition fns = FilePosition.startOfFile(new InputSource(
functionsFile.getAbsoluteFile().toURI()));
MessageContext mc = new MessageContext();
mc.addInputSource(sps.source());
mc.addInputSource(fns.source());
MessageQueue mq = new EchoingMessageQueue(
new PrintWriter(new OutputStreamWriter(System.err), true), mc, false);
Set<File> inputsAndDeps = Sets.newHashSet();
for (File f : inputs) { inputsAndDeps.add(f.getAbsoluteFile()); }
for (File f : deps) { inputsAndDeps.add(f.getAbsoluteFile()); }
ImportResolver resolver = new AllowedFileResolver(inputsAndDeps);
CssSchema schema;
try {
schema = new CssSchema(
ConfigUtil.loadWhiteListFromJson(
sps.source().getUri(), resolver, mq),
ConfigUtil.loadWhiteListFromJson(
fns.source().getUri(), resolver, mq));
} catch (ParseException ex) {
ex.toMessageQueue(mq);
throw (IOException) new IOException("Failed to parse schema")
.initCause(ex);
}
Writer out = new OutputStreamWriter(
new FileOutputStream(output), Charsets.UTF_8.name());
try {
String currentDate = "" + new Date();
if (currentDate.indexOf("*/") >= 0) {
throw new SomethingWidgyHappenedError("Date should not contain '*/'");
}
out.write("/* Copyright Google Inc.\n");
out.write(" * Licensed under the Apache Licence Version 2.0\n");
out.write(" * Autogenerated at " + currentDate + "\n");
out.write(" * \\@overrides window\n");
out.write(" * \\@provides cssSchema");
for (CssPropBit b : CssPropBit.values()) {
out.write(", CSS_PROP_BIT_");
out.write(Strings.upper(b.name()));
}
out.write(" */\n");
for (CssPropBit b : CssPropBit.values()) {
out.write("/**\n * @const\n * @type {number}\n */\n");
out.write("var CSS_PROP_BIT_");
out.write(Strings.upper(b.name()));
out.write(" = ");
out.write(String.valueOf(b.jsValue));
out.write(";\n");
}
generatePatterns(schema, out);
out.write("if (typeof window !== 'undefined') {\n");
out.write(" window['cssSchema'] = cssSchema;\n");
out.write("}\n");
} finally {
out.close();
}
return true;
}
}
/**
* Adds a key that is not in allocated to it and returns the result.
* The result will have base as a prefix.
*/
private static final String allocateKey(String base, Set<String> allocated) {
base = Strings.lower(base);
int counter = 0;
String candidate = base;
while (!allocated.add(candidate)) {
candidate = base + "#" + counter;
++counter;
}
return candidate;
}
public static void main(String[] args) throws IOException {
CssSchema schema = CssSchema.getDefaultCss21Schema(
new SimpleMessageQueue());
generatePatterns(schema, System.out);
}
/**
* Compares two CSS signatures by type (concrete class), value, and
* recursively by child list.
* The ordering is suitable for use in an Ordered{Set,Map} but has no greater
* significance.
*/
private static final class SignatureComparator
implements Comparator<CssPropertySignature> {
private SignatureComparator() {}
static final SignatureComparator SINGLETON = new SignatureComparator();
@SuppressWarnings("unchecked")
public int compare(CssPropertySignature a, CssPropertySignature b) {
if (a == b) {
return 0;
}
Class<?> aClass = a.getClass();
Class<?> bClass = b.getClass();
if (aClass != bClass) {
return aClass.getName().compareTo(bClass.getName());
}
Object aValue = a.getValue();
Object bValue = b.getValue();
if (aValue != bValue) {
if (aValue == null) {
return -1;
}
if (bValue == null) {
return 1;
}
// Works for the Number and String types typically used as ParseTreeNode
// values, but is not strictly type safe.
@SuppressWarnings("rawtypes")
Comparable aValueCmp = (Comparable) aValue;
@SuppressWarnings("rawtypes")
Comparable bValueCmp = (Comparable) bValue;
return aValueCmp.compareTo(bValueCmp);
}
List<? extends CssPropertySignature> aChildren = a.children();
List<? extends CssPropertySignature> bChildren = b.children();
int size = aChildren.size();
int sizeDelta = size - bChildren.size();
if (sizeDelta != 0) {
return sizeDelta;
}
for (int i = 0; i < size; ++i) {
int childDelta = compare(aChildren.get(i), bChildren.get(i));
if (childDelta != 0) {
return childDelta;
}
}
return 0;
}
}
}
| 10,370 |
1,682 | <gh_stars>1000+
/*
Copyright (c) 2019 LinkedIn Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.linkedin.r2.netty.handler.common;
import com.linkedin.common.callback.Callback;
import com.linkedin.data.ByteString;
import com.linkedin.r2.message.stream.StreamRequest;
import com.linkedin.r2.message.stream.StreamResponse;
import com.linkedin.r2.message.stream.StreamResponseBuilder;
import com.linkedin.r2.message.stream.entitystream.EntityStreams;
import com.linkedin.r2.message.stream.entitystream.Writer;
import com.linkedin.r2.netty.common.NettyChannelAttributes;
import com.linkedin.r2.netty.entitystream.StreamReader;
import com.linkedin.r2.netty.entitystream.StreamWriter;
import com.linkedin.r2.transport.common.WireAttributeHelper;
import com.linkedin.r2.transport.common.bridge.common.TransportCallback;
import com.linkedin.r2.transport.common.bridge.common.TransportResponseImpl;
import com.linkedin.r2.transport.http.client.stream.OrderedEntityStreamReader;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import java.nio.channels.ClosedChannelException;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ScheduledFuture;
import java.util.function.Supplier;
/**
* Implementation of {@link ChannelDuplexHandler} that is responsible for sending {@link StreamRequest},
* receiving {@link StreamResponseBuilder} and response entity in the form of {@link ByteString}s.
*
* This handler also integrates with R2 entity streaming with the help of {@link StreamReader} and
* {@link StreamWriter}.
*
* The implementation guarantees the user {@link Callback} is invoked at most once
* upon receiving response headers, exception, or channel inactive events. Together with timeout
* {@link ScheduledFuture}, the implementation can also guarantee the callback is invoked eventually.
*
* @author <NAME>
* @author <NAME>
*/
@Sharable
public class ClientEntityStreamHandler extends ChannelDuplexHandler
{
private final long _maxContentLength;
public ClientEntityStreamHandler(long maxContentLength)
{
_maxContentLength = maxContentLength;
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
{
if (msg instanceof StreamRequest)
{
StreamRequest request = (StreamRequest) msg;
// Sets reader after the headers have been flushed on the channel
OrderedEntityStreamReader orderedReader = new OrderedEntityStreamReader(ctx, new StreamReader(ctx));
ctx.write(request).addListener(future -> request.getEntityStream().setReader(orderedReader));
}
else
{
ctx.write(msg);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
{
if (msg instanceof StreamResponseBuilder)
{
final StreamResponseBuilder builder = (StreamResponseBuilder) msg;
final Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
headers.putAll(builder.getHeaders());
final Map<String, String> wireAttrs = WireAttributeHelper.removeWireAttributes(headers);
final StreamWriter writer = new StreamWriter(ctx, _maxContentLength);
ctx.channel().attr(NettyChannelAttributes.RESPONSE_WRITER).set(writer);
final StreamResponse response = builder.unsafeSetHeaders(headers).build(EntityStreams.newEntityStream(writer));
final TransportCallback<StreamResponse> callback = ctx.channel().attr(NettyChannelAttributes.RESPONSE_CALLBACK).getAndSet(null);
if (callback != null)
{
callback.onResponse(TransportResponseImpl.success(response, wireAttrs));
}
}
else if (msg instanceof ByteString)
{
final StreamWriter writer = msg == StreamWriter.EOF ?
ctx.channel().attr(NettyChannelAttributes.RESPONSE_WRITER).getAndSet(null) :
ctx.channel().attr(NettyChannelAttributes.RESPONSE_WRITER).get();
if (writer != null)
{
writer.onDataAvailable((ByteString) msg);
}
}
else
{
ctx.fireChannelRead(msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx)
{
tryInvokeCallbackWithError(ctx, ClosedChannelException::new);
tryNotifyWriterWithError(ctx, ClosedChannelException::new);
ctx.fireChannelInactive();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
{
tryInvokeCallbackWithError(ctx, () -> cause);
tryNotifyWriterWithError(ctx, () -> cause);
ctx.fireExceptionCaught(cause);
}
/**
* Attempts to invoke {@link Callback} with the given {@link Throwable}. Callback can be invoked
* at most once guaranteed by channel attributes #getAndSet(null).
* @param ctx Channel handler context
* @param causeSupplier Supplies throwable used to invoke the callback
*/
private void tryInvokeCallbackWithError(ChannelHandlerContext ctx, Supplier<Throwable> causeSupplier)
{
final TransportCallback<StreamResponse> callback = ctx.channel().attr(NettyChannelAttributes.RESPONSE_CALLBACK).getAndSet(null);
if (callback != null)
{
callback.onResponse(TransportResponseImpl.error(causeSupplier.get()));
}
}
/**
* Attempts to notify {@link Writer} with the given {@link Throwable}. Writer can be notified
* at most once guaranteed by channel attributes #getAndSet(null)
* @param ctx Channel handler context
* @param causeSupplier Supplies throwable used to invoke the callback
*/
private void tryNotifyWriterWithError(ChannelHandlerContext ctx, Supplier<Throwable> causeSupplier)
{
final StreamWriter writer = ctx.channel().attr(NettyChannelAttributes.RESPONSE_WRITER).getAndSet(null);
if (writer != null)
{
writer.onError(causeSupplier.get());
}
}
}
| 2,010 |
1,541 | package com.bwssystems.HABridge.plugins.moziot;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MozIotDevice {
@SerializedName("gatewayName")
@Expose
private String gatewayName;
@SerializedName("deviceDetail")
@Expose
private MozillaThing deviceDetail;
public String getGatewayName() {
return gatewayName;
}
public void setGatewayName(String gatewayName) {
this.gatewayName = gatewayName;
}
public MozillaThing getDeviceDetail() {
return deviceDetail;
}
public void setDeviceDetail(MozillaThing deviceDetail) {
this.deviceDetail = deviceDetail;
}
} | 266 |
1,056 | <reponame>timfel/netbeans<filename>php/php.latte/src/org/netbeans/modules/php/latte/completion/LatteDocumentationFactory.java
/*
* 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 org.netbeans.modules.php.latte.completion;
import java.util.MissingResourceException;
import org.openide.util.NbBundle;
/**
*
* @author <NAME> <<EMAIL>>
*/
public interface LatteDocumentationFactory {
LatteDocumentation create(String elementName);
public abstract static class BaseDocumentationFactory implements LatteDocumentationFactory {
protected abstract String getDocumentationKey();
@Override
@NbBundle.Messages("MSG_NoDocumentation=Documentation not found.")
public LatteDocumentation create(String itemName) {
String content;
try {
content = NbBundle.getMessage(LatteDocumentation.Factory.class, getDocumentationKey() + itemName);
} catch (MissingResourceException ex) {
content = Bundle.MSG_NoDocumentation();
}
return new LatteDocumentation.DummyDocumentation(itemName, content);
}
}
public static final class MacroDocumentationFactory extends BaseDocumentationFactory {
private static final LatteDocumentationFactory INSTANCE = new MacroDocumentationFactory();
public static LatteDocumentationFactory getInstance() {
return INSTANCE;
}
private MacroDocumentationFactory() {
}
@Override
protected String getDocumentationKey() {
return "MACRO_"; //NOI18N
}
}
public static final class HelperDocumentationFactory extends BaseDocumentationFactory {
private static final LatteDocumentationFactory INSTANCE = new HelperDocumentationFactory();
public static LatteDocumentationFactory getInstance() {
return INSTANCE;
}
private HelperDocumentationFactory() {
}
@Override
protected String getDocumentationKey() {
return "HELPER_"; //NOI18N
}
}
public static final class KeywordDocumentationFactory extends BaseDocumentationFactory {
private static final LatteDocumentationFactory INSTANCE = new KeywordDocumentationFactory();
public static LatteDocumentationFactory getInstance() {
return INSTANCE;
}
private KeywordDocumentationFactory() {
}
@Override
protected String getDocumentationKey() {
return "KEYWORD_"; //NOI18N
}
}
public static final class IteratorItemDocumentationFactory extends BaseDocumentationFactory {
private static final LatteDocumentationFactory INSTANCE = new IteratorItemDocumentationFactory();
public static LatteDocumentationFactory getInstance() {
return INSTANCE;
}
private IteratorItemDocumentationFactory() {
}
@Override
protected String getDocumentationKey() {
return "ITERATOR_ITEM_"; //NOI18N
}
}
public static final class VariableDocumentationFactory extends BaseDocumentationFactory {
private static final LatteDocumentationFactory INSTANCE = new VariableDocumentationFactory();
public static LatteDocumentationFactory getInstance() {
return INSTANCE;
}
private VariableDocumentationFactory() {
}
@Override
protected String getDocumentationKey() {
return "VARIABLE_"; //NOI18N
}
}
public static final class ControlDocumentationFactory extends BaseDocumentationFactory {
private static final LatteDocumentationFactory INSTANCE = new ControlDocumentationFactory();
public static LatteDocumentationFactory getInstance() {
return INSTANCE;
}
private ControlDocumentationFactory() {
}
@Override
protected String getDocumentationKey() {
return "CONTROL_"; //NOI18N
}
}
}
| 1,664 |
575 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/metrics/metrics_service.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/macros.h"
#include "base/strings/string_number_conversions.h"
#include "components/metrics/metrics_switches.h"
#include "components/metrics/test/test_metrics_service_client.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace metrics {
namespace {
class MetricsServiceClientTest : public testing::Test {
public:
MetricsServiceClientTest() {}
~MetricsServiceClientTest() override {}
private:
DISALLOW_COPY_AND_ASSIGN(MetricsServiceClientTest);
};
} // namespace
TEST_F(MetricsServiceClientTest, TestUploadIntervalDefaultsToStandard) {
TestMetricsServiceClient client;
ASSERT_EQ(client.GetStandardUploadInterval(), client.GetUploadInterval());
}
TEST_F(MetricsServiceClientTest, TestModifyMetricsUploadInterval) {
TestMetricsServiceClient client;
// Flip it a few times to make sure we really can modify it. Values are
// arbitrary (but positive, because the upload interval should be).
int specified_upload_sec = 800;
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kMetricsUploadIntervalSec,
base::NumberToString(specified_upload_sec));
ASSERT_EQ(base::TimeDelta::FromSeconds(specified_upload_sec),
client.GetUploadInterval());
base::CommandLine::ForCurrentProcess()->RemoveSwitch(
switches::kMetricsUploadIntervalSec);
specified_upload_sec = 30;
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kMetricsUploadIntervalSec,
base::NumberToString(specified_upload_sec));
ASSERT_EQ(base::TimeDelta::FromSeconds(specified_upload_sec),
client.GetUploadInterval());
}
TEST_F(MetricsServiceClientTest, TestUploadIntervalLimitedForDos) {
TestMetricsServiceClient client;
// If we set the upload interval too small, it should be limited to prevent
// the possibility of DOS'ing the backend. This should be a safe guess for a
// value strictly smaller than the DOS limit.
int too_short_upload_sec = 2;
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kMetricsUploadIntervalSec,
base::NumberToString(too_short_upload_sec));
// Upload interval should be the DOS rate limit.
ASSERT_EQ(base::TimeDelta::FromSeconds(20), client.GetUploadInterval());
}
} // namespace metrics
| 810 |
2,151 | <filename>src/trusted/service_runtime/win/vm_hole.c
/*
* Copyright (c) 2012 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "native_client/src/shared/platform/nacl_sync_checked.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/service_runtime/thread_suspension.h"
void NaClVmHoleWaitToStartThread(struct NaClApp *nap) {
NaClXMutexLock(&nap->mu);
/* ensure no virtual memory hole may appear */
while (nap->vm_hole_may_exist) {
NaClXCondVarWait(&nap->cv, &nap->mu);
}
++nap->threads_launching;
NaClXMutexUnlock(&nap->mu);
/*
* NB: Dropped lock, so many threads launching can starve VM
* operations. If this becomes a problem in practice, we can use a
* reader/writer lock so that a waiting writer will block new
* readers.
*/
}
void NaClVmHoleThreadStackIsSafe(struct NaClApp *nap) {
NaClXMutexLock(&nap->mu);
if (0 == --nap->threads_launching) {
/*
* Wake up the threads waiting to do VM operations.
*/
NaClXCondVarBroadcast(&nap->cv);
}
NaClXMutexUnlock(&nap->mu);
}
/*
* NaClVmHoleOpeningMu() is called when we are about to open a hole in
* untrusted address space on Windows, where we cannot atomically
* remap pages.
*
* NaClVmHoleOpeningMu() must be called with the mutex nap->mu held.
* NaClVmHoleClosingMu() must later be called to undo the effects of
* this call.
*/
void NaClVmHoleOpeningMu(struct NaClApp *nap) {
/*
* Temporarily stop any of NaCl's threads from launching so that no
* trusted thread's stack will be allocated inside the mmap hole.
*/
while (0 != nap->threads_launching) {
NaClXCondVarWait(&nap->cv, &nap->mu);
}
nap->vm_hole_may_exist = 1;
/*
* For safety, suspend all untrusted threads so that if another
* trusted thread (outside of our control) allocates memory that is
* placed into the mmap hole, untrusted code will not be able to
* write to that location.
*/
NaClUntrustedThreadsSuspendAll(nap, /* save_registers= */ 0);
}
/*
* NaClVmHoleClosingMu() is the counterpart of NaClVmHoleOpeningMu().
* It must be called with the mutex nap->mu held.
*/
void NaClVmHoleClosingMu(struct NaClApp *nap) {
NaClUntrustedThreadsResumeAll(nap);
nap->vm_hole_may_exist = 0;
NaClXCondVarBroadcast(&nap->cv);
}
| 868 |
380 | <gh_stars>100-1000
#include <string.h>
#include <stdlib.h>
#include "w2xconv.h"
int
main(int argc, char **argv)
{
char *dst_path;
size_t path_len;
struct W2XConv *c;
int r;
char *src_path;
if (argc < 2) {
puts("usage : w2xc <in.png>");
return 1;
}
src_path = argv[1];
path_len = strlen(src_path);
dst_path = malloc(path_len + 5);
dst_path[0] = 'm';
dst_path[1] = 'a';
dst_path[2] = 'i';
dst_path[3] = '_';
strcpy(dst_path+4, argv[1]);
c = w2xconv_init(W2XCONV_GPU_AUTO, 0, 0);
r = w2xconv_load_models(c, "models");
if (r < 0) {
goto error;
}
r = w2xconv_convert_file(c, dst_path, src_path, 1, 2.0, 512);
if (r < 0) {
goto error;
}
w2xconv_fini(c);
return 0;
error:
{
char *err = w2xconv_strerror(&c->last_error);
puts(err);
w2xconv_free(err);
}
w2xconv_fini(c);
return 1;
}
| 589 |
450 | /*
* Copyright (C) 2015-2021 <NAME> <<EMAIL>>
* Copyright (C) 2020 <NAME> <<EMAIL>>
*
* Licence: wxWindows Library Licence, Version 3.1
*/
#ifndef __GUM_EXCEPTOR_H__
#define __GUM_EXCEPTOR_H__
#include <glib-object.h>
#include <gum/gummemory.h>
#include <gum/gumprocess.h>
#include <setjmp.h>
G_BEGIN_DECLS
#define GUM_TYPE_EXCEPTOR (gum_exceptor_get_type ())
G_DECLARE_FINAL_TYPE (GumExceptor, gum_exceptor, GUM, EXCEPTOR, GObject)
#if defined (G_OS_WIN32) || defined (__APPLE__)
# define GUM_NATIVE_SETJMP(env) setjmp (env)
# define GUM_NATIVE_LONGJMP longjmp
typedef jmp_buf GumExceptorNativeJmpBuf;
#else
# define GUM_NATIVE_SETJMP(env) sigsetjmp (env, TRUE)
# define GUM_NATIVE_LONGJMP siglongjmp
# if !defined (GUM_GIR_COMPILATION)
typedef sigjmp_buf GumExceptorNativeJmpBuf;
# endif
#endif
typedef struct _GumExceptionDetails GumExceptionDetails;
typedef guint GumExceptionType;
typedef struct _GumExceptionMemoryDetails GumExceptionMemoryDetails;
typedef gboolean (* GumExceptionHandler) (GumExceptionDetails * details,
gpointer user_data);
typedef struct _GumExceptorScope GumExceptorScope;
enum _GumExceptionType
{
GUM_EXCEPTION_ABORT = 1,
GUM_EXCEPTION_ACCESS_VIOLATION,
GUM_EXCEPTION_GUARD_PAGE,
GUM_EXCEPTION_ILLEGAL_INSTRUCTION,
GUM_EXCEPTION_STACK_OVERFLOW,
GUM_EXCEPTION_ARITHMETIC,
GUM_EXCEPTION_BREAKPOINT,
GUM_EXCEPTION_SINGLE_STEP,
GUM_EXCEPTION_SYSTEM
};
struct _GumExceptionMemoryDetails
{
GumMemoryOperation operation;
gpointer address;
};
struct _GumExceptionDetails
{
GumThreadId thread_id;
GumExceptionType type;
gpointer address;
GumExceptionMemoryDetails memory;
GumCpuContext context;
gpointer native_context;
};
struct _GumExceptorScope
{
GumExceptionDetails exception;
/*< private */
gboolean exception_occurred;
gpointer padding[2];
jmp_buf env;
#ifdef __ANDROID__
sigset_t mask;
#endif
GumExceptorScope * next;
};
GUM_API void gum_exceptor_disable (void);
GUM_API GumExceptor * gum_exceptor_obtain (void);
GUM_API void gum_exceptor_add (GumExceptor * self, GumExceptionHandler func,
gpointer user_data);
GUM_API void gum_exceptor_remove (GumExceptor * self, GumExceptionHandler func,
gpointer user_data);
#if defined (_MSC_VER) && GLIB_SIZEOF_VOID_P == 8
/*
* On MSVC/64-bit setjmp() is actually an intrinsic that calls _setjmp() with a
* a hidden second argument specifying the frame pointer. This makes sense when
* the longjmp() is guaranteed to happen from code we control, but is not
* reliable otherwise.
*/
# define gum_exceptor_try(self, scope) ( \
_gum_exceptor_prepare_try (self, scope), \
((int (*) (jmp_buf env, void * frame_pointer)) _setjmp) ( \
(scope)->env, NULL) == 0)
#else
# define gum_exceptor_try(self, scope) ( \
_gum_exceptor_prepare_try (self, scope), \
GUM_NATIVE_SETJMP ((scope)->env) == 0)
#endif
GUM_API gboolean gum_exceptor_catch (GumExceptor * self,
GumExceptorScope * scope);
GUM_API gboolean gum_exceptor_has_scope (GumExceptor * self,
GumThreadId thread_id);
GUM_API gchar * gum_exception_details_to_string (
const GumExceptionDetails * details);
GUM_API void _gum_exceptor_prepare_try (GumExceptor * self,
GumExceptorScope * scope);
G_END_DECLS
#endif
| 1,251 |
665 | <filename>testing/MLDB-2161-utf8-in-script-apply.py
# coding=utf-8 #
# MLDB-2161-utf8-in-script-apply.py
# <NAME>, 2017-03-08
# This file is part of MLDB. Copyright 2017 mldb.ai inc. All rights reserved.
#
from mldb import mldb, MldbUnitTest, ResponseException
class MLDB2161Utf8InScriptApply(MldbUnitTest): # noqa
def test_python_script_apply_with_utf8(self):
mldb.put("/v1/functions/filter_top_themes", {
"type": "script.apply",
"params": {
"language": 'python',
"scriptConfig": {
"source": """
from mldb import mldb
# retrieve all themes
mldb.log(mldb.script.args)
request.set_return([[str(mldb.script.args[0][1]), 0, '1970-01-01T00:00:00.0000000Z']])
"""
}
}
})
self.assertTableResultEquals(mldb.query("""
SELECT filter_top_themes(
{{"Politique Provinciale":2, "Élections":1, "Thèmes et sous-thàmes":0} AS args}
) AS *
"""),
[
[
"_rowName",
"return.['Thèmes et sous-thàmes', [0, '-Inf']]"
],
[
"result",
0
]
]
)
if __name__ == '__main__':
mldb.run_tests()
| 739 |
483 | <filename>nitrite/src/main/java/org/dizitart/no2/migration/commands/RenameField.java<gh_stars>100-1000
package org.dizitart.no2.migration.commands;
import lombok.AllArgsConstructor;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteId;
import org.dizitart.no2.collection.operation.IndexManager;
import org.dizitart.no2.common.Fields;
import org.dizitart.no2.common.tuples.Pair;
import org.dizitart.no2.index.IndexDescriptor;
import java.util.Collection;
/**
* A command to rename a document field.
*
* @author <NAME>
* @since 4.0
*/
@AllArgsConstructor
public class RenameField extends BaseCommand implements Command {
private final String collectionName;
private final String oldName;
private final String newName;
@Override
public void execute(Nitrite nitrite) {
initialize(nitrite, collectionName);
try(IndexManager indexManager = new IndexManager(oldName, nitrite.getConfig())) {
Fields oldField = Fields.withNames(oldName);
Collection<IndexDescriptor> matchingIndexDescriptors
= indexManager.findMatchingIndexDescriptors(oldField);
for (Pair<NitriteId, Document> entry : nitriteMap.entries()) {
Document document = entry.getSecond();
if (document.containsKey(oldName)) {
Object value = document.get(oldName);
document.put(newName, value);
document.remove(oldName);
nitriteMap.put(entry.getFirst(), document);
}
}
if (!matchingIndexDescriptors.isEmpty()) {
for (IndexDescriptor matchingIndexDescriptor : matchingIndexDescriptors) {
String indexType = matchingIndexDescriptor.getIndexType();
Fields oldIndexFields = matchingIndexDescriptor.getIndexFields();
Fields newIndexFields = getNewIndexFields(oldIndexFields, oldName, newName);
operations.dropIndex(matchingIndexDescriptor.getIndexFields());
operations.createIndex(newIndexFields, indexType);
}
}
}
}
private Fields getNewIndexFields(Fields oldIndexFields, String oldName, String newName) {
Fields newIndexFields = new Fields();
for (String fieldName : oldIndexFields.getFieldNames()) {
if (fieldName.equals(oldName)) {
newIndexFields.addField(newName);
} else {
newIndexFields.addField(fieldName);
}
}
return newIndexFields;
}
}
| 1,156 |
3,702 | <gh_stars>1000+
/*
* 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 app.metatron.discovery.common.revision;
import com.google.common.collect.Maps;
import org.hibernate.envers.boot.internal.EnversService;
import org.hibernate.envers.event.spi.EnversPostInsertEventListenerImpl;
import org.hibernate.event.spi.PostInsertEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import app.metatron.discovery.common.GlobalObjectMapper;
import app.metatron.discovery.common.StatLogger;
import app.metatron.discovery.domain.revision.MetatronRevisionDto;
import app.metatron.discovery.domain.revision.MetatronRevisionEntity;
public class CustomEnversPostInsertEventListener extends EnversPostInsertEventListenerImpl {
private static Logger LOGGER = LoggerFactory.getLogger(CustomEnversPostInsertEventListener.class);
public CustomEnversPostInsertEventListener(EnversService enversService) {
super(enversService);
}
@Override
public void onPostInsert(PostInsertEvent event) {
try {
String entityName = event.getPersister().getEntityName();
if (entityName.endsWith("_AUD")) {
LOGGER.debug(GlobalObjectMapper.writeValueAsString(event.getEntity()));
Map dataMap = (HashMap) event.getEntity();
String revisionType = dataMap.get("REVTYPE").toString();
MetatronRevisionDto metatronRevisionDto = new MetatronRevisionDto();
HashMap<String, Object> additionalInformation = Maps.newHashMap();
if ("MOD".equals(revisionType)) {
String modifiedFlagSuffix = this.getEnversService().getGlobalConfiguration().getModifiedFlagSuffix();
Iterator iterator = dataMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry)iterator.next();
String key = entry.getKey();
if (key.endsWith(modifiedFlagSuffix) && entry.getValue() != null && Boolean.parseBoolean(entry.getValue().toString())) {
String propertyName = key.substring(0, key.length() - modifiedFlagSuffix.length());
additionalInformation.put(propertyName, dataMap.get(propertyName));
}
}
} else {
if (entityName.indexOf("User_AUD") > -1) {
additionalInformation.put("fullName", dataMap.get("fullName"));
} else if (entityName.indexOf("Group_AUD") > -1) {
additionalInformation.put("name", dataMap.get("name"));
} else if (entityName.indexOf("GroupMember_AUD") > -1) {
additionalInformation.put("group_id", dataMap.get("group_id"));
additionalInformation.put("memberId", dataMap.get("memberId"));
additionalInformation.put("memberName", dataMap.get("memberName"));
} else if (entityName.indexOf("RoleDirectory_AUD") > -1) {
additionalInformation.put("role_id", dataMap.get("role_id"));
additionalInformation.put("type", dataMap.get("type"));
additionalInformation.put("directoryId", dataMap.get("directoryId"));
additionalInformation.put("directoryName", dataMap.get("directoryName"));
}
}
metatronRevisionDto.setAdditionalInformation(additionalInformation);
Map originalId = (HashMap) dataMap.get("originalId");
MetatronRevisionEntity rev = (MetatronRevisionEntity) originalId.get("REV");
metatronRevisionDto.setRevisionType(revisionType);
metatronRevisionDto.setRevisionDate(new SimpleDateFormat(StatLogger.DATE_FORMAT).format(rev.getRevisionDate()));
metatronRevisionDto.setUserName(rev.getUsername());
metatronRevisionDto.setTargetId(originalId.get("id").toString());
metatronRevisionDto.setTargetType(entityName.substring(entityName.lastIndexOf(".") +1).replace("_AUD", "").toUpperCase());
StatLogger.revision(metatronRevisionDto);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
super.onPostInsert(event);
}
}
| 1,675 |
488 | // -*- C++ -*-
#ifndef __LTL_H__
#define __LTL_H__
//#include <boost/shared_ptr.hpp>
#include <string>
#include <iostream>
#include <sstream>
#include <cassert>
extern FILE* ltl_input;
extern int ltl_parse();
extern bool ltl_eof;
extern unsigned short ltl_label;
/// Linear Temporal Logic (LTL) Abstract syntax tree (AST)
///
/// \authors <pre>
///
/// Copyright (c) 2012 Lawrence Livermore National Security, LLC.
/// Produced at the Lawrence Livermore National Laboratory
/// Written by <NAME> <<EMAIL>>.
///
/// UCRL-CODE-155962.
/// All rights reserved.
///
/// This file is part of ROSE. For details, see http://www.rosecompiler.org/.
/// Please read the COPYRIGHT file for Our Notice and for the BSD License.
///
/// </pre>
///
/// \date 2012
/// \author <NAME>
namespace CodeThorn {
namespace LTL {
/// Inherited Attribute for visitor pattern
class InheritedAttribute {};
//MS: removed smart pointers
//typedef boost::shared_ptr<InheritedAttribute> IAttr;
typedef InheritedAttribute* IAttr;
class Expr;
class InputSymbol;
class OutputSymbol;
class NegInputSymbol;
class NegOutputSymbol;
class Not;
class Next;
class Eventually;
class Globally;
class And;
class Or;
class Until;
class WeakUntil;
class Release;
class True;
class False;
enum NodeType {
e_Error=0,
e_InputSymbol, e_OutputSymbol, e_NegInputSymbol, e_NegOutputSymbol,
e_True, e_False,
e_Not, e_Next, e_Eventually, e_Globally, e_And, e_Or, e_Until,
e_WeakUntil, e_Release };
/**
* Abstract visitor pattern Visitor base class for LTL expressions.
*/
class BottomUpVisitor {
public:
virtual void visit(const InputSymbol* e) {}
virtual void visit(const OutputSymbol* e) {}
virtual void visit(const NegInputSymbol* e) {}
virtual void visit(const NegOutputSymbol* e) {}
virtual void visit(const Not* e) {}
virtual void visit(const Next* e) {}
virtual void visit(const Eventually* e) {}
virtual void visit(const Globally* e) {}
virtual void visit(const And* e) {}
virtual void visit(const Or* e) {}
virtual void visit(const Until* e) {}
virtual void visit(const WeakUntil* e) {}
virtual void visit(const Release* e) {}
virtual void visit(const True* e) {}
virtual void visit(const False* e) {}
};
/**
* Abstract visitor pattern Visitor base class for LTL expressions,
* which supports the calculation of inherited attributes.
*/
class TopDownVisitor {
public:
virtual IAttr visit(InputSymbol* e, IAttr a) { return a; }
virtual IAttr visit(OutputSymbol* e, IAttr a) { return a; }
virtual IAttr visit(NegInputSymbol* e, IAttr a) { return a; }
virtual IAttr visit(NegOutputSymbol* e, IAttr a) { return a; }
virtual IAttr visit(Not* e, IAttr a) { return a; }
virtual IAttr visit(Next* e, IAttr a) { return a; }
virtual IAttr visit(Eventually* e, IAttr a) { return a; }
virtual IAttr visit(Globally* e, IAttr a) { return a; }
virtual IAttr visit(And* e, IAttr a) { return a; }
virtual IAttr visit(Or* e, IAttr a) { return a; }
virtual IAttr visit(Until* e, IAttr a) { return a; }
virtual IAttr visit(WeakUntil* e, IAttr a) { return a; }
virtual IAttr visit(Release* e, IAttr a) { return a; }
virtual IAttr visit(True* e, IAttr a) { return a; }
virtual IAttr visit(False* e, IAttr a) { return a; }
};
#define LTL_ATOMIC_VISITOR \
void accept(BottomUpVisitor& v) const { v.visit(this); } \
void accept(TopDownVisitor& v, IAttr a) { v.visit(this, a); }
#define LTL_UNARY_VISITOR \
void accept(BottomUpVisitor& v) const { expr1->accept(v); v.visit(this); } \
void accept(TopDownVisitor& v, IAttr a) { expr1->accept(v, v.visit(this, a)); }
#define LTL_BINARY_VISITOR \
void accept(BottomUpVisitor& v) const \
{ \
expr1->accept(v); \
expr2->accept(v); \
v.visit(this); \
} \
\
void accept(TopDownVisitor& v, IAttr a) \
{ \
IAttr a1 = v.visit(this, a); \
expr1->accept(v, a1); \
expr2->accept(v, a1); \
}
/**
* Base Expression
*/
class Expr {
public:
bool quantified;
short label;
std::string id;
enum NodeType type;
Expr(std::string _id="not implemented", NodeType _type=e_Error): id(_id), type(_type) {}
virtual operator std::string () const { return id; }
virtual void accept(BottomUpVisitor& v) const = 0;
virtual void accept(TopDownVisitor& v, IAttr a) = 0;
virtual ~Expr() {}
};
class UnaryExpr : public Expr {
public:
Expr *expr1;
UnaryExpr(std::string _id, NodeType _type, Expr *e): Expr(_id, _type), expr1(e) {
assert(e);
label = ltl_label++;
}
operator std::string () const {
std::stringstream s;
s << id << "(" << std::string(*expr1) << ")";//^"<<label;
return s.str();
}
};
class BinaryExpr : public Expr {
public:
Expr *expr1, *expr2;
BinaryExpr(std::string _id, NodeType _type, Expr *e1, Expr *e2):
Expr(_id, _type), expr1(e1), expr2(e2) {
assert(e1 && e2);
label = ltl_label++;
}
operator std::string () const {
std::stringstream s;
s << id << "(" << std::string(*expr1) << ", " << std::string(*expr2) << ")";//^"<<label;
return s.str();
}
};
class InputSymbol : public Expr {
public:
char c;
InputSymbol(int _c) {
label = ltl_label++;
type = e_InputSymbol;
c = (char)_c;
std::stringstream s;
s << "input("<<std::string(1, c)<<")";//^"<<label;
id = s.str();
}
LTL_ATOMIC_VISITOR
};
class OutputSymbol : public Expr {
public:
char c;
OutputSymbol(int _c) {
label = ltl_label++;
type = e_OutputSymbol;
c = (char)_c;
std::stringstream s;
s << "output("<<std::string(1, c)<<")";//^"<<label;
id = s.str();
}
LTL_ATOMIC_VISITOR
};
/// special case for !iX
class NegInputSymbol : public InputSymbol {
public:
NegInputSymbol(int _c) : InputSymbol(_c) {
type = e_NegInputSymbol;
std::stringstream s;
s << "neg_input("<<std::string(1, c)<<")";//^"<<label;
id = s.str();
}
LTL_ATOMIC_VISITOR
};
/// special case for !oX
class NegOutputSymbol : public OutputSymbol {
public:
NegOutputSymbol(int _c) : OutputSymbol(_c) {
type = e_NegOutputSymbol;
std::stringstream s;
s << "neg_output("<<std::string(1, c)<<")";//^"<<label;
id = s.str();
}
LTL_ATOMIC_VISITOR
};
/// atom true
class True : public Expr {
public:
True() {
label = ltl_label++;
type = e_True;
id = "true";
}
LTL_ATOMIC_VISITOR
};
/// atom false
class False : public Expr {
public:
False() {
label = ltl_label++;
type = e_False;
id = "false";
}
LTL_ATOMIC_VISITOR
};
/// ! / ¬ operator
class Not : public UnaryExpr {
public:
Not(Expr *e) : UnaryExpr("not", e_Not, e) {}
LTL_UNARY_VISITOR
};
/// X / ○ operator
class Next : public UnaryExpr {
public:
Next(Expr *e) : UnaryExpr("next", e_Next, e) {}
LTL_UNARY_VISITOR
};
/// F / ◇ operator
class Eventually : public UnaryExpr {
public:
Eventually(Expr *e) : UnaryExpr("eventually", e_Eventually, e) {}
LTL_UNARY_VISITOR
};
/// G / □ operator
class Globally : public UnaryExpr {
public:
Globally(Expr *e) : UnaryExpr("globally", e_Globally, e) {}
LTL_UNARY_VISITOR
};
class And : public BinaryExpr {
public:
And(Expr *e1, Expr *e2) : BinaryExpr("and", e_And, e1, e2) {}
LTL_BINARY_VISITOR
};
class Or : public BinaryExpr {
public:
Or(Expr *e1, Expr *e2) : BinaryExpr("or", e_Or, e1, e2) {}
LTL_BINARY_VISITOR
};
/// U operator
class Until : public BinaryExpr {
public:
Until(Expr *e1, Expr *e2) : BinaryExpr("until", e_Until, e1, e2) {}
LTL_BINARY_VISITOR
};
/// WU / weak U operator
class WeakUntil : public BinaryExpr {
public:
WeakUntil(Expr *e1, Expr *e2) : BinaryExpr("weakUntil", e_WeakUntil, e1, e2) {}
LTL_BINARY_VISITOR
};
/// R operator
class Release : public BinaryExpr {
public:
Release(Expr *e1, Expr *e2) : BinaryExpr("release", e_Release, e1, e2) {}
LTL_BINARY_VISITOR
};
/**
* A well-formed LTL formula.
* Performs basic grammar checking on an LTL expressions.
*/
class Formula {
public:
/**
* Construct a new formula and make sure all atomic expressions are properly quantified.
* As a side effect, the quantified attribute of each expression node is set.
*
* Note: this may be a misconception, but I do not understand what
* "oX" is supposed to mean if it is encountered
* unquantified. E.g., what's the difference between "oX" and "G
* oX", otherwise?
*/
Formula(Expr& e1) :e(e1), expr_size(ltl_label) {
class WellFormedVisitor: public TopDownVisitor {
public:
struct Attr: public InheritedAttribute {
Attr(bool q) : quantified(q) {}
bool quantified;
};
// FIXME: is there a less ugly way to implement generic attributes?
// MS: needed to remove the shared ptr
static Attr* getAttr(IAttr a) { return static_cast<Attr*>(a); }
static IAttr newAttr(bool b) { return new Attr(b); }
IAttr visit(InputSymbol* e, IAttr a) {
e->quantified=getAttr(a)->quantified;
if (!getAttr(a)->quantified) throw "unquantified input operation";
return a;
}
IAttr visit(OutputSymbol* e, IAttr a) {
e->quantified=getAttr(a)->quantified;
if (!getAttr(a)->quantified) throw "unquantified output operation";
return a;
}
IAttr visit(NegInputSymbol* e, IAttr a) {
e->quantified=getAttr(a)->quantified;
if (!getAttr(a)->quantified) throw "unquantified input operation";
return a;
}
IAttr visit(NegOutputSymbol* e, IAttr a) {
e->quantified=getAttr(a)->quantified;
if (!getAttr(a)->quantified) throw "unquantified output operation";
return a;
}
IAttr visit(Next* e, IAttr a) { e->quantified=getAttr(a)->quantified; return newAttr(true); }
IAttr visit(Eventually* e, IAttr a) { e->quantified=getAttr(a)->quantified; return newAttr(true); }
IAttr visit(Globally* e, IAttr a) { e->quantified=getAttr(a)->quantified; return newAttr(true); }
IAttr visit(Until* e, IAttr a) { e->quantified=getAttr(a)->quantified; return newAttr(true); }
IAttr visit(WeakUntil* e, IAttr a) { e->quantified=getAttr(a)->quantified; return newAttr(true); }
IAttr visit(Release* e, IAttr a) { e->quantified=getAttr(a)->quantified; return newAttr(true); }
IAttr visit(Not* e, IAttr a) { e->quantified=getAttr(a)->quantified; return a; }
IAttr visit(And* e, IAttr a) { e->quantified=getAttr(a)->quantified; return a; }
IAttr visit(Or* e, IAttr a) { e->quantified=getAttr(a)->quantified; return a; }
IAttr visit(True* e, IAttr a) { e->quantified=getAttr(a)->quantified; return a; }
IAttr visit(False* e, IAttr a) { e->quantified=getAttr(a)->quantified; return a; }
};
WellFormedVisitor v;
e1.accept(v, WellFormedVisitor::newAttr(false));
}
operator std::string () const { return std::string(e); }
operator const Expr& () const { return e; }
size_t size() const { return expr_size; }
protected:
Expr& e;
size_t expr_size;
};
} // namespace LTL
} // namespace CodeThorn
#endif
| 5,436 |
841 | <reponame>tkobayas/jbpm<gh_stars>100-1000
/*
* Copyright 2021 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.jbpm.process.core.impl;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.jbpm.process.core.impl.ObjectCloner.Config;
import org.junit.Test;
public class ObjectClonerTest {
private enum Status {
SINGLE,
MARRIED,
DIVORCED,
WIDOWED
}
public static class NamedPerson extends Person {
private String name;
public NamedPerson(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Objects.hash(name);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof NamedPerson)) {
return false;
}
NamedPerson other = (NamedPerson) obj;
return Objects.equals(name, other.name);
}
}
public static class Room {
private String id;
private boolean open;
public Room() {}
public Room(Room room) {
this.id = room.id;
this.open = room.open;
}
public Room(String id, boolean open) {
this.id = id;
this.open = open;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isOpen() {
return open;
}
public void setOpen(boolean open) {
this.open = open;
}
@Override
public String toString() {
return "Room [id=" + id + ", open=" + open + "]";
}
@Override
public int hashCode() {
return Objects.hash(id, open);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Room)) {
return false;
}
Room other = (Room) obj;
return Objects.equals(id, other.id) && open == other.open;
}
}
public static class Person {
private Address address;
private Status status;
private int age;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
return Objects.hash(address, age, status);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Person)) {
return false;
}
Person other = (Person) obj;
return Objects.equals(address, other.address) && age == other.age && status == other.status;
}
@Override
public String toString() {
return "Person [address=" + address + ", status=" + status + ", age=" + age + "]";
}
}
public static class Address {
private final String street;
private final int number;
public Address(String street, int number) {
this.street = street;
this.number = number;
}
public String getStreet() {
return street;
}
public int getNumber() {
return number;
}
@Override
public int hashCode() {
return Objects.hash(number, street);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Address)) {
return false;
}
Address other = (Address) obj;
return number == other.number && Objects.equals(street, other.street);
}
}
public static class Picture implements Cloneable {
private String author;
private byte[] data;
public Picture(String author, byte[] data) {
this.author = author;
this.data = data;
}
public Object clone() {
return new Picture(author, data);
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(data);
result = prime * result + Objects.hash(author);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Picture)) {
return false;
}
Picture other = (Picture) obj;
return Objects.equals(author, other.author) && Arrays.equals(data, other.data);
}
}
public static class BigBrother {
public String name;
public Collection<Person> lovers;
@Override
public int hashCode() {
return Objects.hash(lovers, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof BigBrother)) {
return false;
}
BigBrother other = (BigBrother) obj;
return Objects.equals(lovers, other.lovers) && Objects.equals(name, other.name);
}
}
@Test
public void testInmutable() {
Config config = new Config().deepCloneCollections(false);
Object obj = 5;
assertSame(obj, ObjectCloner.clone(obj));
obj = true;
assertSame(obj, ObjectCloner.clone(obj));
obj = "pepe";
assertSame(obj, ObjectCloner.clone(obj));
obj = Arrays.asList("1", "2", "3");
assertSame(obj, ObjectCloner.clone(obj, config));
obj = Collections.singletonMap("pepe", "forever");
assertSame(obj, ObjectCloner.clone(obj, config));
obj = null;
assertSame(obj, ObjectCloner.clone(obj));
}
@Test
public void testMutablePOJOWithDefaultConstructor() {
Person person = new Person();
person.setAddress(new Address("Rue del Percebe", 13));
person.setStatus(Status.MARRIED);
person.setAge(101);
Object cloned = ObjectCloner.clone(person);
assertNotSame(person, cloned);
assertEquals(person, cloned);
}
@Test
public void testPrimitiveArray() {
int[] object = {2, 3, 5, 7, 11, 13, 17};
int[] cloned = (int[]) ObjectCloner.clone(object);
assertNotSame(object, cloned);
assertArrayEquals(object, cloned);
}
@Test
public void testObjectArray() {
Object[] object = {new NamedPerson("pepe"), new Room("id", false)};
Object[] cloned = (Object[]) ObjectCloner.clone(object);
assertNotSame(object, cloned);
assertArrayEquals(object, cloned);
}
@Test
public void testCollection() {
Collection object = new ArrayList<>();
object.add(new NamedPerson("pepe"));
object.add(new Room("pepe", false));
Object cloned = ObjectCloner.clone(object);
assertNotSame(object, cloned);
assertEquals(object, cloned);
}
@Test
public void testMap() {
Map object = new HashMap<>();
object.put("person", new NamedPerson("pepe"));
object.put("room", new Room("pepe", false));
Object cloned = ObjectCloner.clone(object);
assertNotSame(object, cloned);
assertEquals(object, cloned);
}
@Test
public void testCloneable() {
Picture object = new Picture("javierito", new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
Object cloned = ObjectCloner.clone(object);
assertNotSame(object, cloned);
assertEquals(object, cloned);
}
@Test
public void testMutablePOJOWithConstructor() {
Person person = new NamedPerson("pepe");
person.setAddress(new Address("Rue del Percebe", 13));
person.setStatus(Status.SINGLE);
person.setAge(23);
Object cloned = ObjectCloner.clone(person);
assertNotSame(person, cloned);
assertEquals(person, cloned);
}
@Test
public void testMutablePOJOWithCopyConstructor() {
Room room = new Room();
room.setId("Aloha");
room.setOpen(true);
Object cloned = ObjectCloner.clone(room);
assertNotSame(room, cloned);
assertEquals(room, cloned);
}
@Test
public void testPojoWithPublicFields() {
BigBrother object = new BigBrother();
object.name = "nosecomeunarosca";
object.lovers = Collections.unmodifiableList(Collections.emptyList());
Object cloned = ObjectCloner.clone(object);
assertNotSame(object, cloned);
assertEquals(object, cloned);
}
@Test
public void testInmutablePOJO() {
Address address = new Address("Rue del Percebe", 13);
assertSame(address, ObjectCloner.clone(address));
}
}
| 5,100 |
1,442 | <filename>escher/src/message_table_cell_with_editable_text.cpp
#include <escher/message_table_cell_with_editable_text.h>
#include <escher/palette.h>
namespace Escher {
MessageTableCellWithEditableText::MessageTableCellWithEditableText(Responder * parentResponder, InputEventHandlerDelegate * inputEventHandlerDelegate, TextFieldDelegate * textFieldDelegate, I18n::Message message) :
Responder(parentResponder),
MessageTableCell(message),
m_textField(this, m_textBody, Poincare::PrintFloat::k_maxFloatCharSize, TextField::maxBufferSize(), inputEventHandlerDelegate, textFieldDelegate, KDFont::LargeFont, 1.0f, 0.5f, KDColorBlack)
{
m_textBody[0] = '\0';
}
void MessageTableCellWithEditableText::setHighlighted(bool highlight) {
MessageTableCell::setHighlighted(highlight);
KDColor backgroundColor = highlight? Palette::Select : KDColorWhite;
m_textField.setBackgroundColor(backgroundColor);
}
void MessageTableCellWithEditableText::setAccessoryText(const char * text) {
m_textField.setText(text);
layoutSubviews();
}
}
| 333 |
1,144 | package de.metas.contracts.impl;
/*
* #%L
* de.metas.contracts
* %%
* Copyright (C) 2015 metas GmbH
* %%
* 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/gpl-2.0.html>.
* #L%
*/
import java.sql.Timestamp;
import java.util.List;
import java.util.Properties;
import org.adempiere.model.InterfaceWrapperHelper;
import org.compiere.model.Query;
import de.metas.contracts.flatrate.exceptions.SubscriptionChangeException;
import de.metas.contracts.model.I_C_Contract_Change;
import de.metas.contracts.model.I_C_Flatrate_Term;
import de.metas.contracts.model.X_C_Contract_Change;
public class ContractChangeDAO extends AbstractContractChangeDAO
{
@Override
public I_C_Contract_Change retrieveChangeConditions(
final I_C_Flatrate_Term term,
final int newSubscriptionId,
final Timestamp changeDate)
{
final String where = X_C_Contract_Change.COLUMNNAME_Action + "='" + X_C_Contract_Change.ACTION_Abowechsel + "' AND " +
X_C_Contract_Change.COLUMNNAME_C_Flatrate_Transition_ID + "=? AND " +
"COALESCE(" + X_C_Contract_Change.COLUMNNAME_C_Flatrate_Conditions_ID + ",0) IN (0,?) AND " +
X_C_Contract_Change.COLUMNNAME_C_Flatrate_Conditions_Next_ID + "=?";
final Properties ctx = InterfaceWrapperHelper.getCtx(term);
final String trxName = InterfaceWrapperHelper.getTrxName(term);
final List<I_C_Contract_Change> entries = new Query(ctx, I_C_Contract_Change.Table_Name, where, trxName)
.setParameters(term.getC_Flatrate_Transition_ID(), term.getC_Flatrate_Conditions_ID(), newSubscriptionId)
.setOnlyActiveRecords(true)
.setClient_ID()
.setOrderBy(I_C_Contract_Change.COLUMNNAME_C_Contract_Change_ID)
.list(I_C_Contract_Change.class);
final I_C_Contract_Change earliestEntryForRefDate = getEarliestEntryForRefDate(entries, changeDate, term.getEndDate());
if (earliestEntryForRefDate == null)
{
throw new SubscriptionChangeException(term.getC_Flatrate_Conditions_ID(), newSubscriptionId, changeDate);
}
return earliestEntryForRefDate;
}
}
| 902 |
333 | <reponame>coreyp1/graphlab
/*
* Copyright (c) 2009 Car<NAME> University.
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#include <boost/unordered_set.hpp>
#include <graphlab.hpp>
#include <graphlab/ui/metrics_server.hpp>
#include <graphlab/macros_def.hpp>
/**
*
* In this program we implement the "hash-table" version of the
* "edge-iterator" algorithm described in
*
* <NAME>. Algorithmic Aspects of Triangle-Based Network Analysis.
* Phd in computer science, University Karlsruhe, 2007.
*
* The procedure is quite straightforward:
* - each vertex maintains a list of all of its neighbors in a hash table.
* - For each edge (u,v) in the graph, count the number of intersections
* of the neighbor set on u and the neighbor set on v.
* - We store the size of the intersection on the edge.
*
* This will count every triangle exactly 3 times. Summing across all the
* edges and dividing by 3 gives the desired result.
*
* The preprocessing stage take O(|E|) time, and it has been shown that this
* algorithm takes $O(|E|^(3/2))$ time.
*
* If we only require total counts, we can introduce a optimization that is
* similar to the "forward" algorithm
* described in thesis above. Instead of maintaining a complete list of all
* neighbors, each vertex only maintains a list of all neighbors with
* ID greater than itself. This implicitly generates a topological sort
* of the graph.
*
* Then you can see that each triangle
*
* \verbatim
A----->C
| ^
| /
v /
B
* \endverbatim
* Must be counted only once. (Only when processing edge AB, can one
* observe that A and B have intersecting out-neighbor sets).
*
*
* \note The implementation here is built to be easy to understand
* and not necessarily optimal. In particular the unordered_set is slow
* for small number of entries. There is a much more efficient
* (and substantially more complicated) version in undirected_triangle_count.cpp
*/
/*
* Each vertex maintains a list of all its neighbors.
* and a final count for the number of triangles it is involved in
*/
struct vertex_data_type {
vertex_data_type():num_triangles(0) { }
// A list of all its neighbors
boost::unordered_set<graphlab::vertex_id_type> vid_set;
// The number of triangles this vertex is involved it.
// only used if "per vertex counting" is used
size_t num_triangles;
void save(graphlab::oarchive &oarc) const {
oarc << vid_set << num_triangles;
}
void load(graphlab::iarchive &iarc) {
iarc >> vid_set >> num_triangles;
}
};
/*
* Each edge is simply a counter of triangles
*/
typedef size_t edge_data_type;
// To collect the set of neighbors, we need a message type which is
// basically a set of vertex IDs
bool PER_VERTEX_COUNT = false;
/*
* This is the gathering type which accumulates an (unordered) set of
* all neighboring vertices.
* It is a simple wrapper around a boost::unordered_set with
* an operator+= which simply performs a set union.
*
* This struct can be significantly accelerated for small sets.
* Small collections of vertex IDs should not require the overhead
* of the unordered_set.
*/
struct set_union_gather {
boost::unordered_set<graphlab::vertex_id_type> vid_set;
/*
* Combining with another collection of vertices.
* Union it into the current set.
*/
set_union_gather& operator+=(const set_union_gather& other) {
foreach(graphlab::vertex_id_type othervid, other.vid_set) {
vid_set.insert(othervid);
}
return *this;
}
// serialize
void save(graphlab::oarchive& oarc) const {
oarc << vid_set;
}
// deserialize
void load(graphlab::iarchive& iarc) {
iarc >> vid_set;
}
};
/*
* Define the type of the graph
*/
typedef graphlab::distributed_graph<vertex_data_type,
edge_data_type> graph_type;
/*
* This class implements the triangle counting algorithm as described in
* the header. On gather, we accumulate a set of all adjacent vertices.
* If per_vertex output is not necessary, we can use the optimization
* where each vertex only accumulates neighbors with greater vertex IDs.
*/
class triangle_count :
public graphlab::ivertex_program<graph_type,
set_union_gather>,
/* I have no data. Just force it to POD */
public graphlab::IS_POD_TYPE {
public:
// Gather on all edges
edge_dir_type gather_edges(icontext_type& context,
const vertex_type& vertex) const {
return graphlab::ALL_EDGES;
}
/*
* For each edge, figure out the ID of the "other" vertex
* and accumulate a set of the neighborhood vertex IDs.
*/
gather_type gather(icontext_type& context,
const vertex_type& vertex,
edge_type& edge) const {
set_union_gather gather;
// Insert the opposite end of the edge IF the opposite end has
// ID greater than the current vertex
// If we are getting per vertex counts, we need the entire neighborhood
vertex_id_type otherid = edge.source().id() == vertex.id() ?
edge.target().id() : edge.source().id();
if (PER_VERTEX_COUNT ||
otherid > vertex.id()) gather.vid_set.insert(otherid);
return gather;
}
/*
* the gather result now contains the vertex IDs in the neighborhood.
* store it on the vertex.
*/
void apply(icontext_type& context, vertex_type& vertex,
const gather_type& neighborhood) {
vertex.data().vid_set = neighborhood.vid_set;
} // end of apply
/*
* Scatter over all edges to compute the intersection.
* I only need to touch each edge once, so if I scatter just on the
* out edges, that is sufficient.
*/
edge_dir_type scatter_edges(icontext_type& context,
const vertex_type& vertex) const {
return graphlab::OUT_EDGES;
}
/*
* Computes the size of the intersection of two unordered sets
*/
static size_t count_set_intersect(
const boost::unordered_set<vertex_id_type>& smaller_set,
const boost::unordered_set<vertex_id_type>& larger_set) {
size_t count = 0;
foreach(vertex_id_type vid, smaller_set) {
count += larger_set.count(vid);
}
return count;
}
/*
* For each edge, count the intersection of the neighborhood of the
* adjacent vertices. This is the number of triangles this edge is involved
* in.
*/
void scatter(icontext_type& context,
const vertex_type& vertex,
edge_type& edge) const {
const vertex_data_type& srclist = edge.source().data();
const vertex_data_type& targetlist = edge.target().data();
if (srclist.vid_set.size() >= targetlist.vid_set.size()) {
edge.data() = count_set_intersect(targetlist.vid_set, srclist.vid_set);
}
else {
edge.data() = count_set_intersect(srclist.vid_set, targetlist.vid_set);
}
}
};
/*
* This class is used in a second engine call if per vertex counts are needed.
* The number of triangles a vertex is involved in can be computed easily
* by summing over the number of triangles each adjacent edge is involved in
* and dividing by 2.
*/
class get_per_vertex_count :
public graphlab::ivertex_program<graph_type, size_t>,
/* I have no data. Just force it to POD */
public graphlab::IS_POD_TYPE {
public:
// Gather on all edges
edge_dir_type gather_edges(icontext_type& context,
const vertex_type& vertex) const {
return graphlab::ALL_EDGES;
}
// We gather the number of triangles each edge is involved in
size_t gather(icontext_type& context,
const vertex_type& vertex,
edge_type& edge) const {
return edge.data();
}
/* the gather result is the total sum of the number of triangles
* each adjacent edge is involved in . Dividing by 2 gives the
* desired result.
*/
void apply(icontext_type& context, vertex_type& vertex,
const gather_type& num_triangles) {
vertex.data().num_triangles = num_triangles / 2;
}
// No scatter
edge_dir_type scatter_edges(icontext_type& context,
const vertex_type& vertex) const {
return graphlab::NO_EDGES;
}
};
/* Used to sum over all the edges in the graph in a
* map_reduce_edges call
* to get the total number of triangles
*/
size_t get_edge_data(const graph_type::edge_type& e) {
return e.data();
}
/*
* A saver which saves a file where each line is a vid / # triangles pair
*/
struct save_triangle_count{
std::string save_vertex(graph_type::vertex_type v) {
return graphlab::tostr(v.id()) + "\t" +
graphlab::tostr(v.data().num_triangles) + "\n";
}
std::string save_edge(graph_type::edge_type e) {
return "";
}
};
int main(int argc, char** argv) {
std::cout << "This program counts the exact number of triangles in the "
"provided graph.\n\n";
graphlab::command_line_options clopts("Exact Triangle Counting. "
"Given a graph, this program computes the total number of triangles "
"in the graph. An option (per_vertex) is also provided which "
"computes for each vertex, the number of triangles it is involved in."
"The algorithm assumes that each undirected edge appears exactly once "
"in the graph input. If edges may appear more than once, this procedure "
"will over count.");
std::string prefix, format;
std::string per_vertex;
clopts.attach_option("graph", prefix,
"Graph input. reads all graphs matching prefix*");
clopts.attach_option("format", format,
"The graph format");
clopts.attach_option("per_vertex", per_vertex,
"If not empty, will count the number of "
"triangles each vertex belongs to and "
"save to file with prefix \"[per_vertex]\". "
"The algorithm used is slightly different "
"and thus will be a little slower");
if(!clopts.parse(argc, argv)) return EXIT_FAILURE;
if (prefix == "") {
std::cout << "--graph is not optional\n";
clopts.print_description();
return EXIT_FAILURE;
}
else if (format == "") {
std::cout << "--format is not optional\n";
clopts.print_description();
return EXIT_FAILURE;
}
if (per_vertex != "") PER_VERTEX_COUNT = true;
// Initialize control plane using mpi
graphlab::mpi_tools::init(argc, argv);
graphlab::distributed_control dc;
graphlab::launch_metric_server();
// load graph
graph_type graph(dc, clopts);
graph.load_format(prefix, format);
graph.finalize();
dc.cout() << "Number of vertices: " << graph.num_vertices() << std::endl
<< "Number of edges: " << graph.num_edges() << std::endl;
graphlab::timer ti;
// create engine to count the number of triangles
dc.cout() << "Counting Triangles..." << std::endl;
graphlab::synchronous_engine<triangle_count> engine(dc, graph, clopts);
engine.signal_all();
engine.start();
dc.cout() << "Counted in " << ti.current_time() << " seconds" << std::endl;
if (PER_VERTEX_COUNT == false) {
size_t count = graph.map_reduce_edges<size_t>(get_edge_data);
dc.cout() << count << " Triangles" << std::endl;
}
else {
graphlab::synchronous_engine<get_per_vertex_count> engine(dc, graph, clopts);
engine.signal_all();
engine.start();
graph.save(per_vertex,
save_triangle_count(),
false, /* no compression */
true, /* save vertex */
false, /* do not save edge */
1); /* one file per machine */
}
graphlab::stop_metric_server();
graphlab::mpi_tools::finalize();
return EXIT_SUCCESS;
} // End of main
| 4,533 |
1,167 | <reponame>jontrulson/mraa
#!/usr/bin/env python
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2015 Intel Corporation.
#
# SPDX-License-Identifier: MIT
#
# Example Usage: Loopbacks data between MISO and MOSI 100 times
import mraa as m
import random as rand
# intialise SPI
dev = m.Spi(0)
for x in range(0,100):
txbuf = bytearray(4)
for y in range(0,4):
txbuf[y] = rand.randrange(0, 256)
# send and receive data through SPI
rxbuf = dev.write(txbuf)
if rxbuf != txbuf:
print("Data mismatch!")
exit(1)
| 233 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.automation.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.automation.fluent.models.ModuleInner;
import com.azure.resourcemanager.automation.models.PythonPackageCreateParameters;
import com.azure.resourcemanager.automation.models.PythonPackageUpdateParameters;
/** An instance of this class provides access to all the operations defined in Python2PackagesClient. */
public interface Python2PackagesClient {
/**
* Delete the python 2 package by name.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param packageName The python package name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String automationAccountName, String packageName);
/**
* Delete the python 2 package by name.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param packageName The python package name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> deleteWithResponse(
String resourceGroupName, String automationAccountName, String packageName, Context context);
/**
* Retrieve the python 2 package identified by package name.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param packageName The python package name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return definition of the module type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
ModuleInner get(String resourceGroupName, String automationAccountName, String packageName);
/**
* Retrieve the python 2 package identified by package name.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param packageName The python package name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return definition of the module type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<ModuleInner> getWithResponse(
String resourceGroupName, String automationAccountName, String packageName, Context context);
/**
* Create or Update the python 2 package identified by package name.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param packageName The name of python package.
* @param parameters The create or update parameters for python package.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return definition of the module type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
ModuleInner createOrUpdate(
String resourceGroupName,
String automationAccountName,
String packageName,
PythonPackageCreateParameters parameters);
/**
* Create or Update the python 2 package identified by package name.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param packageName The name of python package.
* @param parameters The create or update parameters for python package.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return definition of the module type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<ModuleInner> createOrUpdateWithResponse(
String resourceGroupName,
String automationAccountName,
String packageName,
PythonPackageCreateParameters parameters,
Context context);
/**
* Update the python 2 package identified by package name.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param packageName The name of python package.
* @param parameters The update parameters for python package.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return definition of the module type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
ModuleInner update(
String resourceGroupName,
String automationAccountName,
String packageName,
PythonPackageUpdateParameters parameters);
/**
* Update the python 2 package identified by package name.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param packageName The name of python package.
* @param parameters The update parameters for python package.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return definition of the module type.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<ModuleInner> updateWithResponse(
String resourceGroupName,
String automationAccountName,
String packageName,
PythonPackageUpdateParameters parameters,
Context context);
/**
* Retrieve a list of python 2 packages.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response model for the list module operation.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<ModuleInner> listByAutomationAccount(String resourceGroupName, String automationAccountName);
/**
* Retrieve a list of python 2 packages.
*
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response model for the list module operation.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<ModuleInner> listByAutomationAccount(
String resourceGroupName, String automationAccountName, Context context);
}
| 2,735 |
12,887 | package com.zhisheng.connectors.kafka;
import com.zhisheng.common.model.MetricEvent;
import com.zhisheng.common.schemas.KafkaMetricSchema;
import com.zhisheng.common.utils.ExecutionEnvUtil;
import com.zhisheng.common.utils.GsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;
import java.util.Properties;
import static com.zhisheng.common.utils.KafkaConfigUtil.buildKafkaProps;
/**
* Desc: KafkaDeserializationSchema
* Created by zhisheng on 2019-12-16 21:03
* blog:http://www.54tianzhisheng.cn/
* 微信公众号:zhisheng
*/
@Slf4j
public class KafkaDeserializationSchemaTest {
public static void main(String[] args) throws Exception {
final ParameterTool parameterTool = ExecutionEnvUtil.createParameterTool(args);
StreamExecutionEnvironment env = ExecutionEnvUtil.prepare(parameterTool);
Properties props = buildKafkaProps(parameterTool);
FlinkKafkaConsumer<ObjectNode> kafkaConsumer = new FlinkKafkaConsumer<>("zhisheng",
new KafkaMetricSchema(true),
props);
env.addSource(kafkaConsumer)
.flatMap(new FlatMapFunction<ObjectNode, MetricEvent>() {
@Override
public void flatMap(ObjectNode jsonNodes, Collector<MetricEvent> collector) throws Exception {
try {
// System.out.println(jsonNodes);
MetricEvent metricEvent = GsonUtil.fromJson(jsonNodes.get("value").asText(), MetricEvent.class);
collector.collect(metricEvent);
} catch (Exception e) {
log.error("jsonNodes = {} convert to MetricEvent has an error", jsonNodes, e);
}
}
})
.print();
env.execute();
}
}
| 1,000 |
12,718 | struct user {
struct {
unsigned long gpr[32], nip, msr, orig_gpr3, ctr, link, xer, ccr, mq;
unsigned long trap, dar, dsisr, result;
} regs;
unsigned long u_tsize, u_dsize, u_ssize;
unsigned long start_code, start_data, start_stack;
long signal;
void *u_ar0;
unsigned long magic;
char u_comm[32];
};
#define ELF_NGREG 48
#define ELF_NFPREG 33
#define ELF_NVRREG 33
typedef unsigned long elf_greg_t, elf_gregset_t[ELF_NGREG];
typedef double elf_fpreg_t, elf_fpregset_t[ELF_NFPREG];
typedef struct { unsigned u[4]; }
#ifdef __GNUC__
__attribute__((__aligned__(16)))
#endif
elf_vrreg_t, elf_vrregset_t[ELF_NVRREG]; | 268 |
1,963 | /*
*******************************************************************************
* Copyright (c) 201-2021, STMicroelectronics
* All rights reserved.
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
*******************************************************************************
*/
#if defined(ARDUINO_ST3DP001_EVAL)
#include "pins_arduino.h"
const PinName digitalPin[] = {
PA_9, // TX
PA_10, // RX
// WIFI
PD_3, // CTS
PD_4, // RTS
PD_5, // TX
PD_6, // RX
PB_5, // WIFI_WAKEUP
PE_11, // WIFI_RESET
PE_12, // WIFI_BOOT
// STATUS_LED
PE_1, //STATUS_LED
// SPI USER
PB_12, // SPI_CS
PB_15, // SPI_MOSI
PB_14, // SPI_MISO
PB_13, // SPI_SCK
// I2C USER
PB_7, // SDA
PB_6, // SCL
// SPI
PA_4, // SPI_CS
PA_5, // SPI_SCK
PA_6, // SPI_MISO
PA_7, // SPI_MOSI
// JTAG
PA_13, // JTAG_TMS/SWDIO
PA_14, // JTAG_TCK/SWCLK
PB_3, // JTAG_TDO/SWO
// SDCARD
PC_8, // SDIO_D0
PC_9, // SDIO_D1
PA_15, // SD_CARD_DETECT
PC_10, // SDIO_D2
PC_11, // SDIO_D3
PC_12, // SDIO_CK
PD_2, // SDIO_CMD
// OTG
PA_11, // OTG_DM
PA_12, // OTG_DP
// IR/PROBE
PD_1, // IR_OUT
PC_1, // IR_ON
// USER_PINS
PD_7, // USER3
PB_9, // USER1
PE_0, // USER2
PB_4, // USER4
// USERKET
PE_7, // USER_BUTTON
// ENDSTOPS
PD_8, // X_STOP
PD_9, // Y_STOP
PD_10, // Z_STOP
PD_11, // U_STOP
PA_8, // V_STOP
PD_0, // W_STOP
// HEATERS
PD_13, // BED_HEAT_2
PD_14, // BED_HEAT_1
PD_15, // BED_HEAT_3
PC_7, // E1_HEAT_PWM
PB_0, // E2_HEAT_PWM
PB_1, // E3_HEAT_PWM
// THERMISTOR
PC_2, // BED_THERMISTOR_1
PC_3, // BED_THERMISTOR_2
PA_3, // BED_THERMISTOR_3
PA_0, // E1_THERMISTOR
PA_1, // E2_THERMISTOR
PA_2, // E3_THERMISTOR
// FANS
PC_4, // E1_FAN
PC_5, // E2_FAN
PE_8, // E3_FAN
// X_MOTOR
PE_13, // X_RESET
PE_14, // X_PWM
PE_15, // X_DIR
// Y_MOTOR
PE_10, // Y_RESET
PB_10, // Y_PWM
PE_9, // Y_DIR
// Z_MOTOR
PC_15, // Z_RESET
PC_6, // Z_PWM
PC_0, // Z_DIR
// E1_MOTOR
PC_14, // E1_RESET
PC_13, // E1_DIR
PD_12, // E1_PWM
// E2_MOTOR
PE_4, // E2_RESET
PE_5, // E2_PWM
PE_6, // E2_DIR
// E3_MOTOR
PE_3, // E3_RESET
PE_2, // E3_DIR
PB_8 // E3_PWM
};
// Analog (Ax) pin number array
const uint32_t analogInputPin[] = {
51, // A0, PC2
52, // A1, PC3
53, // A2, PA3
54, // A3, PA0
55, // A4, PA1
56 // A5, PA2
};
// ----------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief System Clock Configuration
* @param None
* @retval None
*/
WEAK void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {};
/* Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
/* Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 15;
RCC_OscInitStruct.PLL.PLLN = 144;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
RCC_OscInitStruct.PLL.PLLQ = 5;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/* Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) {
Error_Handler();
}
}
#ifdef __cplusplus
}
#endif
#endif /* ARDUINO_ST3DP001_EVAL */
| 2,094 |
10,225 | package io.quarkus.devtools.codestarts.core.strategy;
import io.quarkus.devtools.codestarts.CodestartResource.Source;
import java.io.IOException;
import java.nio.file.Path;
public interface DefaultCodestartFileStrategyHandler extends CodestartFileStrategyHandler {
void copyStaticFile(Source source, Path targetPath) throws IOException;
}
| 106 |
794 | <reponame>JasperMorrison/PytorchToCaffe
import numpy as np
from .blob import Blob
from .layers import Base
class Flatten(Base):
def __init__(self,input, name='permute'):
super(Flatten, self).__init__(input, name)
dim=[np.prod(input.data.shape)]
self.out = Blob(dim, self)
class PSROIPool(Base):
def __init__(self,input,rois,output_dim,group_size,name='psroipool'):
super(PSROIPool,self).__init__([input,rois],name)
self.rois=rois
dim=[rois.shape[0],output_dim,group_size,group_size]
self.out=Blob(dim,self)
self.layer_info='output_dim:%d,group_size:%d'%(output_dim,group_size)
# TODO PSROIPOOL ANALYSIS
class ROIPool(Base):
def __init__(self,input,rois,pooled_w,pooled_h,name='roipool'):
super(ROIPool,self).__init__([input,rois],name)
self.rois = rois
dim=[rois.shape[0],pooled_w,pooled_h,input[3]]
self.out = Blob(dim, self)
self.layer_info = 'roi pooled:%dx%d' % (pooled_w, pooled_h)
# TODO PSROIPOOL ANALYSIS | 505 |
3,102 | // RUN: %clang_cc1 -fsyntax-only -verify %s
typedef double * __attribute__((align_value(64))) aligned_double;
void foo(aligned_double x, double * y __attribute__((align_value(32)))) { };
// expected-error@+1 {{requested alignment is not a power of 2}}
typedef double * __attribute__((align_value(63))) aligned_double1;
// expected-error@+1 {{requested alignment is not a power of 2}}
typedef double * __attribute__((align_value(-2))) aligned_double2;
// expected-error@+1 {{attribute takes one argument}}
typedef double * __attribute__((align_value(63, 4))) aligned_double3;
// expected-error@+1 {{attribute takes one argument}}
typedef double * __attribute__((align_value())) aligned_double3a;
// expected-error@+1 {{attribute takes one argument}}
typedef double * __attribute__((align_value)) aligned_double3b;
// expected-error@+1 {{'align_value' attribute requires integer constant}}
typedef double * __attribute__((align_value(4.5))) aligned_double4;
// expected-warning@+1 {{'align_value' attribute only applies to a pointer or reference ('int' is invalid)}}
typedef int __attribute__((align_value(32))) aligned_int;
typedef double * __attribute__((align_value(32*2))) aligned_double5;
// expected-warning@+1 {{'align_value' attribute only applies to variables and typedefs}}
void foo() __attribute__((align_value(32)));
| 414 |
5,169 | <gh_stars>1000+
{
"name": "SYAlertController",
"version": "0.1.0",
"summary": "一个在UIAlertController基础上增加图片的Alert",
"description": "一个基于UIAlertController 上修改的一个可以在顶部插入一个图片的Alert弹窗,你可以使用不同的icon使提示更加醒目,并对接系统Alert自动布局,不用担心文字过多过少引起的样式异常的问题",
"homepage": "https://github.com/wanghao20150901/SYAlertController",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"wanghao": "<EMAIL>"
},
"source": {
"git": "https://github.com/wanghao20150901/SYAlertController.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "8.0"
},
"source_files": "SYAlertController/Classes/**/*",
"dependencies": {
"PureLayout": [
]
}
}
| 417 |
4,901 | <reponame>OneRom/external_okhttp<gh_stars>1000+
/*
* Copyright (C) 2014 Square, Inc.
*
* 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 okio;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** A scriptable sink. Like Mockito, but worse and requiring less configuration. */
class MockSink implements Sink {
private final List<String> log = new ArrayList<String>();
private final Map<Integer, IOException> callThrows = new LinkedHashMap<Integer, IOException>();
public void assertLog(String... messages) {
assertEquals(Arrays.asList(messages), log);
}
public void assertLogContains(String message) {
assertTrue(log.contains(message));
}
public void scheduleThrow(int call, IOException e) {
callThrows.put(call, e);
}
private void throwIfScheduled() throws IOException {
IOException exception = callThrows.get(log.size() - 1);
if (exception != null) throw exception;
}
@Override public void write(Buffer source, long byteCount) throws IOException {
log.add("write(" + source + ", " + byteCount + ")");
source.skip(byteCount);
throwIfScheduled();
}
@Override public void flush() throws IOException {
log.add("flush()");
throwIfScheduled();
}
@Override public Timeout timeout() {
log.add("timeout()");
return Timeout.NONE;
}
@Override public void close() throws IOException {
log.add("close()");
throwIfScheduled();
}
}
| 663 |
1,102 | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This source is available for distribution and/or modification
// only under the terms of the DOOM Source Code License as
// published by id Software. All rights reserved.
//
// The source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
// for more details.
//
// DESCRIPTION:
// AutoMap module.
//
//-----------------------------------------------------------------------------
#ifndef __AMMAP_H__
#define __AMMAP_H__
struct event_t;
class FArchive;
void AM_StaticInit();
// Called by main loop.
bool AM_Responder (event_t* ev, bool last);
// Called by main loop.
void AM_Ticker (void);
// Called by main loop,
// called instead of view drawer if automap active.
void AM_Drawer (void);
// Called to force the automap to quit
// if the level is completed while it is up.
void AM_Stop (void);
void AM_NewResolution ();
void AM_ToggleMap ();
void AM_LevelInit ();
void AM_SerializeMarkers(FArchive &arc);
#endif
| 399 |
476 | import argparse
import os
import sys
import tempfile
from pathlib import Path
from timeit import default_timer as timer
from typing import List
from printer import Printer as P
from printer import print_test_results, print_test_results_machine
from testrunner import TestRunner
from testsuite import TestSuite
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"test_directory", help="The directory where the toolchain tests are located."
)
parser.add_argument(
"-v", "--verbose", action="store_true", help="Print verbose output"
)
parser.add_argument(
"-j",
"--jobs",
type=int,
default=int(os.cpu_count() / 2),
help="Number of threads to use for parallel execution (defaults to half of the system max)",
)
parser.add_argument(
"-t", "--tests", default="all", help="Test/Testsuite to run (defaults to all)"
)
parser.add_argument(
"--format",
choices=("human", "xunit"),
default="human",
help="Format of the test output (defaults to human)",
)
parser.add_argument(
"--cdt",
default=get_cdt_path(),
help="Path to CDT (defaults to built CDT in this repo)",
)
args = parser.parse_args()
P.verbose = args.verbose
abs_test_directory = os.path.abspath(args.test_directory)
temp_dir = tempfile.mkdtemp()
P.print(f"Temp files will be written to {temp_dir}", verbose=True)
os.chdir(temp_dir)
test_directories: List[str] = []
for f in os.listdir(abs_test_directory):
abs_f = os.path.join(abs_test_directory, f)
if os.path.isdir(abs_f):
test_directories.append(abs_f)
test_suites = list(map(lambda d: TestSuite(d, args.cdt), test_directories))
start = timer()
test_runner = TestRunner(test_suites, args.tests, args.jobs)
test_results = test_runner.run_tests()
end = timer()
if args.format == "human":
failures = print_test_results(test_results, end - start)
else:
failures = print_test_results_machine(test_results, end - start)
if failures:
sys.exit(1)
sys.exit(0)
def get_cdt_path() -> str:
return os.path.join(
Path(os.path.realpath(__file__)).parent.parent.parent, "build", "bin"
)
if __name__ == "__main__":
main()
| 949 |
1,711 | <reponame>sobolevn/paasta<gh_stars>1000+
# coding: utf-8
# flake8: noqa
"""
Paasta API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
__version__ = "1.0.0"
# import ApiClient
from paasta_tools.paastaapi.api_client import ApiClient
# import Configuration
from paasta_tools.paastaapi.configuration import Configuration
# import exceptions
from paasta_tools.paastaapi.exceptions import OpenApiException
from paasta_tools.paastaapi.exceptions import ApiAttributeError
from paasta_tools.paastaapi.exceptions import ApiTypeError
from paasta_tools.paastaapi.exceptions import ApiValueError
from paasta_tools.paastaapi.exceptions import ApiKeyError
from paasta_tools.paastaapi.exceptions import ApiException
| 290 |
410 | <filename>lib/bk/bkblock.c
#include "bkblock.h"
static void bkblock_acells(bk_Block *b, uint32_t len) {
if (len <= b->length + b->free) {
// We have enough space
b->free -= len - b->length;
b->length = len;
} else {
// allocate space
b->length = len;
b->free = (len >> 1) & 0xFFFFFF;
RESIZE(b->cells, b->length + b->free);
}
}
bool bk_cellIsPointer(bk_Cell *cell) {
return cell->t >= p16;
}
static bk_Cell *bkblock_grow(bk_Block *b, uint32_t len) {
uint32_t olen = b->length;
bkblock_acells(b, olen + len);
return &(b->cells[olen]);
}
bk_Block *_bkblock_init() {
bk_Block *b;
NEW(b);
bkblock_acells(b, 0);
return b;
}
void bkblock_pushint(bk_Block *b, bk_CellType type, uint32_t x) {
bk_Cell *cell = bkblock_grow(b, 1);
cell->t = type;
cell->z = x;
}
void bkblock_pushptr(bk_Block *b, bk_CellType type, bk_Block *p) {
bk_Cell *cell = bkblock_grow(b, 1);
cell->t = type;
cell->p = p;
}
static void vbkpushitems(bk_Block *b, bk_CellType type0, va_list ap) {
bk_CellType curtype = type0;
while (curtype) {
if (curtype == bkcopy || curtype == bkembed) {
bk_Block *par = va_arg(ap, bk_Block *);
if (par && par->cells) {
for (uint32_t j = 0; j < par->length; j++) {
if (bk_cellIsPointer(par->cells + j)) {
bkblock_pushptr(b, par->cells[j].t, par->cells[j].p);
} else {
bkblock_pushint(b, par->cells[j].t, par->cells[j].z);
}
}
}
if (curtype == bkembed && par) {
FREE(par->cells);
FREE(par);
}
} else if (curtype < p16) {
uint32_t par = va_arg(ap, int);
bkblock_pushint(b, curtype, par);
} else {
bk_Block *par = va_arg(ap, bk_Block *);
bkblock_pushptr(b, curtype, par);
}
curtype = va_arg(ap, int);
}
}
bk_Block *bk_new_Block(int type0, ...) {
va_list ap;
va_start(ap, type0);
bk_Block *b = _bkblock_init();
vbkpushitems(b, type0, ap);
va_end(ap);
return b;
}
bk_Block *bk_push(bk_Block *b, int type0, ...) {
va_list ap;
va_start(ap, type0);
vbkpushitems(b, type0, ap);
va_end(ap);
return b;
}
bk_Block *bk_newBlockFromStringLen(size_t len, const char *str) {
if (!str) return NULL;
bk_Block *b = bk_new_Block(bkover);
for (size_t j = 0; j < len; j++) {
bkblock_pushint(b, b8, str[j]);
}
return b;
}
bk_Block *bk_newBlockFromBuffer(MOVE caryll_Buffer *buf) {
if (!buf) return NULL;
bk_Block *b = bk_new_Block(bkover);
for (size_t j = 0; j < buf->size; j++) {
bkblock_pushint(b, b8, buf->data[j]);
}
buffree(buf);
return b;
}
bk_Block *bk_newBlockFromBufferCopy(OBSERVE caryll_Buffer *buf) {
if (!buf) return NULL;
bk_Block *b = bk_new_Block(bkover);
for (size_t j = 0; j < buf->size; j++) {
bkblock_pushint(b, b8, buf->data[j]);
}
return b;
}
void bk_printBlock(bk_Block *b) {
fprintf(stderr, "Block size %08x\n", (uint32_t)b->length);
fprintf(stderr, "------------------\n");
for (uint32_t j = 0; j < b->length; j++) {
if (bk_cellIsPointer(b->cells + j)) {
if (b->cells[j].p) {
fprintf(stderr, " %3d %p[%d]\n", b->cells[j].t, b->cells[j].p,
b->cells[j].p->_index);
} else {
fprintf(stderr, " %3d [NULL]\n", b->cells[j].t);
}
} else {
fprintf(stderr, " %3d %d\n", b->cells[j].t, b->cells[j].z);
}
}
fprintf(stderr, "------------------\n");
}
| 1,627 |
602 | <gh_stars>100-1000
#pragma once
#include <string>
#include <vector>
#include "common/goos/Object.h"
#include "common/goos/Reader.h"
#include "common/goos/Printer.h"
namespace pretty_print {
// main pretty print function
std::string to_string(const goos::Object& obj, int line_length = 110);
} // namespace pretty_print
| 114 |
11,356 | <filename>deps/src/boost_1_65_1/libs/phoenix/test/function/lazy_list2_tests.cpp
////////////////////////////////////////////////////////////////////////////
// lazy_list2_tests.cpp
//
// more tests on list<T>
//
////////////////////////////////////////////////////////////////////////////
/*=============================================================================
Copyright (c) 2000-2003 <NAME> and <NAME>
Copyright (c) 2001-2007 <NAME>
Copyright (c) 2015 <NAME>
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 <boost/phoenix/core/limits.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/function/lazy_prelude.hpp>
int main()
{
namespace phx = boost::phoenix;
using boost::phoenix::arg_names::arg1;
using boost::phoenix::arg_names::arg2;
using namespace phx;
list<int> l0;
list<int> l1 = list_with<>()(1,2,3,4,5);
list<int> l2 = all_but_last(l1)();
BOOST_TEST(null(l0)());
BOOST_TEST(head(l1)() == 1);
BOOST_TEST(head(tail(l1))() == 2);
BOOST_TEST(last(l1)() == 5);
BOOST_TEST(last(l2)() == 4);
BOOST_TEST(head(drop(2,l2))() == 3);
return boost::report_errors();
}
| 523 |
11,868 | <reponame>MalcolmScoffable/openapi-generator
{"mine":1,"sold":18,"string":568,"Dead":2,"test":2,"Nonavailable":1,"custom":3,"pending":20,"available":2212,"notAvailable":26,"avaiflable":1,"AVAILABLE":1,"swimming":1,"availablee":2,"success":1,"105":1,"missing":11,"disabled":1,"Available":1,"]]>":1} | 112 |
308 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#import <Foundation/Foundation.h>
#import "MSACModel.h"
#import "MSACSerializableObject.h"
static NSString *const kMSACAppId = @"id";
static NSString *const kMSACAppLocale = @"locale";
static NSString *const kMSACAppName = @"name";
static NSString *const kMSACAppVer = @"ver";
static NSString *const kMSACAppUserId = @"userId";
/**
* The App extension contains data specified by the application.
*/
@interface MSACAppExtension : NSObject <MSACSerializableObject, MSACModel>
/**
* The application's bundle identifier.
*/
@property(nonatomic, copy) NSString *appId;
/**
* The application's version.
*/
@property(nonatomic, copy) NSString *ver;
/**
* The application's name.
*/
@property(nonatomic, copy) NSString *name;
/**
* The application's locale.
*/
@property(nonatomic, copy) NSString *locale;
/**
* The application's userId.
*/
@property(nonatomic, copy) NSString *userId;
@end
| 320 |
675 | /*
* Copyright 2017 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.scala.run.smrunner;
import static com.google.idea.blaze.base.run.smrunner.SmRunnerUtils.GENERIC_SUITE_PROTOCOL;
import static com.google.idea.blaze.base.run.smrunner.SmRunnerUtils.GENERIC_TEST_PROTOCOL;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.idea.blaze.base.run.smrunner.SmRunnerUtils;
import com.google.idea.blaze.scala.run.Specs2Utils;
import com.intellij.execution.Location;
import com.intellij.execution.PsiLocation;
import com.intellij.execution.testframework.JavaTestLocator;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.ClassUtil;
import com.intellij.psi.util.PsiTreeUtil;
import java.util.List;
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScInfixExpr;
import org.jetbrains.plugins.scala.testingSupport.test.structureView.TestNodeProvider;
/** Locate scala test packages / functions for test UI navigation. */
public final class BlazeScalaTestLocator extends JavaTestLocator {
public static final BlazeScalaTestLocator INSTANCE = new BlazeScalaTestLocator();
private BlazeScalaTestLocator() {}
@Override
@SuppressWarnings("rawtypes")
public List<Location> getLocation(
String protocol, String path, Project project, GlobalSearchScope scope) {
List<Location> location = super.getLocation(protocol, path, project, scope);
if (!location.isEmpty()) {
// Regular JUnit tests and specs2 test classes.
return location;
}
switch (protocol) {
case GENERIC_SUITE_PROTOCOL:
// specs2 test.xml doesn't currently output the necessary information to location suites.
return ImmutableList.of();
case GENERIC_TEST_PROTOCOL:
return findTestCase(project, path);
default:
return ImmutableList.of();
}
}
@SuppressWarnings("rawtypes")
private List<Location> findTestCase(Project project, String path) {
String[] parts = path.split(SmRunnerUtils.TEST_NAME_PARTS_SPLITTER, 2);
if (parts.length < 2) {
return ImmutableList.of();
}
String className = parts[0];
String testName = parts[1];
PsiClass testClass = ClassUtil.findPsiClass(PsiManager.getInstance(project), className);
for (ScInfixExpr testCase : PsiTreeUtil.findChildrenOfType(testClass, ScInfixExpr.class)) {
if (TestNodeProvider.isSpecs2TestExpr(testCase)
&& Objects.equal(Specs2Utils.getSpecs2ScopedTestName(testCase), testName)) {
return ImmutableList.of(new PsiLocation<>(testCase));
}
}
return ImmutableList.of();
}
}
| 1,148 |
9,402 | <reponame>pyracanda/runtime<gh_stars>1000+
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "ildasmpch.h"
#include "mdfileformat.h"
#include "../tools/metainfo/mdinfo.cpp"
#include "../tools/metainfo/mdobj.cpp"
| 106 |
3,172 | <gh_stars>1000+
# Copyright (c) 2021 PaddlePaddle Authors. 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.
import parl
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
class MAModel(parl.Model):
def __init__(self, obs_dim, act_dim, critic_in_dim):
super(MAModel, self).__init__()
self.actor_model = ActorModel(obs_dim, act_dim)
self.critic_model = CriticModel(critic_in_dim)
def policy(self, obs):
return self.actor_model(obs)
def value(self, obs, act):
return self.critic_model(obs, act)
def get_actor_params(self):
return self.actor_model.parameters()
def get_critic_params(self):
return self.critic_model.parameters()
class ActorModel(parl.Model):
def __init__(self, obs_dim, act_dim):
super(ActorModel, self).__init__()
hid1_size = 64
hid2_size = 64
self.fc1 = nn.Linear(
obs_dim,
hid1_size,
weight_attr=paddle.ParamAttr(
initializer=paddle.nn.initializer.XavierUniform()))
self.fc2 = nn.Linear(
hid1_size,
hid2_size,
weight_attr=paddle.ParamAttr(
initializer=paddle.nn.initializer.XavierUniform()))
self.fc3 = nn.Linear(
hid2_size,
act_dim,
weight_attr=paddle.ParamAttr(
initializer=paddle.nn.initializer.XavierUniform()))
def forward(self, obs):
hid1 = F.relu(self.fc1(obs))
hid2 = F.relu(self.fc2(hid1))
means = self.fc3(hid2)
return means
class CriticModel(parl.Model):
def __init__(self, critic_in_dim):
super(CriticModel, self).__init__()
hid1_size = 64
hid2_size = 64
out_dim = 1
self.fc1 = nn.Linear(
critic_in_dim,
hid1_size,
weight_attr=paddle.ParamAttr(
initializer=paddle.nn.initializer.XavierUniform()))
self.fc2 = nn.Linear(
hid1_size,
hid2_size,
weight_attr=paddle.ParamAttr(
initializer=paddle.nn.initializer.XavierUniform()))
self.fc3 = nn.Linear(
hid2_size,
out_dim,
weight_attr=paddle.ParamAttr(
initializer=paddle.nn.initializer.XavierUniform()))
def forward(self, obs_n, act_n):
inputs = paddle.concat(obs_n + act_n, axis=1)
hid1 = F.relu(self.fc1(inputs))
hid2 = F.relu(self.fc2(hid1))
Q = self.fc3(hid2)
Q = paddle.squeeze(Q, axis=1)
return Q
| 1,476 |
570 | <reponame>AmbientAI/amazon-kinesis-client
/*
* Copyright 2019 Amazon.com, Inc. 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 software.amazon.kinesis.checkpoint;
import lombok.Data;
import lombok.experimental.Accessors;
import software.amazon.kinesis.retrieval.kpl.ExtendedSequenceNumber;
/**
* A class encapsulating the 2 pieces of state stored in a checkpoint.
*/
@Data
@Accessors(fluent = true)
public class Checkpoint {
private final ExtendedSequenceNumber checkpoint;
private final ExtendedSequenceNumber pendingCheckpoint;
private final byte[] pendingCheckpointState;
@Deprecated
public Checkpoint(final ExtendedSequenceNumber checkpoint, final ExtendedSequenceNumber pendingCheckpoint) {
this(checkpoint, pendingCheckpoint, null);
}
/**
* Constructor.
*
* @param checkpoint the checkpoint sequence number - cannot be null or empty.
* @param pendingCheckpoint the pending checkpoint sequence number - can be null.
* @param pendingCheckpointState the pending checkpoint state - can be null.
*/
public Checkpoint(final ExtendedSequenceNumber checkpoint, final ExtendedSequenceNumber pendingCheckpoint, byte[] pendingCheckpointState) {
if (checkpoint == null || checkpoint.sequenceNumber().isEmpty()) {
throw new IllegalArgumentException("Checkpoint cannot be null or empty");
}
this.checkpoint = checkpoint;
this.pendingCheckpoint = pendingCheckpoint;
this.pendingCheckpointState = pendingCheckpointState;
}
}
| 610 |
2,151 | <reponame>zipated/src
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/network/public/cpp/cors/preflight_result.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/time/default_tick_clock.h"
#include "base/time/tick_clock.h"
#include "base/time/time.h"
#include "net/http/http_request_headers.h"
#include "services/network/public/cpp/cors/cors.h"
namespace network {
namespace cors {
namespace {
// Timeout values below are at the discretion of the user agent.
// Default cache expiry time for an entry that does not have
// Access-Control-Max-Age header in its CORS-preflight response.
constexpr base::TimeDelta kDefaultTimeout = base::TimeDelta::FromSeconds(5);
// Maximum cache expiry time. Even if a CORS-preflight response contains
// Access-Control-Max-Age header that specifies a longer expiry time, this
// maximum time is applied.
//
// Note: Should be short enough to minimize the risk of using a poisoned cache
// after switching to a secure network.
// TODO(toyoshim): Consider to invalidate all entries when network configuration
// is changed. See also discussion at https://crbug.com/131368.
constexpr base::TimeDelta kMaxTimeout = base::TimeDelta::FromSeconds(600);
// Holds TickClock instance to overwrite TimeTicks::Now() for testing.
const base::TickClock* tick_clock_for_testing = nullptr;
base::TimeTicks Now() {
if (tick_clock_for_testing)
return tick_clock_for_testing->NowTicks();
return base::TimeTicks::Now();
}
bool ParseAccessControlMaxAge(const base::Optional<std::string>& max_age,
base::TimeDelta* expiry_delta) {
DCHECK(expiry_delta);
if (!max_age)
return false;
uint64_t delta;
if (!base::StringToUint64(*max_age, &delta))
return false;
*expiry_delta = base::TimeDelta::FromSeconds(delta);
if (*expiry_delta > kMaxTimeout)
*expiry_delta = kMaxTimeout;
return true;
}
// At this moment, this function always succeeds.
bool ParseAccessControlAllowList(const base::Optional<std::string>& string,
base::flat_set<std::string>* set,
bool insert_in_lower_case) {
DCHECK(set);
if (!string)
return true;
for (const auto& value : base::SplitString(
*string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
// TODO(toyoshim): Strict ABNF header field checks want to be applied, e.g.
// strict VCHAR check of RFC-7230.
set->insert(insert_in_lower_case ? base::ToLowerASCII(value) : value);
}
return true;
}
} // namespace
// static
void PreflightResult::SetTickClockForTesting(
const base::TickClock* tick_clock) {
tick_clock_for_testing = tick_clock;
}
// static
std::unique_ptr<PreflightResult> PreflightResult::Create(
const mojom::FetchCredentialsMode credentials_mode,
const base::Optional<std::string>& allow_methods_header,
const base::Optional<std::string>& allow_headers_header,
const base::Optional<std::string>& max_age_header,
base::Optional<mojom::CORSError>* detected_error) {
std::unique_ptr<PreflightResult> result =
base::WrapUnique(new PreflightResult(credentials_mode));
base::Optional<mojom::CORSError> error =
result->Parse(allow_methods_header, allow_headers_header, max_age_header);
if (error) {
if (detected_error)
*detected_error = error;
return nullptr;
}
return result;
}
PreflightResult::PreflightResult(
const mojom::FetchCredentialsMode credentials_mode)
: credentials_(credentials_mode == mojom::FetchCredentialsMode::kInclude) {}
PreflightResult::~PreflightResult() = default;
base::Optional<mojom::CORSError>
PreflightResult::EnsureAllowedCrossOriginMethod(
const std::string& method) const {
// Request method is normalized to upper case, and comparison is performed in
// case-sensitive way, that means access control header should provide an
// upper case method list.
const std::string normalized_method = base::ToUpperASCII(method);
if (methods_.find(normalized_method) != methods_.end() ||
IsCORSSafelistedMethod(normalized_method)) {
return base::nullopt;
}
if (!credentials_ && methods_.find("*") != methods_.end())
return base::nullopt;
return mojom::CORSError::kMethodDisallowedByPreflightResponse;
}
base::Optional<mojom::CORSError>
PreflightResult::EnsureAllowedCrossOriginHeaders(
const net::HttpRequestHeaders& headers,
std::string* detected_header) const {
if (!credentials_ && headers_.find("*") != headers_.end())
return base::nullopt;
for (const auto& header : headers.GetHeaderVector()) {
// Header list check is performed in case-insensitive way. Here, we have a
// parsed header list set in lower case, and search each header in lower
// case.
const std::string key = base::ToLowerASCII(header.key);
if (headers_.find(key) == headers_.end() &&
!IsCORSSafelistedHeader(key, header.value)) {
// Forbidden headers are forbidden to be used by JavaScript, and checked
// beforehand. But user-agents may add these headers internally, and it's
// fine.
if (IsForbiddenHeader(key))
continue;
if (detected_header)
*detected_header = header.key;
return mojom::CORSError::kHeaderDisallowedByPreflightResponse;
}
}
return base::nullopt;
}
bool PreflightResult::EnsureAllowedRequest(
mojom::FetchCredentialsMode credentials_mode,
const std::string& method,
const net::HttpRequestHeaders& headers) const {
if (absolute_expiry_time_ <= Now())
return false;
if (!credentials_ &&
credentials_mode == mojom::FetchCredentialsMode::kInclude) {
return false;
}
if (EnsureAllowedCrossOriginMethod(method))
return false;
if (EnsureAllowedCrossOriginHeaders(headers, nullptr))
return false;
return true;
}
base::Optional<mojom::CORSError> PreflightResult::Parse(
const base::Optional<std::string>& allow_methods_header,
const base::Optional<std::string>& allow_headers_header,
const base::Optional<std::string>& max_age_header) {
DCHECK(methods_.empty());
DCHECK(headers_.empty());
// Keeps parsed method case for case-sensitive search.
if (!ParseAccessControlAllowList(allow_methods_header, &methods_, false))
return mojom::CORSError::kInvalidAllowMethodsPreflightResponse;
// Holds parsed headers in lower case for case-insensitive search.
if (!ParseAccessControlAllowList(allow_headers_header, &headers_, true))
return mojom::CORSError::kInvalidAllowHeadersPreflightResponse;
base::TimeDelta expiry_delta;
if (max_age_header) {
// Set expiry_delta to 0 on invalid Access-Control-Max-Age headers so to
// invalidate the entry immediately. CORS-preflight response should be still
// usable for the request that initiates the CORS-preflight.
if (!ParseAccessControlMaxAge(max_age_header, &expiry_delta))
expiry_delta = base::TimeDelta();
} else {
expiry_delta = kDefaultTimeout;
}
absolute_expiry_time_ = Now() + expiry_delta;
return base::nullopt;
}
} // namespace cors
} // namespace network
| 2,539 |
634 | <gh_stars>100-1000
package com.intellij.util;
import consulo.util.dataholder.Key;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
/**
* @author peter
*/
public class ProcessingContext {
private Map<Object, Object> myMap;
private SharedProcessingContext mySharedContext;
public ProcessingContext() {
}
public ProcessingContext(final SharedProcessingContext sharedContext) {
mySharedContext = sharedContext;
}
@Nonnull
public SharedProcessingContext getSharedContext() {
if (mySharedContext == null) {
return mySharedContext = new SharedProcessingContext();
}
return mySharedContext;
}
@SuppressWarnings({"ConstantConditions"})
public Object get(@Nonnull @NonNls final Object key) {
return myMap == null? null : myMap.get(key);
}
public void put(@Nonnull @NonNls final Object key, @Nonnull final Object value) {
checkMapInitialized();
myMap.put(key, value);
}
public <T> void put(Key<T> key, T value) {
checkMapInitialized();
myMap.put(key, value);
}
@SuppressWarnings({"ConstantConditions"})
public <T> T get(Key<T> key) {
return myMap == null ? null : (T)myMap.get(key);
}
private void checkMapInitialized() {
if (myMap == null) myMap = new HashMap<Object, Object>(1);
}
}
| 471 |
3,358 | <reponame>urgu00/QuantLib
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<<EMAIL>>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file ridder.hpp
\brief Ridder 1-D solver
*/
#ifndef quantlib_solver1d_ridder_h
#define quantlib_solver1d_ridder_h
#include <ql/math/solver1d.hpp>
namespace QuantLib {
//! %Ridder 1-D solver
/*! \test the correctness of the returned values is tested by
checking them against known good results.
\ingroup solvers
*/
class Ridder : public Solver1D<Ridder> {
public:
template <class F>
Real solveImpl(const F& f,
Real xAcc) const {
/* The implementation of the algorithm was inspired by
Press, Teukolsky, Vetterling, and Flannery,
"Numerical Recipes in C", 2nd edition,
Cambridge University Press
*/
Real fxMid, froot, s, xMid, nextRoot;
// test on Black-Scholes implied volatility show that
// Ridder solver algorithm actually provides an
// accuracy 100 times below promised
Real xAccuracy = xAcc/100.0;
// Any highly unlikely value, to simplify logic below
root_ = QL_MIN_REAL;
while (evaluationNumber_<=maxEvaluations_) {
xMid = 0.5*(xMin_+xMax_);
// First of two function evaluations per iteraton
fxMid = f(xMid);
++evaluationNumber_;
s = std::sqrt(fxMid*fxMid-fxMin_*fxMax_);
if (close(s, 0.0)) {
f(root_);
++evaluationNumber_;
return root_;
}
// Updating formula
nextRoot = xMid + (xMid - xMin_) *
((fxMin_ >= fxMax_ ? 1.0 : -1.0) * fxMid / s);
if (std::fabs(nextRoot-root_) <= xAccuracy) {
f(root_);
++evaluationNumber_;
return root_;
}
root_ = nextRoot;
// Second of two function evaluations per iteration
froot = f(root_);
++evaluationNumber_;
if (close(froot, 0.0))
return root_;
// Bookkeeping to keep the root bracketed on next iteration
if (sign(fxMid,froot) != fxMid) {
xMin_ = xMid;
fxMin_ = fxMid;
xMax_ = root_;
fxMax_ = froot;
} else if (sign(fxMin_,froot) != fxMin_) {
xMax_ = root_;
fxMax_ = froot;
} else if (sign(fxMax_,froot) != fxMax_) {
xMin_ = root_;
fxMin_ = froot;
} else {
QL_FAIL("never get here.");
}
if (std::fabs(xMax_-xMin_) <= xAccuracy) {
f(root_);
++evaluationNumber_;
return root_;
}
}
QL_FAIL("maximum number of function evaluations ("
<< maxEvaluations_ << ") exceeded");
}
private:
Real sign(Real a, Real b) const {
return b >= 0.0 ? std::fabs(a) : -std::fabs(a);
}
};
}
#endif
| 2,099 |
2,151 | /*
* Copyright © 2014 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): <NAME>
*/
#include <stdlib.h>
#include <stdio.h>
#include "hb-fc.h"
static hb_bool_t
hb_fc_get_glyph (hb_font_t *font /*HB_UNUSED*/,
void *font_data,
hb_codepoint_t unicode,
hb_codepoint_t variation_selector,
hb_codepoint_t *glyph,
void *user_data /*HB_UNUSED*/)
{
FcCharSet *cs = (FcCharSet *) font_data;
if (variation_selector)
{
/* Fontconfig doesn't cache cmap-14 info. However:
* 1. If the font maps the variation_selector, assume it's
* supported,
* 2. If the font doesn't map it, still say it's supported,
* but return 0. This way, the caller will see the zero
* and reject. If we return unsupported here, then the
* variation selector will be hidden and ignored.
*/
if (FcCharSetHasChar (cs, unicode) &&
FcCharSetHasChar (cs, variation_selector))
{
unsigned int var_num = 0;
if (variation_selector - 0xFE00u < 16)
var_num = variation_selector - 0xFE00 + 1;
else if (variation_selector - 0xE0100u < (256 - 16))
var_num = variation_selector - 0xE0100 + 17;
*glyph = (var_num << 21) | unicode;
}
else
{
*glyph = 0;
}
return true;
}
*glyph = FcCharSetHasChar (cs, unicode) ? unicode : 0;
return *glyph != 0;
}
static hb_font_funcs_t *
_hb_fc_get_font_funcs (void)
{
static const hb_font_funcs_t *fc_ffuncs;
const hb_font_funcs_t *ffuncs;
if (!(ffuncs = fc_ffuncs))
{
hb_font_funcs_t *newfuncs = hb_font_funcs_create ();
hb_font_funcs_set_glyph_func (newfuncs, hb_fc_get_glyph, nullptr, nullptr);
/* XXX MT-unsafe */
if (fc_ffuncs)
hb_font_funcs_destroy (newfuncs);
else
fc_ffuncs = ffuncs = newfuncs;
}
return const_cast<hb_font_funcs_t *> (fc_ffuncs);
}
hb_font_t *
hb_fc_font_create (FcPattern *fcfont)
{
static hb_face_t *face;
hb_font_t *font;
FcCharSet *cs;
if (FcResultMatch != FcPatternGetCharSet (fcfont, FC_CHARSET, 0, &cs))
return hb_font_get_empty ();
if (!face) /* XXX MT-unsafe */
face = hb_face_create (hb_blob_get_empty (), 0);
font = hb_font_create (face);
hb_font_set_funcs (font,
_hb_fc_get_font_funcs (),
FcCharSetCopy (cs),
(hb_destroy_func_t) FcCharSetDestroy);
return font;
}
hb_bool_t
hb_fc_can_render (hb_font_t *font, const char *text)
{
static const char *ot[] = {"ot", nullptr};
hb_buffer_t *buffer = hb_buffer_create ();
hb_buffer_add_utf8 (buffer, text, -1, 0, -1);
/* XXX Do we need this? I think Arabic and Hangul shapers are the
* only one that make any use of this. The Hangul case is not really
* needed, and for Arabic we'll miss a very narrow set of fonts.
* Might be better to force generic shaper perhaps. */
hb_buffer_guess_segment_properties (buffer);
if (!hb_shape_full (font, buffer, nullptr, 0, ot))
abort (); /* hb-ot shaper not enabled? */
unsigned int len;
hb_glyph_info_t *info = hb_buffer_get_glyph_infos (buffer, &len);
for (unsigned int i = 0; i < len; i++)
{
if (!info[i].codepoint)
{
return false;
}
}
return true;
}
| 1,689 |
701 | <gh_stars>100-1000
#include <cc/ast/val.h>
const char *cval_type_to_str_raw[CVAL_COUNT] =
{
[CVAL_SIGNED] = "signed",
[CVAL_UNSIGNED] = "unsigned",
[CVAL_FLOAT] = "float",
[CVAL_STRING] = "string",
};
Str cval_type_to_str(CValType type)
{
return str$(cval_type_to_str_raw[type]);
}
| 171 |
440 | <filename>IGC/Compiler/PromoteResourceToDirectAS.h
/*========================== begin_copyright_notice ============================
Copyright (C) 2017-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#pragma once
#include "common/LLVMWarningsPush.hpp"
#include <llvm/Pass.h>
#include <llvm/IR/InstVisitor.h>
#include "common/LLVMWarningsPop.hpp"
#include "Compiler/CISACodeGen/CISACodeGen.h"
#include "Compiler/MetaDataUtilsWrapper.h"
#include "GenISAIntrinsics/GenIntrinsicInst.h"
#include <unordered_map>
namespace IGC
{
class PromoteResourceToDirectAS : public llvm::FunctionPass, public llvm::InstVisitor<PromoteResourceToDirectAS>
{
public:
static char ID;
PromoteResourceToDirectAS();
virtual llvm::StringRef getPassName() const override
{
return "PromoteResourceToDirectAS";
}
virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override
{
AU.addRequired<IGC::MetaDataUtilsWrapper>();
AU.addRequired<IGC::CodeGenContextWrapper>();
AU.setPreservesCFG();
}
bool runOnFunction(llvm::Function& F) override;
void visitInstruction(llvm::Instruction& I);
private:
void PromoteSamplerTextureToDirectAS(llvm::GenIntrinsicInst*& pIntr, llvm::Value* resourcePtr);
void PromoteBufferToDirectAS(llvm::Instruction* inst, llvm::Value* resourcePtr);
llvm::Value* getOffsetValue(llvm::Value* srcPtr, int& bufferoffset);
CodeGenContext* m_pCodeGenContext;
IGCMD::MetaDataUtils* m_pMdUtils;
std::unordered_map<llvm::Value*, llvm::Value*> m_SrcPtrToBufferOffsetMap;
};
} // namespace IGC
| 725 |
6,034 | <reponame>ssSlowDown/onemall<filename>moved/system/system-biz/src/main/java/cn/iocoder/mall/system/biz/log/operation/event/OperationLogListener.java
package cn.iocoder.mall.system.biz.log.operation.event;
import cn.iocoder.mall.system.biz.log.operation.service.OperationLogSaveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
/**
* @author
* 异步监听日志事件
*/
@Slf4j
public class OperationLogListener {
@Autowired
private OperationLogSaveService operationLogSaveService;
@Async
@Order
@EventListener(OperationLogEvent.class)
public void saveSysLog(OperationLogEvent event) {
operationLogSaveService.saveLog(event.getOperationLogDTO());
}
}
| 304 |
3,269 | <filename>Algo and DSA/LeetCode-Solutions-master/Python/number-of-paths-with-max-score.py
# Time: O(n^2)
# Space: O(n)
class Solution(object):
def pathsWithMaxScore(self, board):
"""
:type board: List[str]
:rtype: List[int]
"""
MOD = 10**9+7
directions = [[1, 0], [0, 1], [1, 1]]
dp = [[[0, 0] for r in xrange(len(board[0])+1)]
for r in xrange(2)]
dp[(len(board)-1)%2][len(board[0])-1] = [0, 1]
for r in reversed(xrange(len(board))):
for c in reversed(xrange(len(board[0]))):
if board[r][c] in "XS":
continue
dp[r%2][c] = [0, 0]
for dr, dc in directions:
if dp[r%2][c][0] < dp[(r+dr)%2][c+dc][0]:
dp[r%2][c] = dp[(r+dr)%2][c+dc][:]
elif dp[r%2][c][0] == dp[(r+dr)%2][c+dc][0]:
dp[r%2][c][1] = (dp[r%2][c][1]+dp[(r+dr)%2][c+dc][1]) % MOD
if dp[r%2][c][1] and board[r][c] != 'E':
dp[r%2][c][0] += int(board[r][c])
return dp[0][0]
| 718 |
984 | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
Module Name:
spapidef.h
Abstract:
Public header file for Windows NT Setup and Device Installer services Dll.
--*/
#ifndef _INC_SPAPIDEF
#define _INC_SPAPIDEF
#if _MSC_VER > 1000
#pragma once
#endif
#include <winapifamily.h>
#pragma region Desktop Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#ifndef SP_LOG_TOKEN
typedef DWORDLONG SP_LOG_TOKEN;
typedef DWORDLONG *PSP_LOG_TOKEN;
#endif
//
// Special txtlog token values
//
#define LOGTOKEN_TYPE_MASK 3
#define LOGTOKEN_UNSPECIFIED 0
#define LOGTOKEN_NO_LOG 1
#define LOGTOKEN_SETUPAPI_APPLOG 2
#define LOGTOKEN_SETUPAPI_DEVLOG 3
//
// Flags for SetupCreateTextLogSection
//
#define TXTLOG_SETUPAPI_DEVLOG 0x00000001 // 1 = setupdi.log, 0 = setupapi.log
#define TXTLOG_SETUPAPI_CMDLINE 0x00000002 // log the command line
#define TXTLOG_SETUPAPI_BITS 0x00000003
//
// Flags for SetupWriteTextLog
//
//
// Event Levels (bits 0-3)
//
#define TXTLOG_ERROR 0x1 // shows entries which indicate a real problem
#define TXTLOG_WARNING 0x2 // shows entries which indicate a potential problem
#define TXTLOG_SYSTEM_STATE_CHANGE 0x3 // system changes only
#define TXTLOG_SUMMARY 0x4 // show basic operation surrounding system changes
#define TXTLOG_DETAILS 0x5 // detailed operation of the install process
#define TXTLOG_VERBOSE 0x6 // log entries which potentially generate a lot of data
#define TXTLOG_VERY_VERBOSE 0x7 // highest level shows all log entries
//
// Bits reserved for internal use
//
#define TXTLOG_RESERVED_FLAGS 0x0000FFF0
//
// Basic flags (bits 4-31)
//
#define TXTLOG_TIMESTAMP 0x00010000
#define TXTLOG_DEPTH_INCR 0x00020000
#define TXTLOG_DEPTH_DECR 0x00040000
#define TXTLOG_TAB_1 0x00080000
#define TXTLOG_FLUSH_FILE 0x00100000
#define TXTLOG_LEVEL(flags) (flags & 0xf)
//
// Setupapi, Setupdi event categories
//
#define TXTLOG_DEVINST 0x00000001
#define TXTLOG_INF 0x00000002
#define TXTLOG_FILEQ 0x00000004
#define TXTLOG_COPYFILES 0x00000008
#define TXTLOG_SIGVERIF 0x00000020
#define TXTLOG_BACKUP 0x00000080
#define TXTLOG_UI 0x00000100
#define TXTLOG_UTIL 0x00000200
#define TXTLOG_INFDB 0x00000400
#define TXTLOG_DRVSETUP 0x00400000
#define TXTLOG_POLICY 0x00800000
#define TXTLOG_NEWDEV 0x01000000
#define TXTLOG_UMPNPMGR 0x02000000
#define TXTLOG_DRIVER_STORE 0x04000000
#define TXTLOG_SETUP 0x08000000
#define TXTLOG_CMI 0x10000000
#define TXTLOG_DEVMGR 0x20000000
#define TXTLOG_INSTALLER 0x40000000
#define TXTLOG_VENDOR 0x80000000
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */
#pragma endregion
#endif // _INC_SPAPIDEF
| 1,515 |
666 | <gh_stars>100-1000
/**
*
* Copyright 2018 iQIYI.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.iqiyi.halberd.liteapp.plugin.widget.impl;
import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;
import com.iqiyi.halberd.liteapp.api.provider.LiteAppNativeViewHolder;
import com.iqiyi.halberd.liteapp.context.LiteAppContext;
import com.iqiyi.halberd.liteapp.api.provider.LiteAppNativeWidgetBase;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by <EMAIL> on 2017/8/8.
* use this to create a color box (useless)
*/
public class ColorBoxWidget extends LiteAppNativeWidgetBase {
@Override
public LiteAppNativeViewHolder createNativeViewHolder(int top, int left, int width, int height, JSONObject viewData, Context context, LiteAppContext liteAppContext) throws JSONException {
float scale = context.getResources().getDisplayMetrics().density;
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams
(Math.round(width * scale), Math.round(height * scale));
layoutParams.setMargins(Math.round(left * scale), Math.round(top * scale), 0, 0);
final View view = new View(context);
view.setLayoutParams(layoutParams);
validateColor(view, viewData);
view.setFocusable(true);
return new LiteAppNativeViewHolder() {
@Override
public View getNativeView() {
return view;
}
};
}
}
| 695 |
2,151 | <filename>components/invalidation/impl/profile_invalidation_provider.h
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_INVALIDATION_IMPL_PROFILE_INVALIDATION_PROVIDER_H_
#define COMPONENTS_INVALIDATION_IMPL_PROFILE_INVALIDATION_PROVIDER_H_
#include <memory>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "components/keyed_service/core/keyed_service.h"
namespace user_prefs {
class PrefRegistrySyncable;
}
namespace invalidation {
class InvalidationService;
// A KeyedService that owns an InvalidationService.
class ProfileInvalidationProvider : public KeyedService {
public:
explicit ProfileInvalidationProvider(
std::unique_ptr<InvalidationService> invalidation_service);
~ProfileInvalidationProvider() override;
InvalidationService* GetInvalidationService();
// KeyedService:
void Shutdown() override;
// Register prefs to be used by per-Profile instances of this class which
// store invalidation state in Profile prefs.
static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
private:
std::unique_ptr<InvalidationService> invalidation_service_;
DISALLOW_COPY_AND_ASSIGN(ProfileInvalidationProvider);
};
} // namespace invalidation
#endif // COMPONENTS_INVALIDATION_IMPL_PROFILE_INVALIDATION_PROVIDER_H_
| 436 |
777 | <gh_stars>100-1000
// Copyright 2016 The open-vcdiff Authors. 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.
/* Defined to PROJECT_VERSION from CMakeLists.txt */
#define OPEN_VCDIFF_VERSION "0.8.4"
/* Define to 1 if you have the <ext/rope> header file. */
/* #undef HAVE_EXT_ROPE */
/* Define to 1 if you have the `gettimeofday' function. */
#define HAVE_GETTIMEOFDAY
/* Define to 1 if you have the <malloc.h> header file. */
#define HAVE_MALLOC_H
/* Define to 1 if you have the `memalign' function. */
#define HAVE_MEMALIGN
/* Define to 1 if you have the `mprotect' function. */
#define HAVE_MPROTECT
/* Define to 1 if you have the `posix_memalign' function. */
#define HAVE_POSIX_MEMALIGN
/* Define to 1 if you have the <sys/mman.h> header file. */
#define HAVE_SYS_MMAN_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H
/* Define to 1 if you have the <windows.h> header file. */
/* #undef HAVE_WINDOWS_H */
/* Use custom compare function instead of memcmp */
/* #undef VCDIFF_USE_BLOCK_COMPARE_WORDS */
| 582 |
834 | <reponame>nathanawmk/fboss
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/qsfp_service/lib/QsfpClient.h"
DEFINE_int32(
qsfp_service_recv_timeout,
5000,
"Receive timeout(ms) from qsfp service");
namespace facebook {
namespace fboss {
// static
apache::thrift::RpcOptions QsfpClient::getRpcOptions() {
apache::thrift::RpcOptions opts;
opts.setTimeout(std::chrono::milliseconds(FLAGS_qsfp_service_recv_timeout));
return opts;
}
} // namespace fboss
} // namespace facebook
| 268 |
335 | {
"word": "Hurt",
"definitions": [
"Cause pain or injury to.",
"(of a part of the body) suffer pain.",
"Cause distress to.",
"(of a person) feel distress.",
"Be detrimental to.",
"Have a pressing need for."
],
"parts-of-speech": "Verb"
} | 134 |
389 | <gh_stars>100-1000
/*
* Copyright 2014 <NAME>, Inc.
*/
package gw.internal.gosu.parser.statements;
import gw.internal.gosu.parser.Statement;
import gw.lang.parser.statements.IClassFileStatement;
import gw.lang.parser.statements.INamespaceStatement;
import gw.lang.parser.statements.ITerminalStatement;
import gw.lang.reflect.module.IModule;
import gw.util.StringPool;
/**
*/
public class NamespaceStatement extends Statement implements INamespaceStatement
{
private String _strNamespace;
public NamespaceStatement()
{
}
public String getNamespace()
{
return _strNamespace;
}
public void setNamespace( String strNamespace )
{
_strNamespace = strNamespace == null ? null : StringPool.get( strNamespace );
}
public Object execute()
{
// no-op
return Statement.VOID_RETURN_VALUE;
}
@Override
protected ITerminalStatement getLeastSignificantTerminalStatement_internal( boolean[] bAbsolute )
{
bAbsolute[0] = false;
return null;
}
@Override
public boolean isNoOp()
{
return true;
}
@Override
public String toString()
{
return "package " + getNamespace();
}
public IModule getModule() {
IClassFileStatement cfs = (IClassFileStatement) getParent();
return cfs.getGosuClass().getTypeLoader().getModule();
}
}
| 446 |
565 |
// The files containing the tree of child classes of |DynamicFrame| must be
// included in the order of inheritance to avoid circular dependencies. This
// class will end up being reincluded as part of the implementation of its
// parent.
#ifndef PRINCIPIA_PHYSICS_DYNAMIC_FRAME_HPP_
#include "physics/dynamic_frame.hpp"
#else
#ifndef PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_
#define PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_
#include "base/not_null.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/rotation.hpp"
#include "physics/continuous_trajectory.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "physics/dynamic_frame.hpp"
#include "physics/ephemeris.hpp"
#include "physics/massive_body.hpp"
#include "physics/rigid_motion.hpp"
#include "quantities/named_quantities.hpp"
namespace principia {
namespace physics {
namespace internal_body_centred_body_direction_dynamic_frame {
using base::not_null;
using geometry::AngularVelocity;
using geometry::Instant;
using geometry::Position;
using geometry::Rotation;
using geometry::Vector;
using quantities::Acceleration;
// The origin of the frame is the centre of mass of the primary body. The X
// axis points to the secondary. The Y axis is in the direction of the velocity
// of the secondary with respect to the primary. The Z axis is in the direction
// of the angular velocity of the system. The basis has the same orientation as
// |InertialFrame|.
template<typename InertialFrame, typename ThisFrame>
class BodyCentredBodyDirectionDynamicFrame
: public DynamicFrame<InertialFrame, ThisFrame> {
static_assert(ThisFrame::may_rotate);
public:
BodyCentredBodyDirectionDynamicFrame(
not_null<Ephemeris<InertialFrame> const*> ephemeris,
not_null<MassiveBody const*> primary,
not_null<MassiveBody const*> secondary);
BodyCentredBodyDirectionDynamicFrame(
not_null<Ephemeris<InertialFrame> const*> ephemeris,
std::function<Trajectory<InertialFrame> const&()> primary_trajectory,
not_null<MassiveBody const*> secondary);
not_null<MassiveBody const*> primary() const;
not_null<MassiveBody const*> secondary() const;
Instant t_min() const override;
Instant t_max() const override;
RigidMotion<InertialFrame, ThisFrame> ToThisFrameAtTime(
Instant const& t) const override;
void WriteToMessage(
not_null<serialization::DynamicFrame*> message) const override;
static not_null<std::unique_ptr<BodyCentredBodyDirectionDynamicFrame>>
ReadFromMessage(
not_null<Ephemeris<InertialFrame> const*> ephemeris,
serialization::BodyCentredBodyDirectionDynamicFrame const& message);
private:
Vector<Acceleration, InertialFrame> GravitationalAcceleration(
Instant const& t,
Position<InertialFrame> const& q) const override;
AcceleratedRigidMotion<InertialFrame, ThisFrame> MotionOfThisFrame(
Instant const& t) const override;
// Fills |rotation| with the rotation that maps the basis of |InertialFrame|
// to the basis of |ThisFrame|. Fills |angular_velocity| with the
// corresponding angular velocity.
static void ComputeAngularDegreesOfFreedom(
DegreesOfFreedom<InertialFrame> const& primary_degrees_of_freedom,
DegreesOfFreedom<InertialFrame> const& secondary_degrees_of_freedom,
Rotation<InertialFrame, ThisFrame>& rotation,
AngularVelocity<InertialFrame>& angular_velocity);
not_null<Ephemeris<InertialFrame> const*> const ephemeris_;
MassiveBody const* const primary_;
not_null<MassiveBody const*> const secondary_;
std::function<Vector<Acceleration, InertialFrame>(
Position<InertialFrame> const& position,
Instant const& t)> compute_gravitational_acceleration_on_primary_;
std::function<Trajectory<InertialFrame> const&()> const primary_trajectory_;
not_null<ContinuousTrajectory<InertialFrame> const*> const
secondary_trajectory_;
};
} // namespace internal_body_centred_body_direction_dynamic_frame
using internal_body_centred_body_direction_dynamic_frame::
BodyCentredBodyDirectionDynamicFrame;
} // namespace physics
} // namespace principia
#include "physics/body_centred_body_direction_dynamic_frame_body.hpp"
#endif // PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_
#endif // PRINCIPIA_PHYSICS_DYNAMIC_FRAME_HPP_
| 1,506 |
1,062 | //
// Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <AppKit/NSToolbarItem.h>
@class NSSegmentedControl;
@interface MUISegmentedToolbarItem : NSToolbarItem
{
}
- (void)sizeToFit; // IMP=0x000000000001e3a5
- (void)validate; // IMP=0x000000000001e264
@property(retain) NSSegmentedControl *view;
- (id)initWithDictionaryRepresentation:(id)arg1; // IMP=0x000000000001df7b
@end
| 188 |
5,169 | {
"name": "ViVuTech",
"version": "1.0.6",
"summary": "Small test to test code sharing via cocoapods.",
"description": "This is some superl oco framework that was made by kevin vugts.",
"homepage": "https://github.com/trunghieunt/ViVuTech",
"license": "MIT",
"authors": {
"Hieu": "<EMAIL>"
},
"platforms": {
"ios": "11.0"
},
"source": {
"git": "https://github.com/trunghieunt/ViVuTech.git",
"tag": "1.0.6"
},
"source_files": "ViVuTech/**/*",
"exclude_files": "ViVuTech/**/*.plist",
"swift_versions": "5.0",
"swift_version": "5.0"
}
| 254 |
2,360 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyHdbscan(PythonPackage):
"""HDBSCAN - Hierarchical Density-Based Spatial Clustering of
Applications with Noise. Performs DBSCAN over varying epsilon
values and integrates the result to find a clustering that gives
the best stability over epsilon. This allows HDBSCAN to find
clusters of varying densities (unlike DBSCAN), and be more robust
to parameter selection. In practice this means that HDBSCAN
returns a good clustering straight away with little or no
parameter tuning -- and the primary parameter, minimum cluster
size, is intuitive and easy to select. HDBSCAN is ideal for
exploratory data analysis; it's a fast and robust algorithm that
you can trust to return meaningful clusters (if there are any)."""
homepage = "https://github.com/scikit-learn-contrib/hdbscan"
url = "https://github.com/scikit-learn-contrib/hdbscan/archive/0.8.26.tar.gz"
version('0.8.26', sha256='2fd10906603b6565ee138656b6d59df3494c03c5e8099aede400d50b13af912b')
depends_on('py-setuptools', type='build')
depends_on('[email protected]:', type='build')
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'))
depends_on('py-joblib', type=('build', 'run'))
depends_on('py-six', type=('build', 'run'))
| 553 |
14,668 | <reponame>chromium/chromium
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_PAGE_INFO_SAFETY_TIP_PAGE_INFO_BUBBLE_VIEW_H_
#define CHROME_BROWSER_UI_VIEWS_PAGE_INFO_SAFETY_TIP_PAGE_INFO_BUBBLE_VIEW_H_
#include "base/memory/raw_ptr.h"
#include "chrome/browser/reputation/safety_tip_ui.h"
#include "chrome/browser/ui/views/page_info/page_info_bubble_view_base.h"
#include "components/security_state/core/security_state.h"
#include "content/public/browser/visibility.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/styled_label.h"
namespace content {
class WebContents;
} // namespace content
namespace gfx {
class Rect;
} // namespace gfx
namespace views {
class Link;
class View;
class Widget;
} // namespace views
// When Chrome displays a safety tip, we create a stripped-down bubble view
// without all of the details. Safety tip info is still displayed in the usual
// PageInfoBubbleView, just less prominently.
class SafetyTipPageInfoBubbleView : public PageInfoBubbleViewBase {
public:
// If |anchor_view| is nullptr, or has no Widget, |parent_window| may be
// provided to ensure this bubble is closed when the parent closes.
//
// |close_callback| will be called when the bubble is destroyed. The argument
// indicates what action (if any) the user took to close the bubble.
SafetyTipPageInfoBubbleView(
views::View* anchor_view,
const gfx::Rect& anchor_rect,
gfx::NativeView parent_window,
content::WebContents* web_contents,
security_state::SafetyTipStatus safety_tip_status,
const GURL& suggested_url,
base::OnceCallback<void(SafetyTipInteraction)> close_callback);
SafetyTipPageInfoBubbleView(const SafetyTipPageInfoBubbleView&) = delete;
SafetyTipPageInfoBubbleView& operator=(const SafetyTipPageInfoBubbleView&) =
delete;
~SafetyTipPageInfoBubbleView() override;
// views::WidgetObserver:
void OnWidgetDestroying(views::Widget* widget) override;
private:
friend class SafetyTipPageInfoBubbleViewBrowserTest;
void ExecuteLeaveCommand();
void OpenHelpCenter();
views::Button* GetLeaveButtonForTesting() { return leave_button_; }
// WebContentsObserver:
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
void OnVisibilityChanged(content::Visibility visibility) override;
void PrimaryPageChanged(content::Page& page) override;
void DidChangeVisibleSecurityState() override;
const security_state::SafetyTipStatus safety_tip_status_;
// The URL of the page the Safety Tip suggests you intended to go to, when
// applicable (for SafetyTipStatus::kLookalike).
const GURL suggested_url_;
raw_ptr<views::Link> info_link_ = nullptr;
raw_ptr<views::MdTextButton> leave_button_ = nullptr;
base::OnceCallback<void(SafetyTipInteraction)> close_callback_;
SafetyTipInteraction action_taken_ = SafetyTipInteraction::kNoAction;
};
// Creates and returns a safety tip bubble. Used in unit tests.
PageInfoBubbleViewBase* CreateSafetyTipBubbleForTesting(
gfx::NativeView parent_view,
content::WebContents* web_contents,
security_state::SafetyTipStatus safety_tip_status,
const GURL& suggested_url,
base::OnceCallback<void(SafetyTipInteraction)> close_callback);
#endif // CHROME_BROWSER_UI_VIEWS_PAGE_INFO_SAFETY_TIP_PAGE_INFO_BUBBLE_VIEW_H_
| 1,137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.